
# Objective - Fixes #17960 ## Solution - Followed the [edition upgrade guide](https://doc.rust-lang.org/edition-guide/editions/transitioning-an-existing-project-to-a-new-edition.html) ## Testing - CI --- ## Summary of Changes ### Documentation Indentation When using lists in documentation, proper indentation is now linted for. This means subsequent lines within the same list item must start at the same indentation level as the item. ```rust /* Valid */ /// - Item 1 /// Run-on sentence. /// - Item 2 struct Foo; /* Invalid */ /// - Item 1 /// Run-on sentence. /// - Item 2 struct Foo; ``` ### Implicit `!` to `()` Conversion `!` (the never return type, returned by `panic!`, etc.) no longer implicitly converts to `()`. This is particularly painful for systems with `todo!` or `panic!` statements, as they will no longer be functions returning `()` (or `Result<()>`), making them invalid systems for functions like `add_systems`. The ideal fix would be to accept functions returning `!` (or rather, _not_ returning), but this is blocked on the [stabilisation of the `!` type itself](https://doc.rust-lang.org/std/primitive.never.html), which is not done. The "simple" fix would be to add an explicit `-> ()` to system signatures (e.g., `|| { todo!() }` becomes `|| -> () { todo!() }`). However, this is _also_ banned, as there is an existing lint which (IMO, incorrectly) marks this as an unnecessary annotation. So, the "fix" (read: workaround) is to put these kinds of `|| -> ! { ... }` closuers into variables and give the variable an explicit type (e.g., `fn()`). ```rust // Valid let system: fn() = || todo!("Not implemented yet!"); app.add_systems(..., system); // Invalid app.add_systems(..., || todo!("Not implemented yet!")); ``` ### Temporary Variable Lifetimes The order in which temporary variables are dropped has changed. The simple fix here is _usually_ to just assign temporaries to a named variable before use. ### `gen` is a keyword We can no longer use the name `gen` as it is reserved for a future generator syntax. This involved replacing uses of the name `gen` with `r#gen` (the raw-identifier syntax). ### Formatting has changed Use statements have had the order of imports changed, causing a substantial +/-3,000 diff when applied. For now, I have opted-out of this change by amending `rustfmt.toml` ```toml style_edition = "2021" ``` This preserves the original formatting for now, reducing the size of this PR. It would be a simple followup to update this to 2024 and run `cargo fmt`. ### New `use<>` Opt-Out Syntax Lifetimes are now implicitly included in RPIT types. There was a handful of instances where it needed to be added to satisfy the borrow checker, but there may be more cases where it _should_ be added to avoid breakages in user code. ### `MyUnitStruct { .. }` is an invalid pattern Previously, you could match against unit structs (and unit enum variants) with a `{ .. }` destructuring. This is no longer valid. ### Pretty much every use of `ref` and `mut` are gone Pattern binding has changed to the point where these terms are largely unused now. They still serve a purpose, but it is far more niche now. ### `iter::repeat(...).take(...)` is bad New lint recommends using the more explicit `iter::repeat_n(..., ...)` instead. ## Migration Guide The lifetimes of functions using return-position impl-trait (RPIT) are likely _more_ conservative than they had been previously. If you encounter lifetime issues with such a function, please create an issue to investigate the addition of `+ use<...>`. ## Notes - Check the individual commits for a clearer breakdown for what _actually_ changed. --------- Co-authored-by: François Mockers <francois.mockers@vleue.com>
220 lines
6.8 KiB
Rust
220 lines
6.8 KiB
Rust
//! Demonstrates how to observe life-cycle triggers as well as define custom ones.
|
|
|
|
use bevy::{
|
|
platform_support::collections::{HashMap, HashSet},
|
|
prelude::*,
|
|
};
|
|
use rand::{Rng, SeedableRng};
|
|
use rand_chacha::ChaCha8Rng;
|
|
|
|
fn main() {
|
|
App::new()
|
|
.add_plugins(DefaultPlugins)
|
|
.init_resource::<SpatialIndex>()
|
|
.add_systems(Startup, setup)
|
|
.add_systems(Update, (draw_shapes, handle_click))
|
|
// Observers are systems that run when an event is "triggered". This observer runs whenever
|
|
// `ExplodeMines` is triggered.
|
|
.add_observer(
|
|
|trigger: Trigger<ExplodeMines>,
|
|
mines: Query<&Mine>,
|
|
index: Res<SpatialIndex>,
|
|
mut commands: Commands| {
|
|
// You can access the trigger data via the `Observer`
|
|
let event = trigger.event();
|
|
// Access resources
|
|
for e in index.get_nearby(event.pos) {
|
|
// Run queries
|
|
let mine = mines.get(e).unwrap();
|
|
if mine.pos.distance(event.pos) < mine.size + event.radius {
|
|
// And queue commands, including triggering additional events
|
|
// Here we trigger the `Explode` event for entity `e`
|
|
commands.trigger_targets(Explode, e);
|
|
}
|
|
}
|
|
},
|
|
)
|
|
// This observer runs whenever the `Mine` component is added to an entity, and places it in a simple spatial index.
|
|
.add_observer(on_add_mine)
|
|
// This observer runs whenever the `Mine` component is removed from an entity (including despawning it)
|
|
// and removes it from the spatial index.
|
|
.add_observer(on_remove_mine)
|
|
.run();
|
|
}
|
|
|
|
#[derive(Component)]
|
|
struct Mine {
|
|
pos: Vec2,
|
|
size: f32,
|
|
}
|
|
|
|
impl Mine {
|
|
fn random(rand: &mut ChaCha8Rng) -> Self {
|
|
Mine {
|
|
pos: Vec2::new(
|
|
(rand.r#gen::<f32>() - 0.5) * 1200.0,
|
|
(rand.r#gen::<f32>() - 0.5) * 600.0,
|
|
),
|
|
size: 4.0 + rand.r#gen::<f32>() * 16.0,
|
|
}
|
|
}
|
|
}
|
|
|
|
#[derive(Event)]
|
|
struct ExplodeMines {
|
|
pos: Vec2,
|
|
radius: f32,
|
|
}
|
|
|
|
#[derive(Event)]
|
|
struct Explode;
|
|
|
|
fn setup(mut commands: Commands) {
|
|
commands.spawn(Camera2d);
|
|
commands.spawn((
|
|
Text::new(
|
|
"Click on a \"Mine\" to trigger it.\n\
|
|
When it explodes it will trigger all overlapping mines.",
|
|
),
|
|
Node {
|
|
position_type: PositionType::Absolute,
|
|
top: Val::Px(12.),
|
|
left: Val::Px(12.),
|
|
..default()
|
|
},
|
|
));
|
|
|
|
let mut rng = ChaCha8Rng::seed_from_u64(19878367467713);
|
|
|
|
commands
|
|
.spawn(Mine::random(&mut rng))
|
|
// Observers can watch for events targeting a specific entity.
|
|
// This will create a new observer that runs whenever the Explode event
|
|
// is triggered for this spawned entity.
|
|
.observe(explode_mine);
|
|
|
|
// We want to spawn a bunch of mines. We could just call the code above for each of them.
|
|
// That would create a new observer instance for every Mine entity. Having duplicate observers
|
|
// generally isn't worth worrying about as the overhead is low. But if you want to be maximally efficient,
|
|
// you can reuse observers across entities.
|
|
//
|
|
// First, observers are actually just entities with the Observer component! The `observe()` functions
|
|
// you've seen so far in this example are just shorthand for manually spawning an observer.
|
|
let mut observer = Observer::new(explode_mine);
|
|
|
|
// As we spawn entities, we can make this observer watch each of them:
|
|
for _ in 0..1000 {
|
|
let entity = commands.spawn(Mine::random(&mut rng)).id();
|
|
observer.watch_entity(entity);
|
|
}
|
|
|
|
// By spawning the Observer component, it becomes active!
|
|
commands.spawn(observer);
|
|
}
|
|
|
|
fn on_add_mine(
|
|
trigger: Trigger<OnAdd, Mine>,
|
|
query: Query<&Mine>,
|
|
mut index: ResMut<SpatialIndex>,
|
|
) {
|
|
let mine = query.get(trigger.target()).unwrap();
|
|
let tile = (
|
|
(mine.pos.x / CELL_SIZE).floor() as i32,
|
|
(mine.pos.y / CELL_SIZE).floor() as i32,
|
|
);
|
|
index.map.entry(tile).or_default().insert(trigger.target());
|
|
}
|
|
|
|
// Remove despawned mines from our index
|
|
fn on_remove_mine(
|
|
trigger: Trigger<OnRemove, Mine>,
|
|
query: Query<&Mine>,
|
|
mut index: ResMut<SpatialIndex>,
|
|
) {
|
|
let mine = query.get(trigger.target()).unwrap();
|
|
let tile = (
|
|
(mine.pos.x / CELL_SIZE).floor() as i32,
|
|
(mine.pos.y / CELL_SIZE).floor() as i32,
|
|
);
|
|
index.map.entry(tile).and_modify(|set| {
|
|
set.remove(&trigger.target());
|
|
});
|
|
}
|
|
|
|
fn explode_mine(trigger: Trigger<Explode>, query: Query<&Mine>, mut commands: Commands) {
|
|
// If a triggered event is targeting a specific entity you can access it with `.target()`
|
|
let id = trigger.target();
|
|
let Some(mut entity) = commands.get_entity(id) else {
|
|
return;
|
|
};
|
|
info!("Boom! {} exploded.", id.index());
|
|
entity.despawn();
|
|
let mine = query.get(id).unwrap();
|
|
// Trigger another explosion cascade.
|
|
commands.trigger(ExplodeMines {
|
|
pos: mine.pos,
|
|
radius: mine.size,
|
|
});
|
|
}
|
|
|
|
// Draw a circle for each mine using `Gizmos`
|
|
fn draw_shapes(mut gizmos: Gizmos, mines: Query<&Mine>) {
|
|
for mine in &mines {
|
|
gizmos.circle_2d(
|
|
mine.pos,
|
|
mine.size,
|
|
Color::hsl((mine.size - 4.0) / 16.0 * 360.0, 1.0, 0.8),
|
|
);
|
|
}
|
|
}
|
|
|
|
// Trigger `ExplodeMines` at the position of a given click
|
|
fn handle_click(
|
|
mouse_button_input: Res<ButtonInput<MouseButton>>,
|
|
camera: Single<(&Camera, &GlobalTransform)>,
|
|
windows: Query<&Window>,
|
|
mut commands: Commands,
|
|
) {
|
|
let Ok(windows) = windows.get_single() else {
|
|
return;
|
|
};
|
|
|
|
let (camera, camera_transform) = *camera;
|
|
if let Some(pos) = windows
|
|
.cursor_position()
|
|
.and_then(|cursor| camera.viewport_to_world(camera_transform, cursor).ok())
|
|
.map(|ray| ray.origin.truncate())
|
|
{
|
|
if mouse_button_input.just_pressed(MouseButton::Left) {
|
|
commands.trigger(ExplodeMines { pos, radius: 1.0 });
|
|
}
|
|
}
|
|
}
|
|
|
|
#[derive(Resource, Default)]
|
|
struct SpatialIndex {
|
|
map: HashMap<(i32, i32), HashSet<Entity>>,
|
|
}
|
|
|
|
/// Cell size has to be bigger than any `TriggerMine::radius`
|
|
const CELL_SIZE: f32 = 64.0;
|
|
|
|
impl SpatialIndex {
|
|
// Lookup all entities within adjacent cells of our spatial index
|
|
fn get_nearby(&self, pos: Vec2) -> Vec<Entity> {
|
|
let tile = (
|
|
(pos.x / CELL_SIZE).floor() as i32,
|
|
(pos.y / CELL_SIZE).floor() as i32,
|
|
);
|
|
let mut nearby = Vec::new();
|
|
for x in -1..2 {
|
|
for y in -1..2 {
|
|
if let Some(mines) = self.map.get(&(tile.0 + x, tile.1 + y)) {
|
|
nearby.extend(mines.iter());
|
|
}
|
|
}
|
|
}
|
|
nearby
|
|
}
|
|
}
|