The native runtime for three.js: three.js, down to the metal. 45× smaller than Electron, on a Sony PS3, and path-traced at 60 fps on ray-tracing GPUs.
Rust electron-alternativegame-engineglobal-illuminationgraphicsjavascript-runtimemetalpath-tracingray-tracingreal-time-renderingrenderingrustthreejstypescriptvoxelvulkanwebgpuwgpu
Live view: the view's state and the environment beside the scene's data (#131)
Yujia0be0a6f91cd9
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.mdindex be9ec69..bd2a77a 100644--- a/docs/ROADMAP.md+++ b/docs/ROADMAP.md@@ -2560,6 +2560,20 @@ takes one pays is the bake: 0.1 ms for a colour, 6 for a gradient, 47 for an atmthe scene's 0.5 to 0.9 s). No picture changed (render-identity; the live volume tests' own spread is wider thantwo runs show: five runs a side, none differ).+**The view's state and the environment beside the scene's data (2026-11-16, after it).** The live view kept the+scene camera's lens, depth of field and exposure, the preset, and the sky's state in the struct a rebuild replaces+with the scene's data, the fog and the background in the tables beside materials and lights, and wrote each from+two places, the load and an edit, which a test held equal (and found apart once: the emitter cull's cone). They+are two objects of the view now (`live/state.rs`): `ViewState` and `Environment`, each derived whole from the world+by one function, at load and on an edit, and the kernel's parameters each of them says are written by one function+that the build calls too (`Params::set_preset`, `EnvSettings::write`, `SkyBaked::write`). Two change flags that+came to mean the same (the camera's exposure, its depth of field) are one. No behaviour is meant to change, and+one does: after a rebuild that changed the cloud cover, the next commit no longer bakes the sky again.+What other engines do was read first: a scene container without camera, size or post state, size-dependent+buffers and histories owned by the view, and the environment an object of its own are common to all read; which+side the environment hangs on is not (here the scene's, as the scene DSL has it). Still against that: the+per-pixel accumulation buffer is made with the scene's data. Resize moves it to the view.+## 2. Temporal fixesTargets (2026-11-08): bench-temporal, bench-ghosting and their UE MRQ references move to Bistro night (§ 0 step 7); thediff --git a/docs/RUNTIME.md b/docs/RUNTIME.mdindex 4bfbba8..fb2b35c 100644--- a/docs/RUNTIME.md+++ b/docs/RUNTIME.md@@ -46,7 +46,7 @@ runtime, and drives the engine directly, the way a UE game drives its actors:| Engine API | `packages/scene/src/engine.ts` (`Engine`), `renderer/src/script.rs` (`__engine` natives) | Handles (u32) for geometries (typed arrays), textures (asset path, encoded image or RGBA8 pixels), material-function code, materials, objects (group / mesh / model / light / camera) and their transform, visibility, power, light / camera parameters; the environment and render settings. Descriptors are JSON-shaped (`renderer/src/desc.rs`). || Scene binding | `packages/scene/src/engine.ts` `SceneBinding` | Keeps the engine in step with a DSL scene. Objects report their own changes (core.ts change tracking: transforms, visibility, power, shadow flag, mesh geometry / material, add / remove), so a sync visits only what changed. Lights, cameras and materials are compared against what was last sent. || World | `renderer/src/world.rs` | The engine's objects, resources, environment and settings, and what changed since the last commit: parameter changes (power, light / material parameters, environment, camera) or structural ones. Asset paths must stay inside the asset root (game code is untrusted on nodes). |-| Live commit | `renderer/src/live/edits.rs` `LiveCore::commit`, `tables.rs` | Parameter changes rewrite GPU table entries in place (materials, lights, object power, emitter CDF, wetness / rain / fog, camera), and so does hiding or showing a volume, a light without a card or a particle system that is not light-sampled by its own `visible`. What is not the scene's is in place too: the scene camera's lens, depth of field and exposure, which camera is the scene's, fog or a background appearing or going (another variant of the kernel), the render preset, another sky (baked and put in place: `apply_sky`). Anything structural rebuilds the GPU scene from the world, in memory; history survives, validated per pixel. |+| Live commit | `renderer/src/live/edits.rs` `LiveCore::commit`, `tables.rs`, `live/state.rs` | Parameter changes rewrite GPU table entries in place (materials, lights, object power, emitter CDF), and so does hiding or showing a volume, a light without a card or a particle system that is not light-sampled by its own `visible`. What is not the scene's data is held beside it and derived whole from the world, by the same function at load and on an edit (`live/state.rs`): the view's state (`ViewState`: the scene camera's lens, depth of field and exposure, which camera is the scene's, the render preset) and the environment (`Environment`: wetness, rain, fog or a background, appearing or going with another variant of the kernel; its sky, baked and put in place by `apply_sky`). Anything structural rebuilds the GPU scene from the world, in memory; history survives, validated per pixel. || Scene runtime | `renderer/src/script.rs` `ScriptHost` | QuickJS (rquickjs) with no I/O (no fs, network or timers; what needs the outside is asked of the app, "The host channel"). Loads a bundle (one script) or ES modules (`game.js` + `threert-runtime.js`, the cloud layout). Memory capped at 1 GiB. Time budgets: setup 120 s, event 1 s, frame 50 ms; the interrupt handler aborts overruns. Every entry ends by running the promise jobs it left, inside its budget ("Promises", below). The time the engine spends inside a voxel call (`voxelExplode`, `voxelEdit`, `voxelFrame`) is the engine's, not the script's: the deadline moves by it as measured, up to 250 ms an entry; past that it counts against the script, and a voxel call made after the deadline throws "interrupted" at once. A prelude adds `TextEncoder`, `structuredClone`, `atob` and `console`. || Node host | `packages/gameplay/src/node-host.ts` | `globalThis.__threert`: `setup(room, seed)`, `event(type, payload, ts)` (local authority: execute + commit), `commit(writes, seq)` / `setState(state, seq)` (room authority), `state()`, `frame(dt, now)`, `hostMessages(list, ts)` (the app's messages), `sync()` (the engine follows the scene once more: after an entry's promise jobs), and the editor's `outline()`, `inspect(name)`, `edit(name, path, value)`. || World handlers | `packages/gameplay/src/world.ts` | `on[type](world, ev)`: an event handled on this node, changing the scene at once. `WorldContext`: `scene`, `camera`, read-only `state`, `object(id)`, `time`, `now`, `random()`, `emit(type, payload)`. |diff --git a/renderer/src/gpu.rs b/renderer/src/gpu.rsindex f3d96a8..ca29157 100644--- a/renderer/src/gpu.rs+++ b/renderer/src/gpu.rs@@ -1559,8 +1559,18 @@ pub fn huge(groups: [usize; GROUPS], instanced: bool) -> bool {/// Features a scene needs; `THREERT_FEATURES` (bit mask) restricts them for profiling.pub fn features(scene: &Scene, groups: [usize; GROUPS]) -> u32 {- let environment = environment_features(scene.fog.as_ref(), scene.background.is_some(), scene.aerial);- features_of(&scene.materials, environment, !scene.textures.is_empty(), !scene.shaders.is_empty(), groups, instance_features(scene))+ features_of(&scene.materials, scene.environment.features(), !scene.textures.is_empty(), !scene.shaders.is_empty(), groups, instance_features(scene))+}++impl Params {+ /// What the kernel takes from the render preset and the camera's exposure: the bounce limit, the depth Russian+ /// roulette starts at, the firefly clamp on indirect paths (relative to the exposure), energy compensation.+ pub fn set_preset(&mut self, native: &crate::desc::NativePreset, exposure: &crate::desc::Exposure) {+ self.counts[2] = native.max_bounces;+ self.counts[3] = native.russian_roulette_depth;+ self.misc[0] = native.firefly_clamp(exposure);+ self.misc[2] = native.energy_compensation;+ }}/// Kernel features of the environment, which edits change: fog (F_FOG, with lit scattering F_VOLUME), a backgrounddiff --git a/renderer/src/lib.rs b/renderer/src/lib.rsindex da95f69..8b1469e 100644--- a/renderer/src/lib.rs+++ b/renderer/src/lib.rs@@ -622,21 +622,18 @@ pub fn prepare_as(hwrt: bool, units: bool, sc: &mut scene::Scene, timings: &mut// Sky / environment.let t = Instant::now();- let SkyBaked { env, color: sky_color, has_env, sun } = bake_sky(&sc.sky, sc.cloud_cover, sc.camera.position.y.max(0.0));+ let baked = bake_sky(&sc.sky, sc.environment.cloud_cover, sc.camera.position.y.max(0.0));// (The atmosphere's sun: its light's colour is what the bake leaves it.)- if let (Some(i), Some(c)) = (sc.retained.sun.and_then(|s| sc.retained.light_nodes.iter().position(|n| *n == s)), sun) {+ if let (Some(i), Some(c)) = (sc.retained.sun.and_then(|s| sc.retained.light_nodes.iter().position(|n| *n == s)), baked.sun) {sc.lights[i].color = [c.x, c.y, c.z, 0.0];}- let env_cdf = build_env_cdf(&env);+ let env_cdf = build_env_cdf(&baked.env);let procs = [0, sc.procs.len() as u32, sc.gpu_instances.len() as u32, 0];// Environment light sampling (one shadow ray per vertex) is skipped when the sky is negligible next to the emitters- // (night streets): escaping BSDF rays still pick it up, with full MIS weight. The emitters as if all on: a- // time-of-day room loaded by day decides at dusk as one loaded at night does (live/edits.rs `put_sky`).- let env_max = sky_brightest(&env, sky_color);+ // (night streets): escaping BSDF rays still pick it up, with full MIS weight (`SkyBaked::write`). The emitters as+ // if all on: a time-of-day room loaded by day decides at dusk as one loaded at night does (live/edits.rs `put_sky`).let em_area: f32 = emitters[..emitter_tris.len()].iter().map(|e| e[3]).sum();let env_nee_floor = if emitter_tris.is_empty() { 0.0 } else { 0.01 * all_power / em_area.max(1e-6) };- // (A uniform sky is sampled regardless of `env_nee_on`: it reads no table.)- let env_nee = sky_sampled(env_max, env_nee_floor, has_env);// The kernel's light order (`light_order`).let class = light_class;let order = light_order(&sc.lights);@@ -648,8 +645,6 @@ pub fn prepare_as(hwrt: bool, units: bool, sc: &mut scene::Scene, timings: &mutlet first_shadowed = sc.lights.iter().position(|l| class(l) == 2).unwrap_or(sc.lights.len()) as u32;timings.push(("sky_ms".into(), t.elapsed().as_secs_f64() * 1000.0));- let preset = sc.preset.clone();- let fog = fog_params(sc.fog.as_ref());let cam = &sc.camera;let aspect = sc.width as f32 / sc.height as f32;let (lens_radius, focus) = match &cam.dof {@@ -666,16 +661,18 @@ pub fn prepare_as(hwrt: bool, units: bool, sc: &mut scene::Scene, timings: &mutcam_right: [cam.right.x, cam.right.y, cam.right.z, lens_radius],cam_up: [cam.up.x, cam.up.y, cam.up.z, focus],size: [sc.width, sc.height, 0, rng_seed()],- counts: [sc.lights.len() as u32, if total > 0.0 { emitter_tris.len() as u32 } else { 0 }, preset.native.max_bounces, preset.native.russian_roulette_depth],- env: [if has_env { 1.0 } else { 0.0 }, env.width as f32, env.height as f32, -1.0],- misc: [preset.native.firefly_clamp(&cam.exposure), total, preset.native.energy_compensation, 0.0],- sky_color: [sky_color.x, sky_color.y, sky_color.z, 0.0],- counts2: [n_dir, env_nee as u32, 0, first_shadowed],- time: [sc.time, sc.wetness, sc.rain, sc.media.len() as f32],- fog: fog[0],- fog_color: fog[1],- vol: fog[2],- vol2: fog[3],+ // (The preset's and the exposure's: `Params::set_preset`; the sky's: `SkyBaked::write`; the environment's:+ // `EnvSettings::write`. Below.)+ counts: [sc.lights.len() as u32, if total > 0.0 { emitter_tris.len() as u32 } else { 0 }, 0, 0],+ env: [0.0, 0.0, 0.0, -1.0],+ misc: [0.0, total, 0.0, 0.0],+ sky_color: [0.0; 4],+ counts2: [n_dir, 0, 0, first_shadowed],+ time: [sc.time, 0.0, 0.0, sc.media.len() as f32],+ fog: [0.0; 4],+ fog_color: [0.0; 4],+ vol: [0.0; 4],+ vol2: [0.0; 4],raster: [0.0; 4],cache: [0.0; 4],// (z, w: software traversal's units: the top tree's root and their count, as bits; trace_units.wgsl. y is@@ -684,8 +681,8 @@ pub fn prepare_as(hwrt: bool, units: bool, sc: &mut scene::Scene, timings: &mutgroup_first: [[0; 4]; 2],light_lod: [0.0; 4],emit_power: [total, 0.0, 0.0, 0.0],- aerial: sc.aerial,- background: sc.background.map_or([0.0; 4], |b| [b.x, b.y, b.z, 1.0]),+ aerial: [0.0; 4],+ background: [0.0; 4],lod_view: [0.0; 4],ltree: ltree_param,procs,@@ -700,6 +697,10 @@ pub fn prepare_as(hwrt: bool, units: bool, sc: &mut scene::Scene, timings: &mutlive_len: [0; 4],};let mut params = params;+ params.set_preset(&sc.preset.native, &cam.exposure);+ baked.write(&mut params, env_nee_floor);+ sc.environment.write(&mut params);+ let env = baked.env;let mut first = 0u32;for (g, &count) in groups.iter().enumerate() {params.group_first[g / 4][g % 4] = first;@@ -884,6 +885,16 @@ pub fn bake_sky(sky: &scene::SkyData, cloud_cover: f32, altitude: f32) -> SkyBak}}+impl SkyBaked {+ /// The kernel's parameters for it: whether it is a map and its size, a uniform sky's colour, whether it is+ /// light-sampled (`floor`: `Prepared::env_nee_floor`).+ pub fn write(&self, p: &mut gpu::Params, floor: f32) {+ p.env = [if self.has_env { 1.0 } else { 0.0 }, self.env.width as f32, self.env.height as f32, p.env[3]];+ p.sky_color = [self.color.x, self.color.y, self.color.z, 0.0];+ p.counts2[1] = sky_sampled(sky_brightest(&self.env, self.color), floor, self.has_env) as u32;+ }+}+/// The brightest luminance a sky has (its map's texels, its uniform colour).pub fn sky_brightest(env: &gpu::EnvMap, color: Vec3) -> f32 {env.texels.iter().map(|t| 0.2126 * t[0] + 0.7152 * t[1] + 0.0722 * t[2]).fold(0.0f32, f32::max).max(0.2126 * color.x + 0.7152 * color.y + 0.0722 * color.z)diff --git a/renderer/src/live/edits.rs b/renderer/src/live/edits.rsindex d114221..6be8b3d 100644--- a/renderer/src/live/edits.rs+++ b/renderer/src/live/edits.rs@@ -358,7 +358,7 @@ impl LiveCore {if self.sc.tables.add_materials(world, &changes.new_materials) {self.upload_materials();// (A clear coat, an unlit material: the kernel variant with it, compiled once.)- self.sc.up.kernel.features = self.sc.tables.features(self.sc.fixed_features, self.sc.instance_features);+ self.sc.up.kernel.features = self.kernel_features();} else {self.fallback = Some("a new material that cannot be added in place (it emits, is glass or a cutout)".into());self.fallbacks += 1;@@ -533,12 +533,21 @@ impl LiveCore {self.g.set_medium(&self.sc.up, *id, None, Some(o.custom));}}- // Another sky, before the tables take the rest of the environment; one whose map cannot grow in place rebuilds.+ // What is not the scene's data (state.rs), each derived again whole from the world, before the tables' edits. The+ // environment's settings, then its sky (one whose map cannot grow in place rebuilds), then the view (a world+ // that names no camera rebuilds, and the build says so).+ if changes.environment && !changes.structural {+ self.env.settings = scene::EnvSettings::of(world);+ self.env.settings.write(&mut self.sc.base);+ }if changes.sky && !changes.structural && !self.apply_sky(world)? {self.fallback = Some("a sky whose map does not fit the scene's buffers in place".into());self.fallbacks += 1;changes.structural = true;}+ if (changes.camera || changes.view || changes.settings) && !changes.structural && !self.apply_view(world, &changes)? {+ changes.structural = true;+ }let now = shader_time(self.time);let applied = self.sc.tables.apply(world, &changes, now).ok().flatten();let Some(d) = applied else {@@ -546,7 +555,7 @@ impl LiveCore {self.rebuild(world)?;self.rebuild_ms += t.elapsed().as_secs_f32() * 1e3;if changes.camera {- self.cam = self.sc.scene_camera;+ self.cam = self.view.camera;}return Ok(true);};@@ -569,45 +578,51 @@ impl LiveCore {} else if d.deferred {self.send_powers();}- let (e, b) = (&mut self.sc.tables, &mut self.sc.base);- if d.environment {- b.time[1] = e.wetness;- b.time[2] = e.rain;- b.background = e.background.map_or([0.0; 4], |c| [c[0], c[1], c[2], 1.0]);- b.aerial = e.aerial;- [b.fog, b.fog_color, b.vol, b.vol2] = crate::fog_params(e.fog.as_ref());- }- if d.materials || d.environment {+ if d.materials || changes.environment {// (Fog or a background appearing, a clear coat: the kernel's variant with it, compiled once, then cached.)- self.sc.up.kernel.features = e.features(self.sc.fixed_features, self.sc.instance_features);- }- if let Some(c) = e.camera.take() {- self.sc.scene_camera = Camera { pos: c.position, fwd: c.forward, up: c.up, right: c.right, tan_half_fov: c.tan_half_fov };- self.sc.tan_half_fov = c.tan_half_fov;- self.sc.dof = c.dof.clone();- self.cam = self.sc.scene_camera;+ self.sc.up.kernel.features = self.kernel_features();}// Lighting changed: for 45 frames the histories hold HISTORY_LIVE frames at most (`live_lighting`), and where the// change is strong the temporal pass cuts the history locally (anti-lag).- if d.materials || d.lights || d.objects || d.environment {+ if d.materials || d.lights || d.objects || changes.environment {self.lit_changed = self.frame.max(1);}// (A new cloud cover re-bakes the sky and dims the sun as a sun move does.)- if changes.sun || self.sc.tables.cloud_cover != self.sky_cover {- self.sky_cover = self.sc.tables.cloud_cover;+ if changes.sun || self.env.settings.cloud_cover != self.env.sky.cover {+ self.env.sky.cover = self.env.settings.cloud_cover;self.move_sun(world);}- if changes.settings {- self.apply_settings(world)?;+ Ok(false)+ }++ /// The kernel features the scene needs as it is now: what its materials and the environment ask for (edits change+ /// them), with the structural ones the build found (textures, material functions, the traversal groups;+ /// `gpu::instance_features`). A new variant is compiled once, then cached.+ pub(super) fn kernel_features(&self) -> u32 {+ let (textures, functions, groups) = self.sc.fixed_features;+ gpu::features_of(&self.sc.tables.materials, self.env.settings.features(), textures, functions, groups, self.sc.instance_features)+ }++ /// The view's state from the world as it is now (`ViewState::of`: the scene's camera with its lens, depth of field+ /// and exposure; the preset, read again when the settings changed), the kernel's parameters it says, and with+ /// another preset the post passes' settings. The view takes the scene's camera when that moved, changed its lens+ /// or is another one (`Changes::camera`); one its host moved stays through the rest. False: the world names no+ /// camera.+ pub(super) fn apply_view(&mut self, world: &World, ch: &crate::world::Changes) -> Result<bool> {+ let keep = (!ch.settings).then(|| self.view.preset.clone());+ let Some(view) = ViewState::of(world, &self.presets, keep)? else { return Ok(false) };+ self.view = view;+ self.view.write(&mut self.sc.base);+ if ch.settings {+ let preset = self.view.preset.clone();+ self.apply_post(&preset.post);+ self.scene_name = world.settings.name.clone();self.lit_changed = self.frame.max(1);}- if changes.exposure || changes.settings {- self.apply_exposure(world);- }- if changes.dof {- self.sc.dof = world.scene_camera().and_then(|c| c.dof.clone());+ if ch.camera {+ self.cam = self.view.camera;}- Ok(false)+ Ok(true)}/// The atmosphere's sun moved (time of day): its light entry is rewritten now (direction, and its colour through@@ -615,12 +630,11 @@ impl LiveCore {/// move). Lockstep frames wait for the bake, so a lockstep run sees the sky that goes with each sun.pub(super) fn move_sun(&mut self, world: &World) {let Some((id, dir, lux)) = scene::atmosphere_sun(world) else { return };- if self.sc.sky.is_none() {- let (size, alt, floor) = self.sc.sky_inputs;- self.sc.sky = DynamicSky::new(world, size, alt, floor);+ if self.env.sky.worker.is_none() {+ self.env.sky.worker = DynamicSky::new(world, self.env.sky.map, self.env.sky.altitude);}- let Some(sky) = self.sc.sky.as_ref() else { return };- let cover = self.sc.tables.cloud_cover;+ let Some(sky) = self.env.sky.worker.as_ref() else { return };+ let cover = self.env.settings.cloud_cover;let colour = crate::sky::sun_illuminance(&sky.atm, dir, lux, cover);let e = &mut self.sc.tables;if e.set_sun_light(world, id, colour) {@@ -641,17 +655,14 @@ impl LiveCore {/// its own again. False, with nothing changed, when the map's CDF cannot grow in place (`Gpu::put_env`).pub(super) fn apply_sky(&mut self, world: &World) -> Result<bool> {let (sky, sun) = scene::sky_data(world, &self.assets, &|id| world.world_matrix(id))?;- let altitude = world.settings.camera.map_or(self.sc.sky_inputs.1, |id| world.world_matrix(id).w_axis.y.max(0.0));- let cover = world.environment.cloud_cover.clamp(0.0, 1.0);+ let altitude = world.settings.camera.map_or(self.env.sky.altitude, |id| world.world_matrix(id).w_axis.y.max(0.0));+ let cover = self.env.settings.cloud_cover;let baked = crate::bake_sky(&sky, cover, altitude);if !self.g.put_env(&mut self.sc.up, &baked.env, &crate::build_env_cdf(&baked.env)) {return Ok(false);}- let floor = self.sc.sky_inputs.2;- let b = &mut self.sc.base;- b.env = [if baked.has_env { 1.0 } else { 0.0 }, baked.env.width as f32, baked.env.height as f32, b.env[3]];- b.sky_color = [baked.color.x, baked.color.y, baked.color.z, 0.0];- b.counts2[1] = crate::sky_sampled(crate::sky_brightest(&baked.env, baked.color), floor, baked.has_env) as u32;+ let floor = self.env.sky.floor;+ baked.write(&mut self.sc.base, floor);// The lights: what was the sun, and what is.let e = &mut self.sc.tables;let was = std::mem::replace(&mut e.retained.sun, sun);@@ -668,16 +679,14 @@ impl LiveCore {self.sc.up.put_lights(&self.g.queue, &e.lights);}// (The worker that re-bakes a dynamic sky is this sky's no longer: the next move of the sun starts one.)- self.sc.sky = None;- self.sc.sky_inputs = ((baked.env.width, baked.env.height), altitude, floor);- self.sky_cover = cover;+ self.env.sky = SkyState { map: (baked.env.width, baked.env.height), altitude, floor, cover, worker: None };self.lit_changed = self.frame.max(1);Ok(true)}/// A sky the worker thread has baked since the last frame (the newest), into the environment map and its CDF.pub(super) fn take_sky(&mut self) {- let Some(sky) = self.sc.sky.as_ref() else { return };+ let Some(sky) = self.env.sky.worker.as_ref() else { return };let mut last = None;while let Ok(b) = sky.done.try_recv() {last = Some(b);@@ -688,39 +697,16 @@ impl LiveCore {}pub(super) fn put_sky(&mut self, (env, cdf, max): (gpu::EnvMap, Vec<f32>, f32)) {- let Some(sky) = self.sc.sky.as_ref() else { return };// (The worker bakes at the map's size: written in place.)- if !self.g.put_env(&mut self.sc.up, &env, &cdf) {+ if self.env.sky.worker.is_none() || !self.g.put_env(&mut self.sc.up, &env, &cdf) {return;}// As the load decides it: the sky is light-sampled unless it is negligible next to the emitters (night), or a- // baked sky is not light-sampled at all (`env_nee_on`).- self.sc.base.counts2[1] = (max >= sky.env_nee_floor && crate::env_nee_on()) as u32;+ // baked sky is not light-sampled at all (`sky_sampled`).+ self.sc.base.counts2[1] = crate::sky_sampled(max, self.env.sky.floor, true) as u32;self.lit_changed = self.frame.max(1);}- /// The scene camera's exposure (its mode, its values) as a build takes it: what the frame is shown at, the auto- /// exposure's settings, and the kernel's firefly clamp, which is relative to it.- pub(super) fn apply_exposure(&mut self, world: &World) {- let Some(c) = world.scene_camera() else { return };- self.sc.base.misc[0] = self.sc.preset.native.firefly_clamp(&c.exposure);- self.sc.exposure = c.exposure.start();- self.sc.exposure_settings = ExposureSettings::new(&c.exposure, &self.sc.preset.post);- }-- /// The preset, its overrides or the scene's name changed: the kernel parameters a build takes from the preset- /// (bounces, Russian roulette, energy compensation) and the post passes'. (What the preset says of the exposure:- /// `apply_exposure`, after it.)- pub(super) fn apply_settings(&mut self, world: &World) -> Result<()> {- let preset = scene::preset_of(world, &self.presets, None)?;- let b = &mut self.sc.base;- (b.counts[2], b.counts[3], b.misc[2]) = (preset.native.max_bounces, preset.native.russian_roulette_depth, preset.native.energy_compensation);- self.apply_post(&preset.post);- self.sc.preset = preset;- self.scene_name = world.settings.name.clone();- Ok(())- }-/// Moves movable instances: their kernel records (the old transform kept as the previous frame's, for motion/// vectors), their object entries' pivots and their TLAS transforms (hardware traversal; with `build_tlas` it/// rebuilds the TLAS, otherwise the dynamic rebuild that follows does) or their units and the top tree over themdiff --git a/renderer/src/live/frame.rs b/renderer/src/live/frame.rsindex 822a2b2..f255b50 100644--- a/renderer/src/live/frame.rs+++ b/renderer/src/live/frame.rs@@ -512,23 +512,23 @@ impl LiveCore {cur: cam.uniform(self.aspect),prev: self.prev_cam.uniform(self.aspect),size: [w, h, self.frame, self.reset as u32],- misc: [self.sc.exposure, cap, self.vignette, (self.bloom.1.iter().sum::<f32>() > 0.0) as u32 as f32],+ misc: [self.view.exposure, cap, self.vignette, (self.bloom.1.iter().sum::<f32>() > 0.0) as u32 as f32],// misc2.z: motion blur, this frame's motion (pixels) -> blur length. UE (PostProcessMotionBlur.cpp,// UpdateMotionBlurTimeScale) blurs over +- amount / 2 x the motion x (1 / target FPS) / frame time, the// actual frame time without a target. 0 while nothing moves (the pass then costs nothing).misc2: [1.0, SAMPLE_CEILING, if !blur { 0.0 } else if self.blur.1 > 0.0 { self.blur.0 / (self.blur.1 * self.frame_dt.clamp(1.0 / 240.0, 0.25)) } else { self.blur.0 }, spp.max(1) as f32],mode: [self.view_mode, 0, self.live_lighting() as u32, 0],post: self.post,- ae: self.sc.exposure_settings.ae,- ae2: self.sc.exposure_settings.ae2,- ae3: [self.sc.exposure_settings.speed[0], self.sc.exposure_settings.speed[1], self.frame_dt.clamp(1.0 / 240.0, 0.25), (self.reset || self.frame == 0 || exposure_snap()) as u32 as f32],- lx: self.sc.exposure_settings.lx,+ ae: self.view.exposure_settings.ae,+ ae2: self.view.exposure_settings.ae2,+ ae3: [self.view.exposure_settings.speed[0], self.view.exposure_settings.speed[1], self.frame_dt.clamp(1.0 / 240.0, 0.25), (self.reset || self.frame == 0 || exposure_snap()) as u32 as f32],+ lx: self.view.exposure_settings.lx,isz: [iw, ih, self.prev_isz.0, self.prev_isz.1],br: [r[0], r[1], r[2], r[3]],br2: [r[4], r[5], 0.0, 0.0],bt: [t[0], t[1], t[2], t[3]],bt2: [t[4], t[5], 0.0, 0.0],- dof: dof_params(self.sc.dof.as_ref(), cam.tan_half_fov, w, h),+ dof: dof_params(self.view.dof.as_ref(), cam.tan_half_fov, w, h),jit: [jitter.0, jitter.1, 0.0, 0.0],state: [1 - self.frame % 2, 0, 0, 0],lt: [tile_at.0, tile_at.1, 0, layout::light_tiles(iw)],diff --git a/renderer/src/live/inplace_tests.rs b/renderer/src/live/inplace_tests.rsindex 68e5148..51d5165 100644--- a/renderer/src/live/inplace_tests.rs+++ b/renderer/src/live/inplace_tests.rs@@ -54,12 +54,13 @@ fn camera(fov: f32, dof: Option<f32>, exposure: serde_json::Value) -> crate::des/// the view), and what else these edits reach: the lights' table and the sun, the sky's map, what the passes after/// the kernel take. (After a frame: the frame writes the light LOD's reference.)fn state(c: &LiveCore) -> (Vec<u32>, String) {- let s = &c.sc;+ let (s, v, sky) = (&c.sc, &c.view, &c.env.sky);let rest = format!(- "features {:#x} | sun {:?} map {:?} lights {:?} | exposure {} {:?} {:?} {:?} {:?} | lens {} {:?} view {:?} {:?} {} | post {} {:?} {} {:?} {:?} | {}",- s.up.kernel.features, s.tables.retained.sun, s.sky_inputs.0, bytemuck::cast_slice::<_, u32>(&s.tables.lights),- s.exposure, s.exposure_settings.ae, s.exposure_settings.ae2, s.exposure_settings.speed, s.exposure_settings.lx,- s.tan_half_fov, s.dof, s.scene_camera.pos, s.scene_camera.fwd, s.scene_camera.tan_half_fov,+ "features {:#x} | sun {:?} lights {:?} | environment {:?} sky {:?} {} {} | exposure {} {:?} | {:?} {:?} | post {} {:?} {} {:?} {:?} | {}",+ s.up.kernel.features, s.tables.retained.sun, bytemuck::cast_slice::<_, u32>(&s.tables.lights),+ // (Not the altitude the sky was baked for: a view keeps its sky when its camera moves, a build bakes anew.)+ c.env.settings, sky.map, sky.floor, sky.cover,+ v.exposure, v.exposure_settings, v.camera, v.dof,c.post_key, c.bloom, c.vignette, c.post, c.blur, c.scene_name);let camera = (std::mem::offset_of!(gpu::Params, cam_up) + 16) / 4;@@ -185,7 +186,7 @@ fn edits_in_place_leave_what_a_build_does() {let away = Camera { pos: live.cam.pos + Vec3::new(0.5, 0.0, 0.0), ..live.cam };live.cam = away;w.set_camera_desc(6, camera(70.0, Some(3.0), manual(2.0))).unwrap();- assert!(!live.commit(&mut w).unwrap() && live.cam == away && live.sc.dof.is_some(), "a depth of field and an exposure: the view stays");+ assert!(!live.commit(&mut w).unwrap() && live.cam == away && live.view.dof.is_some(), "a depth of field and an exposure: the view stays");w.set_camera_desc(6, camera(40.0, Some(3.0), manual(2.0))).unwrap();- assert!(!live.commit(&mut w).unwrap() && live.cam == live.sc.scene_camera && live.cam != away, "a lens: the view takes the scene's camera");+ assert!(!live.commit(&mut w).unwrap() && live.cam == live.view.camera && live.cam != away, "a lens: the view takes the scene's camera");}diff --git a/renderer/src/live/load.rs b/renderer/src/live/load.rsindex becee5d..8a5ccd8 100644--- a/renderer/src/live/load.rs+++ b/renderer/src/live/load.rs@@ -33,14 +33,6 @@ pub(super) struct LoadedScene {pub(super) base: gpu::Params,/// The live passes' bind groups, a pass each (`Targets::bind_groups`).pub(super) bgs: Vec<wgpu::BindGroup>,- pub(super) exposure: f32,- pub(super) exposure_settings: ExposureSettings,- /// The render preset the kernel's parameters and the post passes' settings were taken from.- pub(super) preset: crate::desc::Preset,- pub(super) tan_half_fov: f32,- pub(super) scene_camera: Camera,- /// The camera's depth of field (UE: off unless it sets a focus distance).- pub(super) dof: Option<crate::desc::Dof>,/// GPU table copies that parameter edits rewrite in place (`commit`).pub(super) tables: tables::Tables,/// CPU copy of the dynamic triangles (posed models: the tail of the GPU triangle order from `dynamic_first`):@@ -50,12 +42,8 @@ pub(super) struct LoadedScene {pub(super) fixed_features: (bool, bool, [usize; crate::GROUPS]),/// Where in-place geometry edits write next (`edit_geometry`); a rebuild starts it afresh.pub(super) edit: EditState,- /// The atmosphere's sky once its sun has moved in place (`move_sun` starts it), and what it bakes with: the- /// environment map's size, the viewer's altitude and the environment's light-sampling floor, as the load had them.- pub(super) sky: Option<DynamicSky>,/// Power edits' emitter rebuilds on a worker (`EmitterWorker`), for scenes with many emitters.pub(super) emit: Option<EmitterWorker>,- pub(super) sky_inputs: ((u32, u32), f32, f32),/// For materials that start emitting (`add_material_emitters`): their flattened static triangles' runs (`prepare`)/// and the flattened triangles' build indices in traversal order (positions in `tris`).pub(super) mat_runs: std::collections::HashMap<u32, Vec<[u32; 3]>>,@@ -75,12 +63,10 @@ pub(super) struct DynamicSky {/// (sun direction, sun illuminance above the atmosphere, cloud cover)pub(super) ask: mpsc::Sender<(glam::Vec3, glam::Vec3, f32)>,pub(super) done: mpsc::Receiver<(gpu::EnvMap, Vec<f32>, f32)>,- /// The brightest sky texel from which the environment is light-sampled (`Prepared::env_nee_floor`).- pub(super) env_nee_floor: f32,}impl DynamicSky {- pub(super) fn new(world: &World, (w, h): (u32, u32), altitude: f32, env_nee_floor: f32) -> Option<DynamicSky> {+ pub(super) fn new(world: &World, (w, h): (u32, u32), altitude: f32) -> Option<DynamicSky> {let crate::desc::Sky::Atmosphere { rayleigh_scale, mie_scale, mie_anisotropy, ground_albedo, glow, horizon_glow, sun: Some(_), .. } = &world.environment.sky else {return None;};@@ -119,7 +105,7 @@ impl DynamicSky {}}).ok()?;- Some(DynamicSky { atm, ask, done, env_nee_floor })+ Some(DynamicSky { atm, ask, done })}}@@ -213,7 +199,7 @@ impl EmitterWorker {}}-pub(super) fn load_scene(g: &gpu::Gpu, world: &World, assets: &Path, presets: &Path, w: u32, h: u32, targets: &Targets, passes: &Passes) -> Result<(LoadedScene, crate::desc::PostPreset)> {+pub(super) fn load_scene(g: &gpu::Gpu, world: &World, assets: &Path, presets: &Path, w: u32, h: u32, targets: &Targets, passes: &Passes) -> Result<(LoadedScene, ViewState, Environment)> {let t0 = Instant::now();let mut sc = scene::build(world, assets, presets, None)?;sc.width = w;@@ -237,7 +223,11 @@ pub(super) fn load_scene(g: &gpu::Gpu, world: &World, assets: &Path, presets: &Pif !g.merged {let _ = g.kernel_pass(&up.kernel, "finish");}- let sky_inputs = ((prep.env.width, prep.env.height), sc.camera.position.y.max(0.0), prep.env_nee_floor);+ let env = Environment {+ sky: SkyState { map: (prep.env.width, prep.env.height), altitude: sc.camera.position.y.max(0.0), floor: prep.env_nee_floor, cover: sc.environment.cloud_cover, worker: None },+ settings: sc.environment.clone(),+ };+ let view = ViewState::new(&sc.camera, Arc::new(sc.preset.clone()));let mut base = prep.params;// The live view's own count of light-tree candidates at camera hits (ltree.rs `RIS_LIVE`).if base.ltree[3] > 0.5 {@@ -246,13 +236,6 @@ pub(super) fn load_scene(g: &gpu::Gpu, world: &World, assets: &Path, presets: &Pbase.ltile[3] = super::LIST_CANDIDATES;base.cam_fwd[3] = w as f32 / h as f32;let bgs = targets.bind_groups(&g.device, passes, &up.accum);- let exposure_settings = ExposureSettings::new(&sc.camera.exposure, &sc.preset.post);- // (Auto: a first guess; the GPU histogram takes the exposure over from frame 1, and the kernel's firefly clamp,- // `Params::misc[0]`, keeps `prepare`'s guess.)- let exposure = sc.camera.exposure.start();- let preset = sc.preset.clone();- let c = &sc.camera;- let scene_camera = Camera { pos: c.position, fwd: c.forward, up: c.up, right: c.right, tan_half_fov: c.tan_half_fov };let (tris, tri_nodes, tri_instances) = (std::mem::take(&mut sc.tris), std::mem::take(&mut sc.tri_nodes), std::mem::take(&mut sc.tri_instances));let instanced = !sc.gpu_instances.is_empty() || !sc.procs.is_empty();let instance_features = gpu::instance_features(&sc);@@ -303,5 +286,5 @@ pub(super) fn load_scene(g: &gpu::Gpu, world: &World, assets: &Path, presets: &Pinst_at_load: instances.len(),added: Default::default(),};- Ok((LoadedScene { timings, triangles, tris, tri_nodes, tri_instances, pool_tris, meshes, instances, gpu_instances, procs, proc_of, proc_first, instanced, instance_features, name: sc.name.clone(), up, base, bgs, exposure, exposure_settings, preset, tan_half_fov: c.tan_half_fov, scene_camera, dof: c.dof.clone(), tables, fixed_features, dynamic, edit, sky: None, emit, sky_inputs, mat_runs, tri_order }, sc.preset.post))+ Ok((LoadedScene { timings, triangles, tris, tri_nodes, tri_instances, pool_tris, meshes, instances, gpu_instances, procs, proc_of, proc_first, instanced, instance_features, name: sc.name.clone(), up, base, bgs, tables, fixed_features, dynamic, edit, emit, mat_runs, tri_order }, view, env))}diff --git a/renderer/src/live/mod.rs b/renderer/src/live/mod.rsindex 11abe63..ce7db12 100644--- a/renderer/src/live/mod.rs+++ b/renderer/src/live/mod.rs@@ -52,6 +52,7 @@ mod layout;mod load;#[cfg(not(target_arch = "wasm32"))]mod session;+mod state;mod targets;#[cfg(test)]pub(crate) use targets::live_source;@@ -61,6 +62,7 @@ pub use session::{parse_cmd, parse_launch, parse_opts, run, save_bgra};use edits::*;use frame::*;use load::*;+use state::*;use targets::*;pub struct LiveOpts {@@ -145,37 +147,7 @@ struct LiveParams {/// uniform ones (`Params::ltile.w`; half past the camera hit). 2 read as 4, 8 and 16 on the lamp-rooms shots.pub(super) const LIST_CANDIDATES: u32 = 2;-/// Auto / local exposure settings of the loaded scene (UE PostProcessVolume semantics).-#[derive(Clone, Copy, Default)]-struct ExposureSettings {- ae: [f32; 4],- ae2: [f32; 4],- speed: [f32; 2],- lx: [f32; 4],-}--impl ExposureSettings {- fn new(exp: &crate::desc::Exposure, pp: &crate::desc::PostPreset) -> Self {- let a = &pp.auto_exposure;- let le = &pp.local_exposure;- let (ae2, comp) = match exp {- crate::desc::Exposure::Manual { ev100 } => ([2f32.powf(-ev100), 0.0, 0.0, 0.0], 2f32.powf(-ev100)),- crate::desc::Exposure::Auto { compensation, min_ev100, max_ev100 } => {- let c = 2f32.powf(*compensation);- ([c, 0.18 * 2f32.powf(*min_ev100), 0.18 * 2f32.powf(*max_ev100), 1.0], c)- }- };- let _ = comp;- ExposureSettings {- ae: [a.low_percent.clamp(1.0, 99.0) / 100.0, a.high_percent.clamp(1.0, 99.0) / 100.0, a.histogram_log_min, a.histogram_log_max.max(a.histogram_log_min + 1.0)],- ae2,- speed: [a.speed_up.max(0.01), a.speed_down.max(0.01)],- lx: [le.highlight_contrast, le.shadow_contrast, le.blurred_luminance_blend, le.detail_strength],- }- }-}--#[derive(Clone, Copy, PartialEq)]+#[derive(Clone, Copy, PartialEq, Debug)]pub struct Camera {pub pos: Vec3,pub fwd: Vec3,@@ -249,6 +221,9 @@ pub struct LiveCore {passes: Passes,pub targets: Targets,sc: LoadedScene,+ /// How a frame is taken and shown, and the environment: beside the scene's data (state.rs).+ view: ViewState,+ env: Environment,presets: PathBuf,/// Asset root (models, file textures).assets: PathBuf,@@ -377,8 +352,6 @@ pub struct LiveCore {pub gpu_blas_ms: f32,/// CPU time the last `render` spent waiting for the oldest frame in flight (ms; frame log `wait`): GPU-bound frames.pub cpu_wait_ms: f32,- /// The cloud cover the sky and the sun light were made with (`move_sun`).- sky_cover: f32,/// The loop guard (gpu.rs `guard_loops`), if a kernel of this session may have it: the invocations it has stopped at/// its limit since the view was made, as last read back (a frame or two behind, without waiting). Above zero:/// frames with wrong pixels, a traversal that did not end on the scene's data. None without the guard.@@ -517,8 +490,9 @@ impl LiveCore {let cache_on = !std::env::var("THREERT_CACHE").is_ok_and(|v| v == "0");// (Without the cache the kernel binds one of one entry.)let targets = Targets::new(&g, w, h, &vec![0u16; (LUT * LUT * LUT * 4) as usize], if cache_on { gpu::CACHE_SIZE } else { 1 });- let (sc, pp) = load_scene(&g, world, assets, presets, w, h, &targets, &passes)?;- let cam = sc.scene_camera;+ let (sc, view, env) = load_scene(&g, world, assets, presets, w, h, &targets, &passes)?;+ let cam = view.camera;+ let pp = view.preset.post.clone();let (triangles, scene_name) = (sc.triangles, sc.name.clone());let profile = (g.timestamps && std::env::var("THREERT_PROFILE").is_ok()).then(|| {// trace, the post passes, cache resolve, then the particle pass, the BLAS rebuild, the translucency pass and@@ -549,15 +523,14 @@ impl LiveCore {// brings it, `gpu::loop_guard_of`.)let guard_read = (gpu::loop_guard_of(!g.hwrt).is_some() && targets.kernel.guard.is_some()).then(|| (g.device.create_buffer(&wgpu::BufferDescriptor { label: Some("loop guard read"), size: 4, usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false }), Arc::new(AtomicU32::new(0))));- let mut core = LiveCore { particle_spawns: Default::default(), grid_sources: Default::default(), g, passes, targets, sc, presets: presets.to_path_buf(), assets: assets.to_path_buf(), w, h, seq: 0, aspect: w as f32 / h as f32, cam, prev_cam: cam, frame: 0, history_len: 0.0, reset: true, bloom: ([0.0; 6], [0.0; 6]), vignette: 0.0, post: [0.0; 4], blur: (0.0, 0.0), inflight: Default::default(), gpu_ms: 0.0, gpu_frame: 0, gpu_trace_ms: 0.0, edit_ms: 0.0, instanced_ms: 0.0, edit_split: EditSplit::default(), rebuild_ms: 0.0, fallback: None, fallbacks: 0, bounces: 4, rays: true, view_mode: std::env::var("THREERT_VIEW_MODE").ok().and_then(|v| v.parse().ok()).unwrap_or(0), fixed_dt: None, motion_blur_off: false, triangles, scene_name, time: 0.0, frame_dt: 1.0 / 60.0, last_frame: Instant::now(), post_key: String::new(), render_scale: 1.0, dynamic_res: false, min_scale: MIN_SCALE, display_scale: 1.0, over_budget: (0, 0), born: Instant::now(), governed: Instant::now(), profile, timer, raster, cache, kernel_bg, tl_kernel_bg, prev_span: None, reposed: false, emitters_moved: false, pose_span: None, pose_reposed: false, inst_moving: vec![], inst_moved: false, prev_isz: (0, 0), light_tiles: None, lit_changed: 0, spark_lights: false, shown_spp: 1, cpu_skin_ms: 0.0, cpu_upload_ms: 0.0, gpu_blas_ms: 0.0, cpu_wait_ms: 0.0, sky_cover: 0.0, guard_trips: guard_read.as_ref().map(|_| 0), guard_read };+ let mut core = LiveCore { particle_spawns: Default::default(), grid_sources: Default::default(), g, passes, targets, sc, view, env, presets: presets.to_path_buf(), assets: assets.to_path_buf(), w, h, seq: 0, aspect: w as f32 / h as f32, cam, prev_cam: cam, frame: 0, history_len: 0.0, reset: true, bloom: ([0.0; 6], [0.0; 6]), vignette: 0.0, post: [0.0; 4], blur: (0.0, 0.0), inflight: Default::default(), gpu_ms: 0.0, gpu_frame: 0, gpu_trace_ms: 0.0, edit_ms: 0.0, instanced_ms: 0.0, edit_split: EditSplit::default(), rebuild_ms: 0.0, fallback: None, fallbacks: 0, bounces: 4, rays: true, view_mode: std::env::var("THREERT_VIEW_MODE").ok().and_then(|v| v.parse().ok()).unwrap_or(0), fixed_dt: None, motion_blur_off: false, triangles, scene_name, time: 0.0, frame_dt: 1.0 / 60.0, last_frame: Instant::now(), post_key: String::new(), render_scale: 1.0, dynamic_res: false, min_scale: MIN_SCALE, display_scale: 1.0, over_budget: (0, 0), born: Instant::now(), governed: Instant::now(), profile, timer, raster, cache, kernel_bg, tl_kernel_bg, prev_span: None, reposed: false, emitters_moved: false, pose_span: None, pose_reposed: false, inst_moving: vec![], inst_moved: false, prev_isz: (0, 0), light_tiles: None, lit_changed: 0, spark_lights: false, shown_spp: 1, cpu_skin_ms: 0.0, cpu_upload_ms: 0.0, gpu_blas_ms: 0.0, cpu_wait_ms: 0.0, guard_trips: guard_read.as_ref().map(|_| 0), guard_read };core.spark_lights = core.sc.tables.emitter_tris.iter().any(|e| e.nominal);- core.sky_cover = core.sc.tables.cloud_cover;core.apply_post(&pp);Ok(core)}pub fn scene_camera(&self) -> Camera {- self.sc.scene_camera+ self.view.camera}/// `guard_trips` for the frame log: None while the scene's kernel has no guard. Natively with nothing set that is@@ -597,15 +570,16 @@ impl LiveCore {}pub fn rebuild(&mut self, world: &World) -> Result<()> {- let (s, pp) = load_scene(&self.g, world, &self.assets, &self.presets, self.w, self.h, &self.targets, &self.passes)?;- self.apply_post(&pp);+ let (s, view, env) = load_scene(&self.g, world, &self.assets, &self.presets, self.w, self.h, &self.targets, &self.passes)?;+ self.apply_post(&view.preset.post);self.triangles = s.triangles;self.scene_name = s.name.clone();// The scene's camera changed (a new lens rebuilds, and a move in the same commit comes with it): the view takes it.// Otherwise the view stays where it is.- if s.scene_camera != self.sc.scene_camera {- self.cam = s.scene_camera;+ if view.camera != self.view.camera {+ self.cam = view.camera;}+ (self.view, self.env) = (view, env);// What the grid programs had simulated goes with the grids that are still the same.self.g.carry_grids(&self.sc.up, &s.up);self.sc = s;@@ -658,7 +632,7 @@ impl LiveCore {c.bufs.clear(&mut e);self.g.queue.submit([e.finish()]);}- self.cam = self.sc.scene_camera;+ self.cam = self.view.camera;self.prev_cam = self.cam;self.reset = true;Ok(())@@ -706,7 +680,7 @@ impl LiveCore {pub fn set_camera(&mut self, mut c: Camera) {if c.tan_half_fov <= 0.0 {- c.tan_half_fov = self.sc.tan_half_fov;+ c.tan_half_fov = self.view.camera.tan_half_fov;}self.cam = c;}@@ -855,8 +829,8 @@ impl LiveCore {#[cfg(not(target_arch = "wasm32"))]/// The exposure the last frame was shown at, EV100 (auto exposure: its adapted value).pub fn read_ev100(&self) -> Result<f32> {- if self.sc.exposure_settings.ae2[3] <= 0.5 {- return Ok(-self.sc.exposure.log2());+ if self.view.exposure_settings.ae2[3] <= 0.5 {+ return Ok(-self.view.exposure.log2());}let d = &self.g.device;let read = d.create_buffer(&wgpu::BufferDescriptor { label: Some("ae read"), size: 16, usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false });diff --git a/renderer/src/live/state.rs b/renderer/src/live/state.rsnew file mode 100644index 0000000..fee33a3--- /dev/null+++ b/renderer/src/live/state.rs@@ -0,0 +1,100 @@+//! What a live view holds beside the scene's data, each derived from the world by one function, at load and on an+//! edit, and replaced whole:+//! - `ViewState`: how a frame is taken and shown (the scene's camera and its lens, depth of field and exposure; the+//! render preset). The view's, not the scene's: a rebuild of the scene's data leaves it.+//! - `Environment`: the environment's settings (`scene::EnvSettings`) and the state of its sky.+//!+//! The scene's data then knows no camera and no post state, and the environment is an object of its own, on the+//! scene's side as the scene DSL has it (`scene.environment`, `background`, fog).++use super::*;++/// Auto / local exposure settings (UE PostProcessVolume semantics).+#[derive(Clone, Copy, Default, Debug)]+pub(super) struct ExposureSettings {+ pub(super) ae: [f32; 4],+ pub(super) ae2: [f32; 4],+ pub(super) speed: [f32; 2],+ pub(super) lx: [f32; 4],+}++impl ExposureSettings {+ fn new(exp: &crate::desc::Exposure, pp: &crate::desc::PostPreset) -> Self {+ let a = &pp.auto_exposure;+ let le = &pp.local_exposure;+ let ae2 = match exp {+ crate::desc::Exposure::Manual { ev100 } => [2f32.powf(-ev100), 0.0, 0.0, 0.0],+ crate::desc::Exposure::Auto { compensation, min_ev100, max_ev100 } => [2f32.powf(*compensation), 0.18 * 2f32.powf(*min_ev100), 0.18 * 2f32.powf(*max_ev100), 1.0],+ };+ ExposureSettings {+ ae: [a.low_percent.clamp(1.0, 99.0) / 100.0, a.high_percent.clamp(1.0, 99.0) / 100.0, a.histogram_log_min, a.histogram_log_max.max(a.histogram_log_min + 1.0)],+ ae2,+ speed: [a.speed_up.max(0.01), a.speed_down.max(0.01)],+ lx: [le.highlight_contrast, le.shadow_contrast, le.blurred_luminance_blend, le.detail_strength],+ }+ }+}++/// How a frame is taken and shown.+pub(super) struct ViewState {+ /// The scene's camera: where a view starts, and its lens (a view moved by its host keeps the lens).+ pub(super) camera: Camera,+ /// The camera's depth of field (UE: off unless it sets a focus distance): a post pass.+ pub(super) dof: Option<crate::desc::Dof>,+ /// The exposure a view starts at (auto exposure takes over from the first frame), and its settings.+ pub(super) exposure: f32,+ pub(super) exposure_settings: ExposureSettings,+ exposure_desc: crate::desc::Exposure,+ /// The render preset: the kernel's bounce limits and clamp, the post passes' settings.+ pub(super) preset: Arc<crate::desc::Preset>,+}++impl ViewState {+ /// From the scene's camera (a build's, or `scene::camera_data` of the world's) and the preset.+ pub(super) fn new(c: &scene::CameraData, preset: Arc<crate::desc::Preset>) -> ViewState {+ ViewState {+ camera: Camera { pos: c.position, fwd: c.forward, up: c.up, right: c.right, tan_half_fov: c.tan_half_fov },+ dof: c.dof.clone(),+ exposure: c.exposure.start(),+ exposure_settings: ExposureSettings::new(&c.exposure, &preset.post),+ exposure_desc: c.exposure.clone(),+ preset,+ }+ }++ /// The world's, as it is now (`preset`: the one to keep; None: the world's settings' own, read again). None: the+ /// world names no camera.+ pub(super) fn of(world: &World, presets: &Path, preset: Option<Arc<crate::desc::Preset>>) -> Result<Option<ViewState>> {+ let (Some(id), Some(c)) = (world.settings.camera, world.scene_camera()) else { return Ok(None) };+ let preset = match preset {+ Some(p) => p,+ None => Arc::new(scene::preset_of(world, presets, None)?),+ };+ Ok(Some(ViewState::new(&scene::camera_data(world.world_matrix(id), c), preset)))+ }++ /// The kernel's parameters that are the view's (`gpu::Params::set_preset`, as a build writes them).+ pub(super) fn write(&self, p: &mut gpu::Params) {+ p.set_preset(&self.preset.native, &self.exposure_desc);+ }+}++/// The environment: its settings, and its sky's state.+pub(super) struct Environment {+ pub(super) settings: scene::EnvSettings,+ pub(super) sky: SkyState,+}++/// What the view keeps of the sky that is on the GPU (`Gpu::put_env`).+pub(super) struct SkyState {+ /// The environment map's size.+ pub(super) map: (u32, u32),+ /// The camera's altitude it was baked for, m.+ pub(super) altitude: f32,+ /// The brightest texel from which a sky is light-sampled (`Prepared::env_nee_floor`).+ pub(super) floor: f32,+ /// The cloud cover it was baked with.+ pub(super) cover: f32,+ /// A dynamic sky's bakes on a worker thread (started by the sun's first move).+ pub(super) worker: Option<DynamicSky>,+}diff --git a/renderer/src/main.rs b/renderer/src/main.rsindex 31f1e18..529733d 100644--- a/renderer/src/main.rs+++ b/renderer/src/main.rs@@ -282,7 +282,6 @@ fn main() -> Result<()> {("lights", bytemuck::cast_slice::<_, u8>(&e.lights) == bytemuck::cast_slice::<_, u8>(&b.lights)),("object power", power(&e.objects) == power(&b.objects)),("emitters", bits(&ea, e.emitter_tris.len()) == bits(&pb.emitters, pb.emitter_tris.len())),- ("wetness / rain", (e.wetness, e.rain) == (b.wetness, b.rain)),];println!("{}", serde_json::json!({ "structural": applied.is_none(), "checks": checks.iter().map(|(k, ok)| (k.to_string(), *ok)).collect::<std::collections::BTreeMap<_, _>>() }));if applied.is_none() || checks.iter().any(|(_, ok)| !ok) {diff --git a/renderer/src/scene.rs b/renderer/src/scene.rsindex b508082..c96ee70 100644--- a/renderer/src/scene.rs+++ b/renderer/src/scene.rs@@ -406,6 +406,43 @@ pub struct CameraData {pub dof: Option<desc::Dof>,}+/// The environment beside its sky, as the world describes it: one derivation (`of`) for a build and for an edit, one+/// place that says what the kernel takes from it (`write`, `features`).+#[derive(Clone, Debug)]+pub struct EnvSettings {+ pub fog: Option<desc::Fog>,+ /// three.js `scene.background` (`desc::Environment::background`): the kernel's F_BACKGROUND, `Params::background`.+ pub background: Option<[f32; 3]>,+ /// The sky's aerial perspective (`aerial_params`): the kernel's F_AERIAL, `Params::aerial`.+ pub aerial: [f32; 4],+ /// Global wetness and rain intensity (0..1).+ pub wetness: f32,+ pub rain: f32,+ /// Cloud cover (0..1) of an atmosphere sky: the sky is baked with it (`bake_sky`).+ pub cloud_cover: f32,+}++impl EnvSettings {+ pub fn of(w: &World) -> EnvSettings {+ let e = &w.environment;+ EnvSettings { fog: e.fog.clone(), background: e.background, aerial: aerial_params(&e.sky), wetness: e.wetness.clamp(0.0, 1.0), rain: e.rain.clamp(0.0, 1.0), cloud_cover: e.cloud_cover.clamp(0.0, 1.0) }+ }++ /// The kernel's parameters for them.+ pub fn write(&self, p: &mut crate::gpu::Params) {+ p.time[1] = self.wetness;+ p.time[2] = self.rain;+ p.background = self.background.map_or([0.0; 4], |c| [c[0], c[1], c[2], 1.0]);+ p.aerial = self.aerial;+ [p.fog, p.fog_color, p.vol, p.vol2] = crate::fog_params(self.fog.as_ref());+ }++ /// The kernel features they ask for (`gpu::environment_features`).+ pub fn features(&self) -> u32 {+ crate::gpu::environment_features(self.fog.as_ref(), self.background.is_some(), self.aerial)+ }+}+pub enum SkyData {None,Color(Vec3),@@ -453,12 +490,8 @@ pub struct Scene {pub lights: Vec<GpuLight>,pub camera: CameraData,pub sky: SkyData,- pub fog: Option<desc::Fog>,- /// Global wetness and rain intensity (0..1).- pub wetness: f32,- pub rain: f32,- /// Cloud cover (0..1) of an atmosphere sky.- pub cloud_cover: f32,+ /// The environment beside its sky (`EnvSettings::of`).+ pub environment: EnvSettings,pub preset: desc::Preset,pub stats: HashMap<&'static str, f64>,/// Triangle ranges per object (name, first, end), in `tris` order: picking and selection outlines.@@ -468,10 +501,6 @@ pub struct Scene {/// Some object has instance colours (`InstanceTable::colors`): the kernel's F_TINT, 4 vec4s an object/// (`object_stride`).pub tinted: bool,- /// three.js `scene.background` (`desc::Environment::background`): the kernel's F_BACKGROUND, `Params::background`.- pub background: Option<Vec3>,- /// The sky's aerial perspective (`aerial_params`): the kernel's F_AERIAL, `Params::aerial`.- pub aerial: [f32; 4],/// Instanced static glTF meshes (model-space triangles, flags, attributes) and their placements. `prepare` appends/// the pool after the flattened triangles (hardware RT) or flattens the instances (software traversal).pub pool_tris: Vec<[Vec3A; 3]>,@@ -1802,7 +1831,6 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se}}- let env = &w.environment;let (sky, sun) = sky_data(w, assets, &|id| worlds.get(&id).copied().unwrap_or(Mat4::IDENTITY))?;retained.sun = sun;@@ -1867,17 +1895,12 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&selights,camera: camera.ok_or_else(|| anyhow!("no camera (settings.camera must name a camera object)"))?,sky,- fog: env.fog.clone(),- wetness: env.wetness.clamp(0.0, 1.0),- rain: env.rain.clamp(0.0, 1.0),- cloud_cover: env.cloud_cover.clamp(0.0, 1.0),+ environment: EnvSettings::of(w),preset,stats,tri_nodes,tri_instances,tinted,- background: w.environment.background.map(Vec3::from),- aerial: aerial_params(&w.environment.sky),retained,particles,particle_fns,diff --git a/renderer/src/tables.rs b/renderer/src/tables.rsindex 0a03707..3956ba4 100644--- a/renderer/src/tables.rs+++ b/renderer/src/tables.rs@@ -3,7 +3,7 @@//! colour / intensity, material parameters, wetness / rain / fog, camera); `LiveCore::commit` uploads them.use crate::desc;-use crate::scene::{self, CameraData, GpuLight, GpuMaterial, Retained};+use crate::scene::{self, GpuLight, GpuMaterial, Retained};use crate::world::{Changes, Kind, World};use crate::EmitterTri;use anyhow::{anyhow, Result};@@ -22,14 +22,11 @@ pub struct Dirty {/// Power edits held back (`Tables::defer_powers`): the live view's emitter worker rebuilds the CDF and the tree's/// powers for them, and they land together.pub deferred: bool,- /// Wetness / rain / fog kernel parameters.- pub environment: bool,- pub camera: bool,}impl Dirty {pub fn any(&self) -> bool {- self.materials || self.lights || self.objects || self.emitters || self.deferred || self.environment || self.camera+ self.materials || self.lights || self.objects || self.emitters || self.deferred}}@@ -43,22 +40,12 @@ pub struct Tables {pub light_tree: Option<crate::ltree::LightTree>,/// Materials that have emitter triangles (others cannot start emitting without a rebuild).pub(crate) emissive: HashSet<u32>,- pub wetness: f32,- pub rain: f32,- /// Cloud cover (0..1): a change re-bakes the sky and dims the sun (live/edits.rs `move_sun`).- pub cloud_cover: f32,- pub fog: Option<desc::Fog>,- /// three.js `scene.background` (`Params::background`).- pub background: Option<[f32; 3]>,/// A material that starts emitting gets emitter entries in place (the live view sets these up, `prepare`'s/// `mat_runs` / `fixed_mats`): it is queued in `started_emitting` for live/edits.rs `add_material_emitters`, unless its/// triangles include pool or dynamic ones (fixed: a rebuild flattens them). Off: such a material rebuilds.pub emit_in_place: bool,pub fixed_mats: HashSet<u32>,pub started_emitting: Vec<u32>,- /// `scene::aerial_params` of the sky.- pub aerial: [f32; 4],- pub camera: Option<CameraData>,/// Object -> its entries in `lights`.pub light_index: HashMap<u32, Vec<usize>>,/// vec4s an object in `objects` (`scene::object_stride`).@@ -84,16 +71,9 @@ impl Tables {emissive: emitter_tris.iter().map(|e| e.mat).collect(),emitter_tris,light_tree,- wetness: sc.wetness,- rain: sc.rain,- cloud_cover: sc.cloud_cover,- fog: sc.fog.clone(),- background: sc.background.map(|b| b.to_array()),emit_in_place: false,fixed_mats: HashSet::new(),started_emitting: vec![],- aerial: sc.aerial,- camera: None,light_index,stride: sc.object_stride(),defer_powers: false,@@ -110,14 +90,6 @@ impl Tables {}/// Applies parameter changes; Err / Ok(None) means the scene must be rebuilt instead.- /// The kernel features the scene needs as these tables are: what the materials and the environment ask for (edits- /// change them), with the scene's structural ones (`fixed`: textures, material functions, the traversal groups;- /// `structure`: `gpu::instance_features`).- pub fn features(&self, (textures, functions, groups): (bool, bool, [usize; crate::GROUPS]), structure: u32) -> u32 {- let environment = crate::gpu::environment_features(self.fog.as_ref(), self.background.is_some(), self.aerial);- crate::gpu::features_of(&self.materials, environment, textures, functions, groups, structure)- }-pub fn apply(&mut self, w: &World, c: &Changes, now: f32) -> Result<Option<Dirty>> {if c.structural || !c.poses.is_empty() || !c.moved.is_empty() {return Ok(None);@@ -177,21 +149,6 @@ impl Tables {self.materials[mi as usize] = gm;d.materials = true;}- if c.environment {- self.wetness = w.environment.wetness.clamp(0.0, 1.0);- self.rain = w.environment.rain.clamp(0.0, 1.0);- self.cloud_cover = w.environment.cloud_cover.clamp(0.0, 1.0);- self.fog = w.environment.fog.clone();- self.background = w.environment.background;- self.aerial = scene::aerial_params(&w.environment.sky);- d.environment = true;- }- if c.camera {- let Some(cid) = w.settings.camera else { return Ok(None) };- let Some(Kind::Camera(cam)) = w.objects.get(&cid).map(|o| &o.kind) else { return Ok(None) };- self.camera = Some(scene::camera_data(w.world_matrix(cid), cam));- d.camera = true;- }Ok(Some(d))}diff --git a/renderer/src/world.rs b/renderer/src/world.rsindex 42d4449..aec1fac 100644--- a/renderer/src/world.rs+++ b/renderer/src/world.rs@@ -292,12 +292,11 @@ pub struct Changes {pub sun: bool,/// Another sky (its kind or its parameters): baked and put in place (live/edits.rs `apply_sky`). With `environment`.pub sky: bool,- /// The scene camera's exposure changed (its mode or its values): applied in place (live/edits.rs `apply_exposure`).- pub exposure: bool,- /// The scene camera's depth of field changed: the post pass's, in place. (Not `camera`: the view stays where it is.)- pub dof: bool,- /// The preset, its overrides or the scene's name changed: what a build takes from them is taken again in place- /// (live/edits.rs `apply_settings`).+ /// The scene camera's depth of field or exposure changed: the view's state, taken again in place (live/edits.rs+ /// `apply_view`). Not `camera`: a view its host moved stays where it is.+ pub view: bool,+ /// The preset, its overrides or the scene's name changed: what a view takes from them is taken again in place+ /// (`apply_view`).pub settings: bool,/// Models whose animation pose changed.pub poses: HashSet<u32>,@@ -332,7 +331,7 @@ pub struct Changes {impl Changes {pub fn any(&self) -> bool {- self.structural || !self.shown.is_empty() || !self.new_materials.is_empty() || !self.materials.is_empty() || !self.lights.is_empty() || !self.powers.is_empty() || !self.customs.is_empty() || self.environment || self.camera || self.sun || self.exposure || self.dof || self.settings || !self.poses.is_empty() || !self.moved.is_empty() || !self.instanced.is_empty() || self.edits()+ self.structural || !self.shown.is_empty() || !self.new_materials.is_empty() || !self.materials.is_empty() || !self.lights.is_empty() || !self.powers.is_empty() || !self.customs.is_empty() || self.environment || self.camera || self.sun || self.view || self.settings || !self.poses.is_empty() || !self.moved.is_empty() || !self.instanced.is_empty() || self.edits()}/// Geometry edits are pending (`geometries`, `added`, `removed`).pub fn edits(&self) -> bool {@@ -902,17 +901,16 @@ impl World {// In place, when it is the scene's camera: a field of view is the view's (as a camera's move: the view takes// it), a depth of field and an exposure are the post passes' (and the kernel's clamp). Nothing is built from a// camera that is not the scene's, nor from near and far; a camera made of another kind of object is a new object.- let (fov, dof, exposure) = match &o.kind {- Kind::Camera(old) => (old.fov != c.fov, old.dof != c.dof, old.exposure != c.exposure),+ let (fov, rest) = match &o.kind {+ Kind::Camera(old) => (old.fov != c.fov, old.dof != c.dof || old.exposure != c.exposure),_ => {self.changes.structural = true;- (false, false, false)+ (false, false)}};o.kind = Kind::Camera(c);self.changes.camera |= active && fov;- self.changes.dof |= active && dof;- self.changes.exposure |= active && exposure;+ self.changes.view |= active && rest;Ok(())}@@ -987,10 +985,8 @@ impl World {self.changes.settings = true;}if old.camera != s.camera {- // Another camera: its place and lens, its depth of field and its exposure.+ // Another camera: the view takes it (its place and lens, its depth of field and its exposure).self.changes.camera = true;- self.changes.dof = true;- self.changes.exposure = true;}self.settings = s;}@@ -1558,25 +1554,25 @@ mod tests {w.take_changes();w.set_camera_desc(1, cam(30.0, manual(0.0))).unwrap();let c = w.take_changes();- assert!(!c.structural && c.camera && !c.exposure && !c.dof, "a lens: the view takes it");+ assert!(!c.structural && c.camera && !c.view, "a lens: the view takes it");let mut with_dof = cam(30.0, manual(0.0));with_dof.dof = Some(serde_json::from_value(serde_json::json!({ "focusDistance": 3, "fStop": 2, "sensorWidth": 36 })).unwrap());w.set_camera_desc(1, with_dof).unwrap();let c = w.take_changes();- assert!(!c.structural && !c.camera && c.dof, "a depth of field: the view stays");+ assert!(!c.structural && !c.camera && c.view, "a depth of field: the view stays");w.set_camera_desc(1, cam(30.0, manual(0.0))).unwrap();w.take_changes();w.set_camera_desc(1, cam(30.0, manual(2.0))).unwrap();let c = w.take_changes();- assert!(!c.structural && !c.camera && c.exposure, "an exposure value");+ assert!(!c.structural && !c.camera && c.view, "an exposure value");w.set_camera_desc(1, cam(30.0, serde_json::json!({ "mode": "auto", "compensation": 0, "minEv100": -2, "maxEv100": 12 }))).unwrap();let c = w.take_changes();- assert!(!c.structural && !c.camera && c.exposure, "an exposure mode");+ assert!(!c.structural && !c.camera && c.view, "an exposure mode");w.set_camera_desc(2, cam(20.0, manual(5.0))).unwrap();assert!(!w.take_changes().any(), "a camera that is not the scene's");w.set_settings(Settings { camera: Some(2), ..w.settings.clone() });let c = w.take_changes();- assert!(!c.structural && c.camera && c.exposure && c.dof, "the scene's camera is another");+ assert!(!c.structural && c.camera, "the scene's camera is another");w.set_settings(Settings { preset: "preview".into(), ..w.settings.clone() });let c = w.take_changes();assert!(!c.structural && c.settings, "another preset");