mirror of
https://github.com/bevyengine/bevy
synced 2024-11-10 15:14:50 +00:00
f487407e07
This adds "high level camera driven rendering" to Bevy. The goal is to give users more control over what gets rendered (and where) without needing to deal with render logic. This will make scenarios like "render to texture", "multiple windows", "split screen", "2d on 3d", "3d on 2d", "pass layering", and more significantly easier. Here is an [example of a 2d render sandwiched between two 3d renders (each from a different perspective)](https://gist.github.com/cart/4fe56874b2e53bc5594a182fc76f4915): ![image](https://user-images.githubusercontent.com/2694663/168411086-af13dec8-0093-4a84-bdd4-d4362d850ffa.png) Users can now spawn a camera, point it at a RenderTarget (a texture or a window), and it will "just work". Rendering to a second window is as simple as spawning a second camera and assigning it to a specific window id: ```rust // main camera (main window) commands.spawn_bundle(Camera2dBundle::default()); // second camera (other window) commands.spawn_bundle(Camera2dBundle { camera: Camera { target: RenderTarget::Window(window_id), ..default() }, ..default() }); ``` Rendering to a texture is as simple as pointing the camera at a texture: ```rust commands.spawn_bundle(Camera2dBundle { camera: Camera { target: RenderTarget::Texture(image_handle), ..default() }, ..default() }); ``` Cameras now have a "render priority", which controls the order they are drawn in. If you want to use a camera's output texture as a texture in the main pass, just set the priority to a number lower than the main pass camera (which defaults to `0`). ```rust // main pass camera with a default priority of 0 commands.spawn_bundle(Camera2dBundle::default()); commands.spawn_bundle(Camera2dBundle { camera: Camera { target: RenderTarget::Texture(image_handle.clone()), priority: -1, ..default() }, ..default() }); commands.spawn_bundle(SpriteBundle { texture: image_handle, ..default() }) ``` Priority can also be used to layer to cameras on top of each other for the same RenderTarget. This is what "2d on top of 3d" looks like in the new system: ```rust commands.spawn_bundle(Camera3dBundle::default()); commands.spawn_bundle(Camera2dBundle { camera: Camera { // this will render 2d entities "on top" of the default 3d camera's render priority: 1, ..default() }, ..default() }); ``` There is no longer the concept of a global "active camera". Resources like `ActiveCamera<Camera2d>` and `ActiveCamera<Camera3d>` have been replaced with the camera-specific `Camera::is_active` field. This does put the onus on users to manage which cameras should be active. Cameras are now assigned a single render graph as an "entry point", which is configured on each camera entity using the new `CameraRenderGraph` component. The old `PerspectiveCameraBundle` and `OrthographicCameraBundle` (generic on camera marker components like Camera2d and Camera3d) have been replaced by `Camera3dBundle` and `Camera2dBundle`, which set 3d and 2d default values for the `CameraRenderGraph` and projections. ```rust // old 3d perspective camera commands.spawn_bundle(PerspectiveCameraBundle::default()) // new 3d perspective camera commands.spawn_bundle(Camera3dBundle::default()) ``` ```rust // old 2d orthographic camera commands.spawn_bundle(OrthographicCameraBundle::new_2d()) // new 2d orthographic camera commands.spawn_bundle(Camera2dBundle::default()) ``` ```rust // old 3d orthographic camera commands.spawn_bundle(OrthographicCameraBundle::new_3d()) // new 3d orthographic camera commands.spawn_bundle(Camera3dBundle { projection: OrthographicProjection { scale: 3.0, scaling_mode: ScalingMode::FixedVertical, ..default() }.into(), ..default() }) ``` Note that `Camera3dBundle` now uses a new `Projection` enum instead of hard coding the projection into the type. There are a number of motivators for this change: the render graph is now a part of the bundle, the way "generic bundles" work in the rust type system prevents nice `..default()` syntax, and changing projections at runtime is much easier with an enum (ex for editor scenarios). I'm open to discussing this choice, but I'm relatively certain we will all come to the same conclusion here. Camera2dBundle and Camera3dBundle are much clearer than being generic on marker components / using non-default constructors. If you want to run a custom render graph on a camera, just set the `CameraRenderGraph` component: ```rust commands.spawn_bundle(Camera3dBundle { camera_render_graph: CameraRenderGraph::new(some_render_graph_name), ..default() }) ``` Just note that if the graph requires data from specific components to work (such as `Camera3d` config, which is provided in the `Camera3dBundle`), make sure the relevant components have been added. Speaking of using components to configure graphs / passes, there are a number of new configuration options: ```rust commands.spawn_bundle(Camera3dBundle { camera_3d: Camera3d { // overrides the default global clear color clear_color: ClearColorConfig::Custom(Color::RED), ..default() }, ..default() }) commands.spawn_bundle(Camera3dBundle { camera_3d: Camera3d { // disables clearing clear_color: ClearColorConfig::None, ..default() }, ..default() }) ``` Expect to see more of the "graph configuration Components on Cameras" pattern in the future. By popular demand, UI no longer requires a dedicated camera. `UiCameraBundle` has been removed. `Camera2dBundle` and `Camera3dBundle` now both default to rendering UI as part of their own render graphs. To disable UI rendering for a camera, disable it using the CameraUi component: ```rust commands .spawn_bundle(Camera3dBundle::default()) .insert(CameraUi { is_enabled: false, ..default() }) ``` ## Other Changes * The separate clear pass has been removed. We should revisit this for things like sky rendering, but I think this PR should "keep it simple" until we're ready to properly support that (for code complexity and performance reasons). We can come up with the right design for a modular clear pass in a followup pr. * I reorganized bevy_core_pipeline into Core2dPlugin and Core3dPlugin (and core_2d / core_3d modules). Everything is pretty much the same as before, just logically separate. I've moved relevant types (like Camera2d, Camera3d, Camera3dBundle, Camera2dBundle) into their relevant modules, which is what motivated this reorganization. * I adapted the `scene_viewer` example (which relied on the ActiveCameras behavior) to the new system. I also refactored bits and pieces to be a bit simpler. * All of the examples have been ported to the new camera approach. `render_to_texture` and `multiple_windows` are now _much_ simpler. I removed `two_passes` because it is less relevant with the new approach. If someone wants to add a new "layered custom pass with CameraRenderGraph" example, that might fill a similar niche. But I don't feel much pressure to add that in this pr. * Cameras now have `target_logical_size` and `target_physical_size` fields, which makes finding the size of a camera's render target _much_ simpler. As a result, the `Assets<Image>` and `Windows` parameters were removed from `Camera::world_to_screen`, making that operation much more ergonomic. * Render order ambiguities between cameras with the same target and the same priority now produce a warning. This accomplishes two goals: 1. Now that there is no "global" active camera, by default spawning two cameras will result in two renders (one covering the other). This would be a silent performance killer that would be hard to detect after the fact. By detecting ambiguities, we can provide a helpful warning when this occurs. 2. Render order ambiguities could result in unexpected / unpredictable render results. Resolving them makes sense. ## Follow Up Work * Per-Camera viewports, which will make it possible to render to a smaller area inside of a RenderTarget (great for something like splitscreen) * Camera-specific MSAA config (should use the same "overriding" pattern used for ClearColor) * Graph Based Camera Ordering: priorities are simple, but they make complicated ordering constraints harder to express. We should consider adopting a "graph based" camera ordering model with "before" and "after" relationships to other cameras (or build it "on top" of the priority system). * Consider allowing graphs to run subgraphs from any nest level (aka a global namespace for graphs). Right now the 2d and 3d graphs each need their own UI subgraph, which feels "fine" in the short term. But being able to share subgraphs between other subgraphs seems valuable. * Consider splitting `bevy_core_pipeline` into `bevy_core_2d` and `bevy_core_3d` packages. Theres a shared "clear color" dependency here, which would need a new home.
253 lines
10 KiB
Rust
253 lines
10 KiB
Rust
//! Demonstrates rotating entities in 2D using quaternions.
|
|
|
|
use bevy::{
|
|
math::{const_vec2, Vec3Swizzles},
|
|
prelude::*,
|
|
time::FixedTimestep,
|
|
};
|
|
|
|
const TIME_STEP: f32 = 1.0 / 60.0;
|
|
const BOUNDS: Vec2 = const_vec2!([1200.0, 640.0]);
|
|
|
|
fn main() {
|
|
App::new()
|
|
.add_plugins(DefaultPlugins)
|
|
.add_startup_system(setup)
|
|
.add_system_set(
|
|
SystemSet::new()
|
|
.with_run_criteria(FixedTimestep::step(TIME_STEP as f64))
|
|
.with_system(player_movement_system)
|
|
.with_system(snap_to_player_system)
|
|
.with_system(rotate_to_player_system),
|
|
)
|
|
.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_bundle(Camera2dBundle::default());
|
|
|
|
let horizontal_margin = BOUNDS.x / 4.0;
|
|
let vertical_margin = BOUNDS.y / 4.0;
|
|
|
|
// player controlled ship
|
|
commands
|
|
.spawn_bundle(SpriteBundle {
|
|
texture: ship_handle,
|
|
..default()
|
|
})
|
|
.insert(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_bundle(SpriteBundle {
|
|
texture: enemy_a_handle.clone(),
|
|
transform: Transform::from_xyz(0.0 - horizontal_margin, 0.0, 0.0),
|
|
..default()
|
|
})
|
|
.insert(SnapToPlayer);
|
|
commands
|
|
.spawn_bundle(SpriteBundle {
|
|
texture: enemy_a_handle,
|
|
transform: Transform::from_xyz(0.0, 0.0 - vertical_margin, 0.0),
|
|
..default()
|
|
})
|
|
.insert(SnapToPlayer);
|
|
|
|
// enemy that rotates to face the player enemy spawns on the top and right
|
|
commands
|
|
.spawn_bundle(SpriteBundle {
|
|
texture: enemy_b_handle.clone(),
|
|
transform: Transform::from_xyz(0.0 + horizontal_margin, 0.0, 0.0),
|
|
..default()
|
|
})
|
|
.insert(RotateToPlayer {
|
|
rotation_speed: f32::to_radians(45.0), // degrees per second
|
|
});
|
|
commands
|
|
.spawn_bundle(SpriteBundle {
|
|
texture: enemy_b_handle,
|
|
transform: Transform::from_xyz(0.0, 0.0 + vertical_margin, 0.0),
|
|
..default()
|
|
})
|
|
.insert(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;
|
|
}
|
|
|
|
// create the change in rotation around the Z axis (perpendicular to the 2D plane of the screen)
|
|
let rotation_delta = Quat::from_rotation_z(rotation_factor * ship.rotation_speed * TIME_STEP);
|
|
// update the ship rotation with our rotation delta
|
|
transform.rotation *= rotation_delta;
|
|
|
|
// 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 query.iter_mut() {
|
|
// 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, Vec3::from((to_player, 0.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 query.iter_mut() {
|
|
// 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);
|
|
|
|
// get the quaternion to rotate from the current enemy facing direction towards the
|
|
// direction facing the player
|
|
let rotation_delta = Quat::from_rotation_z(rotation_angle);
|
|
|
|
// rotate the enemy to face the player
|
|
enemy_transform.rotation *= rotation_delta;
|
|
}
|
|
}
|