 206c7ce219
			
		
	
	
		206c7ce219
		
	
	
	
	
		
			
			Huge thanks to @maniwani, @devil-ira, @hymm, @cart, @superdump and @jakobhellermann for the help with this PR. # Objective - Followup #6587. - Minimal integration for the Stageless Scheduling RFC: https://github.com/bevyengine/rfcs/pull/45 ## Solution - [x] Remove old scheduling module - [x] Migrate new methods to no longer use extension methods - [x] Fix compiler errors - [x] Fix benchmarks - [x] Fix examples - [x] Fix docs - [x] Fix tests ## Changelog ### Added - a large number of methods on `App` to work with schedules ergonomically - the `CoreSchedule` enum - `App::add_extract_system` via the `RenderingAppExtension` trait extension method - the private `prepare_view_uniforms` system now has a public system set for scheduling purposes, called `ViewSet::PrepareUniforms` ### Removed - stages, and all code that mentions stages - states have been dramatically simplified, and no longer use a stack - `RunCriteriaLabel` - `AsSystemLabel` trait - `on_hierarchy_reports_enabled` run criteria (now just uses an ad hoc resource checking run condition) - systems in `RenderSet/Stage::Extract` no longer warn when they do not read data from the main world - `RunCriteriaLabel` - `transform_propagate_system_set`: this was a nonstandard pattern that didn't actually provide enough control. The systems are already `pub`: the docs have been updated to ensure that the third-party usage is clear. ### Changed - `System::default_labels` is now `System::default_system_sets`. - `App::add_default_labels` is now `App::add_default_sets` - `CoreStage` and `StartupStage` enums are now `CoreSet` and `StartupSet` - `App::add_system_set` was renamed to `App::add_systems` - The `StartupSchedule` label is now defined as part of the `CoreSchedules` enum - `.label(SystemLabel)` is now referred to as `.in_set(SystemSet)` - `SystemLabel` trait was replaced by `SystemSet` - `SystemTypeIdLabel<T>` was replaced by `SystemSetType<T>` - The `ReportHierarchyIssue` resource now has a public constructor (`new`), and implements `PartialEq` - Fixed time steps now use a schedule (`CoreSchedule::FixedTimeStep`) rather than a run criteria. - Adding rendering extraction systems now panics rather than silently failing if no subapp with the `RenderApp` label is found. - the `calculate_bounds` system, with the `CalculateBounds` label, is now in `CoreSet::Update`, rather than in `CoreSet::PostUpdate` before commands are applied. - `SceneSpawnerSystem` now runs under `CoreSet::Update`, rather than `CoreStage::PreUpdate.at_end()`. - `bevy_pbr::add_clusters` is no longer an exclusive system - the top level `bevy_ecs::schedule` module was replaced with `bevy_ecs::scheduling` - `tick_global_task_pools_on_main_thread` is no longer run as an exclusive system. Instead, it has been replaced by `tick_global_task_pools`, which uses a `NonSend` resource to force running on the main thread. ## Migration Guide - Calls to `.label(MyLabel)` should be replaced with `.in_set(MySet)` - Stages have been removed. Replace these with system sets, and then add command flushes using the `apply_system_buffers` exclusive system where needed. - The `CoreStage`, `StartupStage, `RenderStage` and `AssetStage` enums have been replaced with `CoreSet`, `StartupSet, `RenderSet` and `AssetSet`. The same scheduling guarantees have been preserved. - Systems are no longer added to `CoreSet::Update` by default. Add systems manually if this behavior is needed, although you should consider adding your game logic systems to `CoreSchedule::FixedTimestep` instead for more reliable framerate-independent behavior. - Similarly, startup systems are no longer part of `StartupSet::Startup` by default. In most cases, this won't matter to you. - For example, `add_system_to_stage(CoreStage::PostUpdate, my_system)` should be replaced with - `add_system(my_system.in_set(CoreSet::PostUpdate)` - When testing systems or otherwise running them in a headless fashion, simply construct and run a schedule using `Schedule::new()` and `World::run_schedule` rather than constructing stages - Run criteria have been renamed to run conditions. These can now be combined with each other and with states. - Looping run criteria and state stacks have been removed. Use an exclusive system that runs a schedule if you need this level of control over system control flow. - For app-level control flow over which schedules get run when (such as for rollback networking), create your own schedule and insert it under the `CoreSchedule::Outer` label. - Fixed timesteps are now evaluated in a schedule, rather than controlled via run criteria. The `run_fixed_timestep` system runs this schedule between `CoreSet::First` and `CoreSet::PreUpdate` by default. - Command flush points introduced by `AssetStage` have been removed. If you were relying on these, add them back manually. - Adding extract systems is now typically done directly on the main app. Make sure the `RenderingAppExtension` trait is in scope, then call `app.add_extract_system(my_system)`. - the `calculate_bounds` system, with the `CalculateBounds` label, is now in `CoreSet::Update`, rather than in `CoreSet::PostUpdate` before commands are applied. You may need to order your movement systems to occur before this system in order to avoid system order ambiguities in culling behavior. - the `RenderLabel` `AppLabel` was renamed to `RenderApp` for clarity - `App::add_state` now takes 0 arguments: the starting state is set based on the `Default` impl. - Instead of creating `SystemSet` containers for systems that run in stages, simply use `.on_enter::<State::Variant>()` or its `on_exit` or `on_update` siblings. - `SystemLabel` derives should be replaced with `SystemSet`. You will also need to add the `Debug`, `PartialEq`, `Eq`, and `Hash` traits to satisfy the new trait bounds. - `with_run_criteria` has been renamed to `run_if`. Run criteria have been renamed to run conditions for clarity, and should now simply return a bool. - States have been dramatically simplified: there is no longer a "state stack". To queue a transition to the next state, call `NextState::set` ## TODO - [x] remove dead methods on App and World - [x] add `App::add_system_to_schedule` and `App::add_systems_to_schedule` - [x] avoid adding the default system set at inappropriate times - [x] remove any accidental cycles in the default plugins schedule - [x] migrate benchmarks - [x] expose explicit labels for the built-in command flush points - [x] migrate engine code - [x] remove all mentions of stages from the docs - [x] verify docs for States - [x] fix uses of exclusive systems that use .end / .at_start / .before_commands - [x] migrate RenderStage and AssetStage - [x] migrate examples - [x] ensure that transform propagation is exported in a sufficiently public way (the systems are already pub) - [x] ensure that on_enter schedules are run at least once before the main app - [x] re-enable opt-in to execution order ambiguities - [x] revert change to `update_bounds` to ensure it runs in `PostUpdate` - [x] test all examples - [x] unbreak directional lights - [x] unbreak shadows (see 3d_scene, 3d_shape, lighting, transparaency_3d examples) - [x] game menu example shows loading screen and menu simultaneously - [x] display settings menu is a blank screen - [x] `without_winit` example panics - [x] ensure all tests pass - [x] SubApp doc test fails - [x] runs_spawn_local tasks fails - [x] [Fix panic_when_hierachy_cycle test hanging](https://github.com/alice-i-cecile/bevy/pull/120) ## Points of Difficulty and Controversy **Reviewers, please give feedback on these and look closely** 1. Default sets, from the RFC, have been removed. These added a tremendous amount of implicit complexity and result in hard to debug scheduling errors. They're going to be tackled in the form of "base sets" by @cart in a followup. 2. The outer schedule controls which schedule is run when `App::update` is called. 3. I implemented `Label for `Box<dyn Label>` for our label types. This enables us to store schedule labels in concrete form, and then later run them. I ran into the same set of problems when working with one-shot systems. We've previously investigated this pattern in depth, and it does not appear to lead to extra indirection with nested boxes. 4. `SubApp::update` simply runs the default schedule once. This sucks, but this whole API is incomplete and this was the minimal changeset. 5. `time_system` and `tick_global_task_pools_on_main_thread` no longer use exclusive systems to attempt to force scheduling order 6. Implemetnation strategy for fixed timesteps 7. `AssetStage` was migrated to `AssetSet` without reintroducing command flush points. These did not appear to be used, and it's nice to remove these bottlenecks. 8. Migration of `bevy_render/lib.rs` and pipelined rendering. The logic here is unusually tricky, as we have complex scheduling requirements. ## Future Work (ideally before 0.10) - Rename schedule_v3 module to schedule or scheduling - Add a derive macro to states, and likely a `EnumIter` trait of some form - Figure out what exactly to do with the "systems added should basically work by default" problem - Improve ergonomics for working with fixed timesteps and states - Polish FixedTime API to match Time - Rebase and merge #7415 - Resolve all internal ambiguities (blocked on better tools, especially #7442) - Add "base sets" to replace the removed default sets.
		
			
				
	
	
		
			251 lines
		
	
	
		
			9.9 KiB
		
	
	
	
		
			Rust
		
	
	
	
	
	
			
		
		
	
	
			251 lines
		
	
	
		
			9.9 KiB
		
	
	
	
		
			Rust
		
	
	
	
	
	
| //! Demonstrates rotating entities in 2D using quaternions.
 | |
| 
 | |
| use bevy::{math::Vec3Swizzles, prelude::*};
 | |
| 
 | |
| const TIME_STEP: f32 = 1.0 / 60.0;
 | |
| const BOUNDS: Vec2 = Vec2::new(1200.0, 640.0);
 | |
| 
 | |
| fn main() {
 | |
|     App::new()
 | |
|         .add_plugins(DefaultPlugins)
 | |
|         .add_startup_system(setup)
 | |
|         .add_systems_to_schedule(
 | |
|             CoreSchedule::FixedUpdate,
 | |
|             (
 | |
|                 player_movement_system,
 | |
|                 snap_to_player_system,
 | |
|                 rotate_to_player_system,
 | |
|             ),
 | |
|         )
 | |
|         .insert_resource(FixedTime::new_from_secs(TIME_STEP))
 | |
|         .add_system(bevy::window::close_on_esc)
 | |
|         .run();
 | |
| }
 | |
| 
 | |
| /// player component
 | |
| #[derive(Component)]
 | |
| struct Player {
 | |
|     /// linear speed in meters per second
 | |
|     movement_speed: f32,
 | |
|     /// rotation speed in radians per second
 | |
|     rotation_speed: f32,
 | |
| }
 | |
| 
 | |
| /// snap to player ship behavior
 | |
| #[derive(Component)]
 | |
| struct SnapToPlayer;
 | |
| 
 | |
| /// rotate to face player ship behavior
 | |
| #[derive(Component)]
 | |
| struct RotateToPlayer {
 | |
|     /// rotation speed in radians per second
 | |
|     rotation_speed: f32,
 | |
| }
 | |
| 
 | |
| /// Add the game's entities to our world and creates an orthographic camera for 2D rendering.
 | |
| ///
 | |
| /// The Bevy coordinate system is the same for 2D and 3D, in terms of 2D this means that:
 | |
| ///
 | |
| /// * `X` axis goes from left to right (`+X` points right)
 | |
| /// * `Y` axis goes from bottom to top (`+Y` point up)
 | |
| /// * `Z` axis goes from far to near (`+Z` points towards you, out of the screen)
 | |
| ///
 | |
| /// The origin is at the center of the screen.
 | |
| fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
 | |
|     let ship_handle = asset_server.load("textures/simplespace/ship_C.png");
 | |
|     let enemy_a_handle = asset_server.load("textures/simplespace/enemy_A.png");
 | |
|     let enemy_b_handle = asset_server.load("textures/simplespace/enemy_B.png");
 | |
| 
 | |
|     // 2D orthographic camera
 | |
|     commands.spawn(Camera2dBundle::default());
 | |
| 
 | |
|     let horizontal_margin = BOUNDS.x / 4.0;
 | |
|     let vertical_margin = BOUNDS.y / 4.0;
 | |
| 
 | |
|     // player controlled ship
 | |
|     commands.spawn((
 | |
|         SpriteBundle {
 | |
|             texture: ship_handle,
 | |
|             ..default()
 | |
|         },
 | |
|         Player {
 | |
|             movement_speed: 500.0,                  // metres per second
 | |
|             rotation_speed: f32::to_radians(360.0), // degrees per second
 | |
|         },
 | |
|     ));
 | |
| 
 | |
|     // enemy that snaps to face the player spawns on the bottom and left
 | |
|     commands.spawn((
 | |
|         SpriteBundle {
 | |
|             texture: enemy_a_handle.clone(),
 | |
|             transform: Transform::from_xyz(0.0 - horizontal_margin, 0.0, 0.0),
 | |
|             ..default()
 | |
|         },
 | |
|         SnapToPlayer,
 | |
|     ));
 | |
|     commands.spawn((
 | |
|         SpriteBundle {
 | |
|             texture: enemy_a_handle,
 | |
|             transform: Transform::from_xyz(0.0, 0.0 - vertical_margin, 0.0),
 | |
|             ..default()
 | |
|         },
 | |
|         SnapToPlayer,
 | |
|     ));
 | |
| 
 | |
|     // enemy that rotates to face the player enemy spawns on the top and right
 | |
|     commands.spawn((
 | |
|         SpriteBundle {
 | |
|             texture: enemy_b_handle.clone(),
 | |
|             transform: Transform::from_xyz(0.0 + horizontal_margin, 0.0, 0.0),
 | |
|             ..default()
 | |
|         },
 | |
|         RotateToPlayer {
 | |
|             rotation_speed: f32::to_radians(45.0), // degrees per second
 | |
|         },
 | |
|     ));
 | |
|     commands.spawn((
 | |
|         SpriteBundle {
 | |
|             texture: enemy_b_handle,
 | |
|             transform: Transform::from_xyz(0.0, 0.0 + vertical_margin, 0.0),
 | |
|             ..default()
 | |
|         },
 | |
|         RotateToPlayer {
 | |
|             rotation_speed: f32::to_radians(90.0), // degrees per second
 | |
|         },
 | |
|     ));
 | |
| }
 | |
| 
 | |
| /// Demonstrates applying rotation and movement based on keyboard input.
 | |
| fn player_movement_system(
 | |
|     keyboard_input: Res<Input<KeyCode>>,
 | |
|     mut query: Query<(&Player, &mut Transform)>,
 | |
| ) {
 | |
|     let (ship, mut transform) = query.single_mut();
 | |
| 
 | |
|     let mut rotation_factor = 0.0;
 | |
|     let mut movement_factor = 0.0;
 | |
| 
 | |
|     if keyboard_input.pressed(KeyCode::Left) {
 | |
|         rotation_factor += 1.0;
 | |
|     }
 | |
| 
 | |
|     if keyboard_input.pressed(KeyCode::Right) {
 | |
|         rotation_factor -= 1.0;
 | |
|     }
 | |
| 
 | |
|     if keyboard_input.pressed(KeyCode::Up) {
 | |
|         movement_factor += 1.0;
 | |
|     }
 | |
| 
 | |
|     // update the ship rotation around the Z axis (perpendicular to the 2D plane of the screen)
 | |
|     transform.rotate_z(rotation_factor * ship.rotation_speed * TIME_STEP);
 | |
| 
 | |
|     // get the ship's forward vector by applying the current rotation to the ships initial facing vector
 | |
|     let movement_direction = transform.rotation * Vec3::Y;
 | |
|     // get the distance the ship will move based on direction, the ship's movement speed and delta time
 | |
|     let movement_distance = movement_factor * ship.movement_speed * TIME_STEP;
 | |
|     // create the change in translation using the new movement direction and distance
 | |
|     let translation_delta = movement_direction * movement_distance;
 | |
|     // update the ship translation with our new translation delta
 | |
|     transform.translation += translation_delta;
 | |
| 
 | |
|     // bound the ship within the invisible level bounds
 | |
|     let extents = Vec3::from((BOUNDS / 2.0, 0.0));
 | |
|     transform.translation = transform.translation.min(extents).max(-extents);
 | |
| }
 | |
| 
 | |
| /// Demonstrates snapping the enemy ship to face the player ship immediately.
 | |
| fn snap_to_player_system(
 | |
|     mut query: Query<&mut Transform, (With<SnapToPlayer>, Without<Player>)>,
 | |
|     player_query: Query<&Transform, With<Player>>,
 | |
| ) {
 | |
|     let player_transform = player_query.single();
 | |
|     // get the player translation in 2D
 | |
|     let player_translation = player_transform.translation.xy();
 | |
| 
 | |
|     for mut enemy_transform in &mut query {
 | |
|         // get the vector from the enemy ship to the player ship in 2D and normalize it.
 | |
|         let to_player = (player_translation - enemy_transform.translation.xy()).normalize();
 | |
| 
 | |
|         // get the quaternion to rotate from the initial enemy facing direction to the direction
 | |
|         // facing the player
 | |
|         let rotate_to_player = Quat::from_rotation_arc(Vec3::Y, to_player.extend(0.));
 | |
| 
 | |
|         // rotate the enemy to face the player
 | |
|         enemy_transform.rotation = rotate_to_player;
 | |
|     }
 | |
| }
 | |
| 
 | |
| /// Demonstrates rotating an enemy ship to face the player ship at a given rotation speed.
 | |
| ///
 | |
| /// This method uses the vector dot product to determine if the enemy is facing the player and
 | |
| /// if not, which way to rotate to face the player. The dot product on two unit length vectors
 | |
| /// will return a value between -1.0 and +1.0 which tells us the following about the two vectors:
 | |
| ///
 | |
| /// * If the result is 1.0 the vectors are pointing in the same direction, the angle between them
 | |
| ///   is 0 degrees.
 | |
| /// * If the result is 0.0 the vectors are perpendicular, the angle between them is 90 degrees.
 | |
| /// * If the result is -1.0 the vectors are parallel but pointing in opposite directions, the angle
 | |
| ///   between them is 180 degrees.
 | |
| /// * If the result is positive the vectors are pointing in roughly the same direction, the angle
 | |
| ///   between them is greater than 0 and less than 90 degrees.
 | |
| /// * If the result is negative the vectors are pointing in roughly opposite directions, the angle
 | |
| ///   between them is greater than 90 and less than 180 degrees.
 | |
| ///
 | |
| /// It is possible to get the angle by taking the arc cosine (`acos`) of the dot product. It is
 | |
| /// often unnecessary to do this though. Beware than `acos` will return `NaN` if the input is less
 | |
| /// than -1.0 or greater than 1.0. This can happen even when working with unit vectors due to
 | |
| /// floating point precision loss, so it pays to clamp your dot product value before calling
 | |
| /// `acos`.
 | |
| fn rotate_to_player_system(
 | |
|     mut query: Query<(&RotateToPlayer, &mut Transform), Without<Player>>,
 | |
|     player_query: Query<&Transform, With<Player>>,
 | |
| ) {
 | |
|     let player_transform = player_query.single();
 | |
|     // get the player translation in 2D
 | |
|     let player_translation = player_transform.translation.xy();
 | |
| 
 | |
|     for (config, mut enemy_transform) in &mut query {
 | |
|         // get the enemy ship forward vector in 2D (already unit length)
 | |
|         let enemy_forward = (enemy_transform.rotation * Vec3::Y).xy();
 | |
| 
 | |
|         // get the vector from the enemy ship to the player ship in 2D and normalize it.
 | |
|         let to_player = (player_translation - enemy_transform.translation.xy()).normalize();
 | |
| 
 | |
|         // get the dot product between the enemy forward vector and the direction to the player.
 | |
|         let forward_dot_player = enemy_forward.dot(to_player);
 | |
| 
 | |
|         // if the dot product is approximately 1.0 then the enemy is already facing the player and
 | |
|         // we can early out.
 | |
|         if (forward_dot_player - 1.0).abs() < f32::EPSILON {
 | |
|             continue;
 | |
|         }
 | |
| 
 | |
|         // get the right vector of the enemy ship in 2D (already unit length)
 | |
|         let enemy_right = (enemy_transform.rotation * Vec3::X).xy();
 | |
| 
 | |
|         // get the dot product of the enemy right vector and the direction to the player ship.
 | |
|         // if the dot product is negative them we need to rotate counter clockwise, if it is
 | |
|         // positive we need to rotate clockwise. Note that `copysign` will still return 1.0 if the
 | |
|         // dot product is 0.0 (because the player is directly behind the enemy, so perpendicular
 | |
|         // with the right vector).
 | |
|         let right_dot_player = enemy_right.dot(to_player);
 | |
| 
 | |
|         // determine the sign of rotation from the right dot player. We need to negate the sign
 | |
|         // here as the 2D bevy co-ordinate system rotates around +Z, which is pointing out of the
 | |
|         // screen. Due to the right hand rule, positive rotation around +Z is counter clockwise and
 | |
|         // negative is clockwise.
 | |
|         let rotation_sign = -f32::copysign(1.0, right_dot_player);
 | |
| 
 | |
|         // limit rotation so we don't overshoot the target. We need to convert our dot product to
 | |
|         // an angle here so we can get an angle of rotation to clamp against.
 | |
|         let max_angle = forward_dot_player.clamp(-1.0, 1.0).acos(); // clamp acos for safety
 | |
| 
 | |
|         // calculate angle of rotation with limit
 | |
|         let rotation_angle = rotation_sign * (config.rotation_speed * TIME_STEP).min(max_angle);
 | |
| 
 | |
|         // rotate the enemy to face the player
 | |
|         enemy_transform.rotate_z(rotation_angle);
 | |
|     }
 | |
| }
 |