Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,11 +66,16 @@ git push origin v0.1.0
Changes that land in the main branch after phases C–E (`0.4.0`) go here.

### Added
- An anti-aliasing pass in the camera's picture (the manual's "The picture"): `picture.anti_aliasing: Some(Fxaa)` or
`Some(Smaa)` in the `camera` content puts Bevy's `Fxaa` (its defaults) or `Smaa` (`High`) on the world cameras, for a
camera SSAO took MSAA from; taking it out gives the camera back its own. `AntiAliasing`. Off by default. The view
model's camera over an HDR world camera keeps Bevy's 4x MSAA of its own (it has its own texture there).
- Ambient occlusion in the camera's picture (the manual's "The picture"): `picture.ssao: Some((quality, radius, thickness))`
in the `camera` content gives the world cameras Bevy's `ScreenSpaceAmbientOcclusion` (`SsaoTuning`, `SsaoQuality::{Low,
Medium, High, Ultra}`), with the depth and normal prepasses it needs and `Msaa::Off` while it is on (Bevy draws no SSAO
under MSAA); taking it out gives the camera back its own SSAO, MSAA and prepasses. The view model's camera follows the
world camera's MSAA and has no SSAO. Off by default.
world camera's MSAA (its own 4x over an HDR world camera, whose texture it does not share) and has no SSAO. Off by
default.
- A shadow budget in views (the manual's "Lights and colour grading (F13)"): `graphics.shadow_views` (0 to 384, default 0)
counts the shadow budget in shadow views, a point light 6 and a spot 1, the nearest first, and replaces
`graphics.shadow_lights` while above 0. The `lights` query says the budget in views, how many are taken and, for a light
Expand Down Expand Up @@ -403,6 +408,13 @@ Changes that land in the main branch after phases C–E (`0.4.0`) go here.
and the timing `field_timing` (`#[ignore]`) in `physics/world.rs`.

### Fixed
- The first-person arms under an HDR world camera (a `picture.bloom`): the view model's camera drew in HDR into the world
camera's texture after its tone mapping and grade, with neither, so a grade's exposure brightened the world and left
the arms that many stops darker (1.7 in a game's tunnels). It now draws without HDR whatever the world camera does, tone
mapped and graded (the exposure) in its materials' shaders as over a camera without HDR; over an HDR one it draws into a
texture of its own, cleared to nothing, laid over the world's finished picture with premultiplied alpha (Bevy's
`CameraOutputMode`). The arms look the same with a bloom and without; the bloom and the rest of an HDR grade are the
world's alone. Tested on a GPU (`first_person::the_arms_are_drawn_alike_over_a_world_camera_with_hdr_and_without`).
- Colour grading said every field of a grade is drawn; Bevy draws only a grade's `exposure` on a camera that does not draw
in HDR (it grades in each material's shader there), and the rest (`temperature`, `tint`, `hue_deg`, `saturation`,
`contrast`, `lift`, `gamma`, `gain`) only in HDR, in its tone mapping pass. A grade tuned without HDR therefore changed
Expand Down
81 changes: 79 additions & 2 deletions crates/sandbox/tests/sandbox/first_person.rs
Original file line number Diff line number Diff line change
Expand Up @@ -356,7 +356,8 @@ fn ssao_from_the_camera_content_draws_through_the_first_person_cameras_and_goes_
let occluded = drawn(&mut app, &picture);
let world = app.world();
assert!(world.get::<ScreenSpaceAmbientOcclusion>(camera).is_some() && world.get::<NormalPrepass>(camera).is_some());
assert_eq!((msaa(&app, camera), msaa(&app, view_model)), (Some(Msaa::Off), Some(Msaa::Off)), "both cameras without MSAA");
// The sandbox's camera draws in HDR (its bloom): the arms are drawn into a texture of their own, with MSAA of their own.
assert_eq!((msaa(&app, camera), msaa(&app, view_model)), (Some(Msaa::Off), Some(Msaa::Sample4)), "the world camera without MSAA, the arms with");
assert!(world.get::<ScreenSpaceAmbientOcclusion>(view_model).is_none(), "the arms have no SSAO of their own");
let luma = |[r, g, b]: [f64; 3]| 0.2126 * r + 0.7152 * g + 0.0722 * b;
let (w, h) = (plain.width(), plain.height());
Expand All @@ -379,7 +380,7 @@ fn ssao_from_the_camera_content_draws_through_the_first_person_cameras_and_goes_
settle(&mut app, 30);
let back = drawn(&mut app, &picture);
assert!(app.world().get::<ScreenSpaceAmbientOcclusion>(camera).is_none());
assert_eq!((msaa(&app, camera), msaa(&app, view_model)), (own, own), "the MSAA the camera had, on both");
assert_eq!((msaa(&app, camera), msaa(&app, view_model)), (own, Some(Msaa::Sample4)), "the MSAA the camera had, and the arms' own");
assert!(mean_difference(&plain, &back) < 1.0, "the plain picture again: {:.3}", mean_difference(&plain, &back));
}

Expand Down Expand Up @@ -439,3 +440,79 @@ fn a_grade_draws_its_exposure_alone_without_hdr_and_all_of_it_in_hdr() {
assert_eq!(said_hdr.as_deref(), Some(" drawn: all of it (the camera draws in HDR)"));
assert!(alike(brighter_ldr, brighter_hdr), "and an exposure is drawn alike in both: {brighter_ldr:.1?} and {brighter_hdr:.1?}");
}

/// The arms are drawn alike over a world camera with HDR (a bloom) and without: the view model's camera draws without
/// HDR either way, tone mapped and graded (its exposure) in its shaders, into a texture of its own laid over the world's
/// picture. (Until it did, an HDR world camera drew the arms after its tone mapping and grade, with neither: a grade's
/// exposure of 1.7 stops brightened the world and left the arms 1.7 stops darker.)
#[test]
#[ignore = "needs a GPU, or a software one (WGPU_FORCE_FALLBACK_ADAPTER=1): cargo test -p sandbox --test sandbox -- --ignored first_person"]
fn the_arms_are_drawn_alike_over_a_world_camera_with_hdr_and_without() {
use shards::motion::camera::{BloomComposite, BloomTuning, Grading};

use crate::offscreen::block;

let mut app = offscreen_app();
let picture = app.world().resource::<Offscreen>().image.clone();
step(&mut app, 30);
look_down_through_the_eye(&mut app);
settle(&mut app, 200);
let brighter = Grading { exposure: 1.7, ..default() };
let bloom = Some(BloomTuning { intensity: 0.1, threshold: 1.0, composite: BloomComposite::Additive, ..default() });
// The picture with this bloom and this grade, and with the view model or without.
let take = |app: &mut App, name: &str, bloom: &Option<BloomTuning>, arms: bool| {
let mut tuning = app.world_mut().resource_mut::<CameraTuning>();
(tuning.picture.bloom, tuning.picture.grading) = (bloom.clone(), Some(brighter.clone()));
tuning.first_person.view_model = arms.then(|| "arms".into());
settle(app, 30);
shot_to(app, name);
capture_stable(app, &picture)
};
let ldr = take(&mut app, "arms-ldr", &None, true);
let hdr = take(&mut app, "arms-hdr", &bloom, true);
let hdr_bare = take(&mut app, "arms-hdr-no-view-model", &bloom, false);
let (arms_ldr, arms_hdr) = (block(&ldr, 230, 440, 870, 280), block(&hdr, 230, 440, 870, 280));
let (world_ldr, world_hdr) = (block(&ldr, 300, 200, 980, 200), block(&hdr, 300, 200, 980, 200));
eprintln!("the arms' mean colour: {arms_ldr:.1?} without HDR, {arms_hdr:.1?} in HDR; the world above them {world_ldr:.1?} and {world_hdr:.1?}");
let alike = |a: [f64; 3], b: [f64; 3], by: f64| (0..3).all(|c| (a[c] - b[c]).abs() < by);
assert!(alike(arms_ldr, arms_hdr, 3.0), "the arms are drawn alike: {arms_ldr:.1?} and {arms_hdr:.1?}");
assert!(alike(world_ldr, world_hdr, 1.5), "and the world above them: {world_ldr:.1?} and {world_hdr:.1?}");
let arms = changed(&hdr, &hdr_bare, (230, 440, 870, 280));
let world = changed(&hdr, &hdr_bare, (300, 200, 980, 200));
assert!(arms > 5000 && world < 50, "in HDR the arms are laid over the world, which shows round them: {arms} pixels differ below, {world} above");
}

/// The content's anti-aliasing pass draws over SSAO, which took the camera's MSAA: the edges change, the picture's
/// light does not, and taking it out gives the picture back.
#[test]
#[ignore = "needs a GPU, or a software one (WGPU_FORCE_FALLBACK_ADAPTER=1): cargo test -p sandbox --test sandbox -- --ignored first_person"]
fn the_contents_anti_aliasing_smooths_the_edges_of_a_picture_without_msaa() {
use shards::motion::camera::{AntiAliasing, SsaoQuality, SsaoTuning};

use crate::offscreen::block;

let mut app = offscreen_app();
let picture = app.world().resource::<Offscreen>().image.clone();
step(&mut app, 30);
look_down_through_the_eye(&mut app);
settle(&mut app, 200);
let take = |app: &mut App, name: &str, aa: Option<AntiAliasing>| {
let mut tuning = app.world_mut().resource_mut::<CameraTuning>();
tuning.picture.ssao = Some(SsaoTuning { quality: SsaoQuality::Medium, radius: 0.5, ..default() });
tuning.picture.anti_aliasing = aa;
settle(app, 30);
shot_to(app, name);
capture_stable(app, &picture)
};
let bare = take(&mut app, "ssao-no-aa", None);
let smaa = take(&mut app, "ssao-smaa", Some(AntiAliasing::Smaa));
let fxaa = take(&mut app, "ssao-fxaa", Some(AntiAliasing::Fxaa));
let again = take(&mut app, "ssao-no-aa-again", None);
let (w, h) = (bare.width(), bare.height());
let (by_smaa, by_fxaa, back) = (changed(&bare, &smaa, (0, 0, w, h)), changed(&bare, &fxaa, (0, 0, w, h)), changed(&bare, &again, (0, 0, w, h)));
let (light, light_smaa) = (block(&bare, 0, 0, w, h), block(&smaa, 0, 0, w, h));
eprintln!("anti-aliasing over SSAO: SMAA changed {by_smaa} pixels, FXAA {by_fxaa}, none again {back}; mean {light:.1?} and {light_smaa:.1?}");
assert!(by_smaa > 100 && by_fxaa > 100, "each pass changes the edges: {by_smaa} and {by_fxaa} pixels");
assert!((0..3).all(|c| (light[c] - light_smaa[c]).abs() < 1.0), "and not the light: {light:.1?} and {light_smaa:.1?}");
assert!(back < 50, "taken out, the picture is as it was: {back} pixels differ");
}
28 changes: 25 additions & 3 deletions crates/shards/tests/action_render/view_model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -240,11 +240,33 @@ fn a_world_camera_that_grades_in_its_shaders_hands_its_grade_to_the_view_model_c
app.update();
assert_eq!(grade_of(&app, vm), ColorGrading::default(), "and ungraded when the world is");

// An HDR camera grades the finished picture, which the second camera draws over (with no tone mapping of its own, so no grade).
app.world_mut().entity_mut(camera).insert((Hdr, grade));
// Over an HDR camera the second one still draws without HDR, graded and tone mapped in its shaders as before, into a
// texture of its own (cleared to nothing) that is laid over the world's finished picture.
use shards::bevy::camera::{CameraOutputMode, ClearColorConfig};
use shards::bevy::render::view::Tonemapping;
app.world_mut().entity_mut(camera).insert((Hdr, grade.clone(), Tonemapping::TonyMcMapface));
app.update();
app.update();
assert_eq!(grade_of(&app, vm), ColorGrading::default(), "under HDR the view model is drawn over the graded picture, ungraded");
assert_eq!(grade_of(&app, vm), grade, "under HDR the view model is graded like the world still");
let world = app.world();
assert!(world.get::<Hdr>(vm).is_none(), "and draws without HDR");
assert_eq!(world.get::<Tonemapping>(vm), Some(&Tonemapping::TonyMcMapface), "tone mapped as the world is, in its shaders");
use shards::bevy::render::view::Msaa;
assert_eq!(world.get::<Msaa>(vm), Some(&Msaa::Sample4), "with MSAA of its own");
let cam = world.get::<Camera>(vm).unwrap();
assert!(matches!(cam.clear_color, ClearColorConfig::Custom(c) if c == Color::NONE), "its own texture starts empty: {:?}", cam.clear_color);
assert!(
matches!(cam.output_mode, CameraOutputMode::Write { blend_state: Some(_), clear_color: ClearColorConfig::None }),
"and is laid over the world's picture: {:?}",
cam.output_mode
);

// Without HDR again: the shared texture, loaded as the world drew it.
app.world_mut().entity_mut(camera).remove::<Hdr>();
app.update();
app.update();
let cam = app.world().get::<Camera>(vm).unwrap();
assert!(matches!(cam.clear_color, ClearColorConfig::None) && matches!(cam.output_mode, CameraOutputMode::Write { blend_state: None, .. }));
}

#[test]
Expand Down
62 changes: 45 additions & 17 deletions crates/shards_action/src/render/view_model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,15 @@
//! (the shake, the bob and the lean included), one `order` above it, with the `view_model` definition's
//! own field of view and near plane. It draws [`VIEW_MODEL_LAYER`] alone and loads what the world camera
//! drew, clearing only the depth (`Camera3d`'s default), so the model is drawn over the world and never
//! inside a wall. It mirrors the world camera's HDR, anti-aliasing and tone mapping, so that the two
//! inside a wall. It mirrors the world camera's anti-aliasing, tone mapping and grade, so that the two
//! share one main texture. The UI goes to the camera that draws last, so the HUD is over the arms.
//! - **Over an HDR world camera** (a bloom) it still draws without HDR, as it does over one without: its
//! materials tone map in their shaders and take the world camera's grade (its exposure; [`ColorGrading`]
//! is drawn in full only in HDR), so the arms are drawn as they were before the world went HDR. The two
//! formats cannot share a texture: the view model draws into its own, cleared to nothing, and that is laid
//! over the world's finished picture (premultiplied alpha, [`CameraOutputMode`]), with Bevy's 4x MSAA of
//! its own whatever the world camera has (SSAO turns the world's off). An HDR view model drawn into the
//! world's texture would come after the world's tone mapping and grade, and be drawn with neither.
//! - **The rig** ([`ViewModelRig`]) is a child of the camera: an [`Animated`] root that [`ShowsBody`] of
//! the looked-through body, so the bridge animates it from that body's actions, with a [`GltfModel`] below.
//! Which definition it is follows the body's moveset each frame, so a weapon switch swaps it; an edit of
Expand All @@ -15,9 +22,10 @@
//! prop the bridge mounts), cast no shadow and are never culled by their (possibly stale) bounds.

use bevy::camera::visibility::{NoFrustumCulling, RenderLayers, VisibilitySystems};
use bevy::camera::{Camera, Camera3d, ClearColorConfig, Hdr, PerspectiveProjection, Projection};
use bevy::camera::{Camera, Camera3d, CameraOutputMode, ClearColorConfig, Hdr, PerspectiveProjection, Projection};
use bevy::light::NotShadowCaster;
use bevy::prelude::*;
use bevy::render::render_resource::BlendState;
use bevy::render::view::{ColorGrading, Msaa, Tonemapping};
use shards_content::ContentDb;
use shards_core::LocalPlayer;
Expand Down Expand Up @@ -75,6 +83,15 @@ fn views_exist(first: Query<(), With<FirstPersonCamera>>, views: Query<(), With<
!first.is_empty() || !views.is_empty()
}

/// Whether two clear colours are the same (Bevy's `ClearColorConfig` has no `PartialEq`).
fn same_clear(a: &ClearColorConfig, b: &ClearColorConfig) -> bool {
match (a, b) {
(ClearColorConfig::Default, ClearColorConfig::Default) | (ClearColorConfig::None, ClearColorConfig::None) => true,
(ClearColorConfig::Custom(x), ClearColorConfig::Custom(y)) => x == y,
_ => false,
}
}

/// The view model a body shows now: its moveset's, else the camera content's default. `None`: no
/// view model (the body has none to show, or the definition is missing).
pub fn view_model_of<'a>(db: &'a ContentDb, tuning: &'a CameraTuning, moveset: Option<&str>) -> Option<(&'a str, &'a ViewModelDef)> {
Expand Down Expand Up @@ -126,28 +143,42 @@ fn sync_view_model(
let (fov, near) = (def.fov_deg.to_radians(), def.near);
let projection = Projection::Perspective(PerspectiveProjection { fov, near, ..default() });
let right_projection = |p: &Projection| matches!(p, Projection::Perspective(p) if (p.fov - fov).abs() < 1e-6 && (p.near - near).abs() < 1e-9);
// An HDR world camera has tone mapped what it drew; the view model is drawn over that as it is.
let tone = if hdr { Some(Tonemapping::None) } else { tonemapping.copied() };
// A camera that does not draw in HDR tone maps (and grades, F13) in each material's shader, so the view model's own
// camera wants the world camera's grade to match; an HDR one grades the finished picture, which this camera draws over.
let grading = if hdr { None } else { world_grading.cloned() };
// The view model never draws in HDR: it tone maps (and grades, F13) in its materials' shaders, with the world
// camera's tone mapping and grade, so the arms are drawn alike over a world camera with HDR and without.
let (tone, grading) = (tonemapping.copied(), world_grading.cloned());
// Sharing a texture, the two must have the same MSAA. Over an HDR camera the view model has a texture of its own
// and keeps Bevy's 4x MSAA for the arms, though the world camera may have none (SSAO turns it off).
let msaa = if hdr { Some(&Msaa::Sample4) } else { msaa };
// Over a world camera without HDR it draws into the same texture, over what the world drew. Over an HDR one (whose
// texture is of another format) it draws into its own, cleared to nothing, and lays that over the world's picture.
let (clear, output) = if hdr {
let blend = CameraOutputMode::Write { blend_state: Some(BlendState::PREMULTIPLIED_ALPHA_BLENDING), clear_color: ClearColorConfig::None };
(ClearColorConfig::Custom(Color::NONE), blend)
} else {
(ClearColorConfig::None, CameraOutputMode::default())
};
let same_output = |a: &CameraOutputMode| match (a, &output) {
(CameraOutputMode::Write { blend_state: x, clear_color: c }, CameraOutputMode::Write { blend_state: y, clear_color: d }) => x == y && same_clear(c, d),
(CameraOutputMode::Skip, CameraOutputMode::Skip) => true,
_ => false,
};
let camera = match existing {
Some((camera, _, mut cam, mut proj, has_hdr, has_msaa, has_tone, has_grading)) => {
let active = world_camera.is_active && !in_shot;
if cam.order != world_camera.order + 1 || cam.is_active != active {
cam.order = world_camera.order + 1;
cam.is_active = active;
}
if !same_clear(&cam.clear_color, &clear) || !same_output(&cam.output_mode) {
cam.clear_color = clear;
cam.output_mode = output;
}
if !right_projection(&proj) {
*proj = projection;
}
let mut e = commands.entity(camera);
if has_hdr != hdr {
if hdr {
e.insert(Hdr);
} else {
e.remove::<Hdr>();
}
if has_hdr {
e.remove::<Hdr>();
}
if has_msaa.copied() != msaa.copied()
&& let Some(msaa) = msaa
Expand All @@ -172,15 +203,12 @@ fn sync_view_model(
Name::new("view model camera"),
ViewModelCamera,
Camera3d::default(),
Camera { order: world_camera.order + 1, is_active: world_camera.is_active && !in_shot, clear_color: ClearColorConfig::None, ..default() },
Camera { order: world_camera.order + 1, is_active: world_camera.is_active && !in_shot, clear_color: clear, output_mode: output, ..default() },
projection,
RenderLayers::layer(VIEW_MODEL_LAYER),
Transform::IDENTITY,
ChildOf(world),
));
if hdr {
e.insert(Hdr);
}
if let Some(msaa) = msaa {
e.insert(*msaa);
}
Expand Down
Loading
Loading