bevy/examples/transforms/global_vs_local_translation.rs
Carter Anderson f487407e07 Camera Driven Rendering (#4745)
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.
2022-06-02 00:12:17 +00:00

191 lines
7.8 KiB
Rust

//! Illustrates the difference between direction of a translation in respect to local object or
//! global object Transform.
use bevy::prelude::*;
// Define a marker for entities that should be changed via their global transform.
#[derive(Component)]
struct ChangeGlobal;
// Define a marker for entities that should be changed via their local transform.
#[derive(Component)]
struct ChangeLocal;
// Define a marker for entities that should move.
#[derive(Component)]
struct Move;
// Define a resource for the current movement direction;
#[derive(Default)]
struct Direction(Vec3);
// Define component to decide when an entity should be ignored by the movement systems.
#[derive(Component)]
struct ToggledBy(KeyCode);
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_startup_system(setup)
.init_resource::<Direction>()
.add_system(move_cubes_according_to_global_transform)
.add_system(move_cubes_according_to_local_transform)
.add_system(update_directional_input)
.add_system(toggle_movement)
.run();
}
// Startup system to setup the scene and spawn all relevant entities.
fn setup(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
asset_server: Res<AssetServer>,
) {
// To show the difference between a local transform (rotation, scale and position in respect to a given entity)
// and global transform (rotation, scale and position in respect to the base coordinate system of the visible scene)
// it's helpful to add multiple entities that are attached to each other.
// This way we'll see that the transform in respect to an entity's parent is different to the
// global transform within the visible scene.
// This example focuses on translation only to clearly demonstrate the differences.
// Spawn a basic cube to have an entity as reference.
let mut main_entity = commands.spawn();
main_entity
.insert_bundle(PbrBundle {
mesh: meshes.add(Mesh::from(shape::Cube { size: 1.0 })),
material: materials.add(Color::YELLOW.into()),
..Default::default()
})
.insert(ChangeGlobal)
.insert(Move)
.insert(ToggledBy(KeyCode::Key1));
// Spawn two entities as children above the original main entity.
// The red entity spawned here will be changed via its global transform
// where the green one will be changed via its local transform.
main_entity.with_children(|child_builder| {
// also see parenting example
child_builder
.spawn_bundle(PbrBundle {
mesh: meshes.add(Mesh::from(shape::Cube { size: 0.5 })),
material: materials.add(Color::RED.into()),
transform: Transform::from_translation(Vec3::Y - Vec3::Z),
..Default::default()
})
.insert(ChangeGlobal)
.insert(Move)
.insert(ToggledBy(KeyCode::Key2));
child_builder
.spawn_bundle(PbrBundle {
mesh: meshes.add(Mesh::from(shape::Cube { size: 0.5 })),
material: materials.add(Color::GREEN.into()),
transform: Transform::from_translation(Vec3::Y + Vec3::Z),
..Default::default()
})
.insert(ChangeLocal)
.insert(Move)
.insert(ToggledBy(KeyCode::Key3));
});
// Spawn a camera looking at the entities to show what's happening in this example.
commands.spawn_bundle(Camera3dBundle {
transform: Transform::from_xyz(0.0, 10.0, 20.0).looking_at(Vec3::ZERO, Vec3::Y),
..Default::default()
});
// Add a light source for better 3d visibility.
commands.spawn_bundle(PointLightBundle {
transform: Transform::from_translation(Vec3::splat(3.0)),
..Default::default()
});
// Add text to explain inputs and what is happening.
commands.spawn_bundle(TextBundle {
text: Text::with_section(
"Press the arrow keys to move the cubes. Toggle movement for yellow (1), red (2) and green (3) cubes via number keys.
Notice how the green cube will translate further in respect to the yellow in contrast to the red cube.
This is due to the use of its LocalTransform that is relative to the yellow cubes transform instead of the GlobalTransform as in the case of the red cube.
The red cube is moved through its GlobalTransform and thus is unaffected by the yellows transform.",
TextStyle {
font: asset_server.load("fonts/FiraSans-Bold.ttf"),
font_size: 22.0,
color: Color::WHITE,
},
TextAlignment {
horizontal: HorizontalAlign::Left,
..Default::default()
},
),
..Default::default()
});
}
// This system will move all cubes that are marked as ChangeGlobal according to their global transform.
fn move_cubes_according_to_global_transform(
mut cubes: Query<&mut GlobalTransform, (With<ChangeGlobal>, With<Move>)>,
direction: Res<Direction>,
timer: Res<Time>,
) {
for mut global_transform in cubes.iter_mut() {
global_transform.translation += direction.0 * timer.delta_seconds();
}
}
// This system will move all cubes that are marked as ChangeLocal according to their local transform.
fn move_cubes_according_to_local_transform(
mut cubes: Query<&mut Transform, (With<ChangeLocal>, With<Move>)>,
direction: Res<Direction>,
timer: Res<Time>,
) {
for mut transform in cubes.iter_mut() {
transform.translation += direction.0 * timer.delta_seconds();
}
}
// This system updates a resource that defines in which direction the cubes should move.
// The direction is defined by the input of arrow keys and is only in left/right and up/down direction.
fn update_directional_input(mut direction: ResMut<Direction>, keyboard_input: Res<Input<KeyCode>>) {
let horizontal_movement = Vec3::X
* (keyboard_input.pressed(KeyCode::Right) as i32
- keyboard_input.pressed(KeyCode::Left) as i32) as f32;
let vertical_movement = Vec3::Y
* (keyboard_input.pressed(KeyCode::Up) as i32
- keyboard_input.pressed(KeyCode::Down) as i32) as f32;
direction.0 = horizontal_movement + vertical_movement;
}
// This system enables and disables the movement for each entity if their assigned key is pressed.
fn toggle_movement(
mut commands: Commands,
movable_entities: Query<(Entity, &Handle<StandardMaterial>, &ToggledBy), With<Move>>,
static_entities: Query<(Entity, &Handle<StandardMaterial>, &ToggledBy), Without<Move>>,
mut materials: ResMut<Assets<StandardMaterial>>,
keyboard_input: Res<Input<KeyCode>>,
) {
// Update the currently movable entities and remove their Move component if the assigned key was pressed to disable their movement.
// This will also make them transparent so they can be identified as 'disabled' in the scene.
for (entity, material_handle, toggled_by) in movable_entities.iter() {
if keyboard_input.just_pressed(toggled_by.0) {
materials
.get_mut(material_handle)
.unwrap()
.base_color
.set_a(0.5);
commands.entity(entity).remove::<Move>();
}
}
// Update the currently non-movable entities and add a Move component if the assigned key was pressed to enable their movement.
// This will also make them opaque so they can be identified as 'enabled' in the scene.
for (entity, material_handle, toggled_by) in static_entities.iter() {
if keyboard_input.just_pressed(toggled_by.0) {
materials
.get_mut(material_handle)
.unwrap()
.base_color
.set_a(1.0);
commands.entity(entity).insert(Move);
}
}
}