Skip to content

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.

Live edits: another sky in place (#125)

Yujia65a4eb99e671
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md
index 3682c0e..be9ec69 100644
--- a/docs/ROADMAP.md
+++ b/docs/ROADMAP.md
@@ -2549,6 +2549,17 @@ gone), the radiance cache and the frames' histories keep the old light for hundr
after 264), here as after a rebuild; the test compares with the histories cleared. Still a rebuild: another sky, and the output's size (a view cannot be resized). The first of the
scene model's steps: the proxy table next.
+**Another sky in place (2026-11-16, after it).** A sky's kind or parameters rebuilt the scene too. The build's sky
+is two functions now, the sky's data from the world (`scene::sky_data`) and its bake (`bake_sky`), and the live view
+calls them for an edit: the environment map and its CDF are written in place when they keep their size, else a new
+texture and the CDF's section grown, the scene bound again (`Gpu::put_env`); the parameters that say how the sky is
+read follow; the atmosphere's sun takes its colour from the bake, and a light that is the sun no longer is a light
+of its own colour again. The same test holds six sky edits (one colour, a gradient, an atmosphere with its sun,
+the same as a dynamic sky, one colour again, none) to a view built from the edited world. What the frame that
+takes one pays is the bake: 0.1 ms for a colour, 6 for a gradient, 47 for an atmosphere (a rebuild paid that and
+the scene's 0.5 to 0.9 s). No picture changed (render-identity; the live volume tests' own spread is wider than
+two runs show: five runs a side, none differ).
+
## 2. Temporal fixes
Targets (2026-11-08): bench-temporal, bench-ghosting and their UE MRQ references move to Bistro night (§ 0 step 7); the
diff --git a/docs/RUNTIME.md b/docs/RUNTIME.md
index 5004798..4bfbba8 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. 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` | 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. |
| 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.rs
index 816b1ed..f3d96a8 100644
--- a/renderer/src/gpu.rs
+++ b/renderer/src/gpu.rs
@@ -387,7 +387,7 @@ pub struct Uploaded {
pub words: Heap<Stream>,
pub cdf_words: usize,
pub region_words: usize,
- /// The environment map (`write_env` replaces it in place when a dynamic sky's sun moves).
+ /// The environment map (`put_env` replaces it: a dynamic sky's sun moved, another sky).
pub env_tex: wgpu::Texture,
/// Translucent particles' acceleration structures and pass resources (hardware RT).
pub translucent: Option<Translucent>,
@@ -2104,23 +2104,7 @@ impl Gpu {
assert!(parts.iter().enumerate().all(|(k, p)| p.0.index() == k), "the tables in `Table`'s order");
let heap = Heap::filled(d, &parts.map(|p| (p.1.len() + p.2) as u64), |put| parts.iter().for_each(|p| put(p.0, 0, p.1)));
- let env_tex = d.create_texture(&wgpu::TextureDescriptor {
- label: Some("env"),
- size: wgpu::Extent3d { width: env.width, height: env.height, depth_or_array_layers: 1 },
- mip_level_count: 1,
- sample_count: 1,
- dimension: wgpu::TextureDimension::D2,
- format: wgpu::TextureFormat::Rgba16Float,
- usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
- view_formats: &[],
- });
- let half: Vec<u16> = env.texels.iter().flat_map(|t| t.iter().map(|v| half::f16::from_f32(v.min(65000.0)).to_bits())).collect();
- self.queue.write_texture(
- wgpu::TexelCopyTextureInfo { texture: &env_tex, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All },
- bytemuck::cast_slice(&half),
- wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(env.width * 8), rows_per_image: Some(env.height) },
- wgpu::Extent3d { width: env.width, height: env.height, depth_or_array_layers: 1 },
- );
+ let env_tex = self.env_texture(env);
let env_view = env_tex.create_view(&Default::default());
let sampler = d.create_sampler(&wgpu::SamplerDescriptor {
address_mode_u: wgpu::AddressMode::Repeat,
@@ -2846,21 +2830,62 @@ impl Gpu {
}
}
- /// A volume node moved or changed its customData: its medium's world -> local rows / `custom` (None: unchanged).
- /// Replaces the environment map and its sampling CDF in place (a dynamic sky's new bake). Both keep their sizes.
- pub fn write_env(&self, up: &Uploaded, env: &EnvMap, cdf: &[f32]) {
- let size = up.env_tex.size();
- if (env.width, env.height) != (size.width, size.height) || cdf.len() != up.cdf_words {
- return;
- }
+ /// An environment map's texture, with its texels.
+ fn env_texture(&self, env: &EnvMap) -> wgpu::Texture {
+ let t = self.device.create_texture(&wgpu::TextureDescriptor {
+ label: Some("env"),
+ size: wgpu::Extent3d { width: env.width, height: env.height, depth_or_array_layers: 1 },
+ mip_level_count: 1,
+ sample_count: 1,
+ dimension: wgpu::TextureDimension::D2,
+ format: wgpu::TextureFormat::Rgba16Float,
+ usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
+ view_formats: &[],
+ });
+ self.write_env_texels(&t, env);
+ t
+ }
+
+ fn write_env_texels(&self, t: &wgpu::Texture, env: &EnvMap) {
let half: Vec<u16> = env.texels.iter().flat_map(|t| t.iter().map(|v| half::f16::from_f32(v.min(65000.0)).to_bits())).collect();
self.queue.write_texture(
- wgpu::TexelCopyTextureInfo { texture: &up.env_tex, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All },
+ wgpu::TexelCopyTextureInfo { texture: t, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All },
bytemuck::cast_slice(&half),
wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(env.width * 8), rows_per_image: Some(env.height) },
- size,
+ wgpu::Extent3d { width: env.width, height: env.height, depth_or_array_layers: 1 },
);
+ }
+
+ /// Whether a buffer of `bytes` can be made and bound (the device's buffer and storage binding limits).
+ pub fn buffer_fits(&self, bytes: u64) -> bool {
+ let l = self.device.limits();
+ bytes <= (l.max_storage_buffer_binding_size as u64).min(l.max_buffer_size)
+ }
+
+ /// A sky's environment map and its sampling CDF (a dynamic sky's new bake, another sky): written in place where
+ /// they are as large as the ones they replace, else a new texture, the CDF's section grown where it has to, and
+ /// the scene bound again. False, with nothing changed, when the grown buffer would pass the device's limits (a
+ /// build lays the scene's words out again, with less room for edits: the caller rebuilds).
+ pub fn put_env(&self, up: &mut Uploaded, env: &EnvMap, cdf: &[f32]) -> bool {
+ let size = up.env_tex.size();
+ if (env.width, env.height) == (size.width, size.height) && cdf.len() == up.cdf_words {
+ self.write_env_texels(&up.env_tex, env);
+ up.words.write(&self.queue, Stream::EnvCdf, 0, bytemuck::cast_slice(cdf));
+ return true;
+ }
+ let bytes = cdf.len() as u64 * 4;
+ if bytes > up.words.cap(Stream::EnvCdf) {
+ if !self.buffer_fits(up.words.size_with(Stream::EnvCdf, bytes)) {
+ return false;
+ }
+ up.words.grow(&self.device, &self.queue, Stream::EnvCdf, bytes);
+ }
+ up.env_tex = self.env_texture(env);
+ up.bg_parts.env_view = up.env_tex.create_view(&Default::default());
up.words.write(&self.queue, Stream::EnvCdf, 0, bytemuck::cast_slice(cdf));
+ up.cdf_words = cdf.len();
+ self.rebind_scene(up);
+ true
}
/// A volume node shown or hidden by its own `visible`, in place: its media keep their place in the table with
diff --git a/renderer/src/lib.rs b/renderer/src/lib.rs
index d4f8aa3..da95f69 100644
--- a/renderer/src/lib.rs
+++ b/renderer/src/lib.rs
@@ -622,60 +622,21 @@ pub fn prepare_as(hwrt: bool, units: bool, sc: &mut scene::Scene, timings: &mut
// Sky / environment.
let t = Instant::now();
- let (env, sky_color, has_env) = match &sc.sky {
- scene::SkyData::Atmosphere { sun_dir, sun_lux, rayleigh, mie, g: mie_g, ground, sun_node, dynamic, glow } => {
- // Scene edits that leave the sky inputs unchanged (materials, transforms, lights) reuse the last bake.
- static LAST: std::sync::Mutex<Option<(Vec<u32>, std::sync::Arc<sky::SkyBake>)>> = std::sync::Mutex::new(None);
- let alt = sc.camera.position.y.max(0.0);
- let (bw, bh) = if *dynamic { sky::DYNAMIC_SKY } else { (1024, 512) };
- let key: Vec<u32> = [*rayleigh, *mie, *mie_g, ground.x, ground.y, ground.z, sun_dir.x, sun_dir.y, sun_dir.z, sun_lux.x, sun_lux.y, sun_lux.z, alt, glow.uniform.x, glow.uniform.y, glow.uniform.z, glow.horizon.x, glow.horizon.y, glow.horizon.z, glow.height, bw as f32, sc.cloud_cover].iter().map(|f| f.to_bits()).collect();
- let mut last = LAST.lock().unwrap();
- let bake = match last.as_ref() {
- Some((k, b)) if *k == key => b.clone(),
- _ => {
- let atm = sky::Atmosphere::earth(*rayleigh, *mie, *mie_g, *ground);
- let b = std::sync::Arc::new(if *dynamic || !glow.is_zero() || sc.cloud_cover > 0.0 {
- sky::bake_atmosphere_tables(&atm, &sky::SkyTables::new(&atm), *sun_dir, *sun_lux, alt, bw, bh, *glow, sc.cloud_cover)
- } else {
- sky::bake_atmosphere(&atm, *sun_dir, *sun_lux, alt, bw, bh)
- });
- *last = Some((key, b.clone()));
- b
- }
- };
- drop(last);
- if let Some(i) = sun_node {
- let s = bake.sun_illuminance;
- sc.lights[*i].color = [s.x, s.y, s.z, 0.0];
- }
- (gpu::EnvMap { width: bake.width, height: bake.height, texels: bake.texels.clone() }, Vec3::ZERO, true)
- }
- scene::SkyData::Gradient(gr) => {
- static LAST: std::sync::Mutex<Option<(sky::Gradient, std::sync::Arc<sky::SkyBake>)>> = std::sync::Mutex::new(None);
- let mut last = LAST.lock().unwrap();
- let bake = match last.as_ref() {
- Some((k, b)) if k == gr => b.clone(),
- _ => {
- let b = std::sync::Arc::new(sky::bake_gradient(gr, 1024, 512));
- *last = Some((gr.clone(), b.clone()));
- b
- }
- };
- (gpu::EnvMap { width: bake.width, height: bake.height, texels: bake.texels.clone() }, Vec3::ZERO, true)
- }
- scene::SkyData::Color(c) => (gpu::EnvMap { width: 1, height: 1, texels: vec![[c.x, c.y, c.z, 1.0]] }, *c, false),
- scene::SkyData::None => (gpu::EnvMap { width: 1, height: 1, texels: vec![[0.0; 4]] }, Vec3::ZERO, false),
- };
+ let SkyBaked { env, color: sky_color, has_env, sun } = bake_sky(&sc.sky, sc.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) {
+ sc.lights[i].color = [c.x, c.y, c.z, 0.0];
+ }
let env_cdf = build_env_cdf(&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 = 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 * sky_color.x + 0.7152 * sky_color.y + 0.0722 * sky_color.z);
+ let env_max = sky_brightest(&env, sky_color);
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 = env_max >= env_nee_floor && (!has_env || env_nee_on());
+ 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);
@@ -871,6 +832,69 @@ fn build_env_cdf(env: &gpu::EnvMap) -> Vec<f32> {
marg
}
+/// A sky as the kernel takes it: the environment map (1 x 1 for a uniform sky or none), a uniform sky's radiance,
+/// whether the map is one to sample, and the illuminance the atmosphere leaves its sun's light.
+pub struct SkyBaked {
+ pub env: gpu::EnvMap,
+ pub color: Vec3,
+ pub has_env: bool,
+ pub sun: Option<Vec3>,
+}
+
+/// Bakes a scene's sky (`cloud_cover`: an atmosphere's; `altitude`: the camera's, m). The last atmosphere and the last
+/// gradient are kept: edits that leave the sky's inputs as they were reuse the bake.
+pub fn bake_sky(sky: &scene::SkyData, cloud_cover: f32, altitude: f32) -> SkyBaked {
+ match sky {
+ scene::SkyData::Atmosphere { sun_dir, sun_lux, rayleigh, mie, g: mie_g, ground, dynamic, glow, .. } => {
+ static LAST: std::sync::Mutex<Option<(Vec<u32>, std::sync::Arc<sky::SkyBake>)>> = std::sync::Mutex::new(None);
+ let alt = altitude;
+ let (bw, bh) = if *dynamic { sky::DYNAMIC_SKY } else { (1024, 512) };
+ let key: Vec<u32> = [*rayleigh, *mie, *mie_g, ground.x, ground.y, ground.z, sun_dir.x, sun_dir.y, sun_dir.z, sun_lux.x, sun_lux.y, sun_lux.z, alt, glow.uniform.x, glow.uniform.y, glow.uniform.z, glow.horizon.x, glow.horizon.y, glow.horizon.z, glow.height, bw as f32, cloud_cover].iter().map(|f| f.to_bits()).collect();
+ let mut last = LAST.lock().unwrap();
+ let bake = match last.as_ref() {
+ Some((k, b)) if *k == key => b.clone(),
+ _ => {
+ let atm = sky::Atmosphere::earth(*rayleigh, *mie, *mie_g, *ground);
+ let b = std::sync::Arc::new(if *dynamic || !glow.is_zero() || cloud_cover > 0.0 {
+ sky::bake_atmosphere_tables(&atm, &sky::SkyTables::new(&atm), *sun_dir, *sun_lux, alt, bw, bh, *glow, cloud_cover)
+ } else {
+ sky::bake_atmosphere(&atm, *sun_dir, *sun_lux, alt, bw, bh)
+ });
+ *last = Some((key, b.clone()));
+ b
+ }
+ };
+ SkyBaked { env: gpu::EnvMap { width: bake.width, height: bake.height, texels: bake.texels.clone() }, color: Vec3::ZERO, has_env: true, sun: Some(bake.sun_illuminance) }
+ }
+ scene::SkyData::Gradient(gr) => {
+ static LAST: std::sync::Mutex<Option<(sky::Gradient, std::sync::Arc<sky::SkyBake>)>> = std::sync::Mutex::new(None);
+ let mut last = LAST.lock().unwrap();
+ let bake = match last.as_ref() {
+ Some((k, b)) if k == gr => b.clone(),
+ _ => {
+ let b = std::sync::Arc::new(sky::bake_gradient(gr, 1024, 512));
+ *last = Some((gr.clone(), b.clone()));
+ b
+ }
+ };
+ SkyBaked { env: gpu::EnvMap { width: bake.width, height: bake.height, texels: bake.texels.clone() }, color: Vec3::ZERO, has_env: true, sun: None }
+ }
+ scene::SkyData::Color(c) => SkyBaked { env: gpu::EnvMap { width: 1, height: 1, texels: vec![[c.x, c.y, c.z, 1.0]] }, color: *c, has_env: false, sun: None },
+ scene::SkyData::None => SkyBaked { env: gpu::EnvMap { width: 1, height: 1, texels: vec![[0.0; 4]] }, color: Vec3::ZERO, has_env: false, sun: None },
+ }
+}
+
+/// 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)
+}
+
+/// Whether the sky is light-sampled (`Params::counts2[1]`): not when it is negligible next to the emitters (`floor`:
+/// `Prepared::env_nee_floor`), nor a baked sky with THREERT_ENV_NEE off. A uniform sky reads no table: always.
+pub fn sky_sampled(brightest: f32, floor: f32, has_env: bool) -> bool {
+ brightest >= floor && (!has_env || env_nee_on())
+}
+
/// UE GGXEnergyLookup equivalent: E.x = integral of D*Vis*NoL (F = 1), E.y = same weighted by (1-VoH)^5.
pub fn energy_lut() -> Vec<[f32; 4]> {
let n = 32usize;
diff --git a/renderer/src/live/edits.rs b/renderer/src/live/edits.rs
index 626c6ee..d114221 100644
--- a/renderer/src/live/edits.rs
+++ b/renderer/src/live/edits.rs
@@ -215,9 +215,7 @@ impl Grow<'_> {
/// Whether buffers of these sizes (bytes) can be bound (the device's storage binding and buffer limits): past them
/// the edit rebuilds instead (Bugbot on #131).
pub(super) fn fits(&self, sizes: &[u64]) -> bool {
- let l = self.g.device.limits();
- let max = (l.max_storage_buffer_binding_size as u64).min(l.max_buffer_size);
- sizes.iter().all(|&s| s <= max)
+ sizes.iter().all(|&s| self.g.buffer_fits(s))
}
/// Triangles: vertices, attributes, the BLASes' vertices, and in a scene with them (`colors`) vertex colours.
@@ -535,6 +533,12 @@ 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.
+ 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;
+ }
let now = shader_time(self.time);
let applied = self.sc.tables.apply(world, &changes, now).ok().flatten();
let Some(d) = applied else {
@@ -619,17 +623,8 @@ impl LiveCore {
let cover = self.sc.tables.cloud_cover;
let colour = crate::sky::sun_illuminance(&sky.atm, dir, lux, cover);
let e = &mut self.sc.tables;
- if let (Some(idx), Some(o)) = (e.light_index.get(&id), world.objects.get(&id)) {
- if let crate::world::Kind::Light(l) = &o.kind {
- if let Some(mut gl) = scene::gpu_light(l, world.world_matrix(id), o.power) {
- // (The sun: hidden with a rebuild, `World::set_visible`.)
- gl.color = [colour.x, colour.y, colour.z, 0.0];
- for &i in idx {
- e.lights[i] = gl;
- }
- self.sc.up.put_lights(&self.g.queue, &e.lights);
- }
- }
+ if e.set_sun_light(world, id, colour) {
+ self.sc.up.put_lights(&self.g.queue, &e.lights);
}
let _ = sky.ask.send((dir, lux, cover));
if self.fixed_dt.is_some() {
@@ -640,6 +635,46 @@ impl LiveCore {
self.lit_changed = self.frame.max(1);
}
+ /// Another sky (its kind, its parameters, its sun), as a build takes it: baked here, its environment map and CDF
+ /// put in place (of another size: a new texture, the scene bound again), the parameters that say how it is read,
+ /// and the lights it owns: the atmosphere's sun takes its colour from the bake, a light that is the sun no longer
+ /// 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 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;
+ // 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);
+ let mut d = tables::Dirty::default();
+ if let Some(id) = was.filter(|id| Some(*id) != sun) {
+ e.update_light(world, id, &mut d);
+ }
+ // (Whole, not its colour alone: the tables no longer update a light that is the sun, and it may have been
+ // turned in this commit.)
+ if let (Some(id), Some(c)) = (sun, baked.sun) {
+ d.lights |= e.set_sun_light(world, id, c);
+ }
+ if d.lights && !e.lights.is_empty() {
+ 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.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 };
@@ -654,7 +689,10 @@ 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 };
- self.g.write_env(&self.sc.up, &env, &cdf);
+ // (The worker bakes at the map's size: written in place.)
+ if !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;
diff --git a/renderer/src/live/inplace_tests.rs b/renderer/src/live/inplace_tests.rs
index 4ca04f8..68e5148 100644
--- a/renderer/src/live/inplace_tests.rs
+++ b/renderer/src/live/inplace_tests.rs
@@ -5,7 +5,7 @@ use super::*;
use crate::world::{Geometry, Kind, Settings};
use glam::Vec3;
-/// A wall, a panel before it and an emissive quad that lights both, under a dim sky; camera 4.
+/// A wall, a panel before it and an emissive quad that lights both, a directional light (20), no sky; camera 4.
fn world() -> World {
let mut w = World::default();
let mat = |color: f32, emissive: f32| serde_json::from_value(serde_json::json!({ "name": "m", "color": [color, color * 0.5, color], "opacity": 1, "metalness": 0, "roughness": 1, "emissive": [1, 1, 1], "emissiveIntensity": emissive, "doubleSided": true })).unwrap();
@@ -20,12 +20,24 @@ fn world() -> World {
w.set_transform(11, Vec3::new(-0.4, 0.0, 0.5), glam::Quat::IDENTITY, Vec3::ONE).unwrap();
w.set_object(12, "lamp".into(), None, mesh(3, 5), true, false).unwrap();
w.set_transform(12, Vec3::new(0.6, 0.3, 1.5), glam::Quat::from_rotation_y(2.6), Vec3::ONE).unwrap();
+ let sun = serde_json::from_value(serde_json::json!({ "type": "directional", "color": [1.0, 0.9, 0.8], "castShadow": true, "intensity": 2.0, "angularDiameter": 0.5 })).unwrap();
+ w.set_object(20, "sun".into(), None, Kind::Light(sun), true, false).unwrap();
+ w.set_transform(20, Vec3::ZERO, glam::Quat::from_rotation_x(-0.5) * glam::Quat::from_rotation_y(0.4), Vec3::ONE).unwrap();
w.set_object(4, "camera".into(), None, Kind::Camera(camera(50.0, None, manual(0.0))), true, false).unwrap();
w.set_transform(4, Vec3::new(0.0, 0.0, 5.0), glam::Quat::IDENTITY, Vec3::ONE).unwrap();
w.set_settings(Settings { camera: Some(4), ..Default::default() });
w
}
+fn sky(v: serde_json::Value) -> crate::desc::Sky {
+ serde_json::from_value(v).unwrap()
+}
+
+/// An atmosphere whose sun is light 20.
+fn atmosphere(dynamic: bool) -> serde_json::Value {
+ serde_json::json!({ "type": "atmosphere", "sun": 20, "groundAlbedo": [0.3, 0.3, 0.3], "rayleighScale": 1, "mieScale": 1, "mieAnisotropy": 0.8, "skyLightIntensity": 1, "dynamic": dynamic })
+}
+
fn manual(ev: f32) -> serde_json::Value {
serde_json::json!({ "mode": "manual", "ev100": ev })
}
@@ -39,12 +51,14 @@ fn camera(fov: f32, dof: Option<f32>, exposure: serde_json::Value) -> crate::des
}
/// A view's state: the kernel's parameters whole (as words; not the camera's four vectors, which the frame writes from
-/// the view), and what the passes after it take. (After a frame: the frame writes the light LOD's reference.)
+/// 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 rest = format!(
- "features {:#x} | exposure {} {:?} {:?} {:?} {:?} | lens {} {:?} view {:?} {:?} {} | post {} {:?} {} {:?} {:?} | {}",
- s.up.kernel.features, s.exposure, s.exposure_settings.ae, s.exposure_settings.ae2, s.exposure_settings.speed, s.exposure_settings.lx,
+ "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,
c.post_key, c.bloom, c.vignette, c.post, c.blur, c.scene_name
);
@@ -125,12 +139,25 @@ fn edits_in_place_leave_what_a_build_does() {
("no fog", true, Box::new(|w| w.set_environment(crate::desc::Environment { fog: None, ..w.environment.clone() }))),
("a background", true, Box::new(|w| w.set_environment(crate::desc::Environment { background: Some([0.2, 0.6, 0.1]), ..w.environment.clone() }))),
("no background", true, Box::new(|w| w.set_environment(crate::desc::Environment { background: None, ..w.environment.clone() }))),
+ ("a sky of one colour", true, Box::new(|w| w.set_environment(crate::desc::Environment { sky: sky(serde_json::json!({ "type": "color", "color": [0.3, 0.5, 1.0], "intensity": 0.5, "skyLightIntensity": 1 })), ..w.environment.clone() }))),
+ ("a gradient sky (a map where there was none)", true, Box::new(|w| w.set_environment(crate::desc::Environment { sky: sky(serde_json::json!({ "type": "gradient", "zenith": [0.1, 0.2, 0.9], "horizon": [0.9, 0.5, 0.2], "ground": [0.1, 0.1, 0.1], "intensity": 0.8, "skyLightIntensity": 1 })), ..w.environment.clone() }))),
+ ("an atmosphere with its sun", true, Box::new(|w| w.set_environment(crate::desc::Environment { sky: sky(atmosphere(false)), ..w.environment.clone() }))),
+ ("the atmosphere as a dynamic sky (a map of another size)", false, Box::new(|w| w.set_environment(crate::desc::Environment { sky: sky(atmosphere(true)), ..w.environment.clone() }))),
+ ("the sun turned (a sun's move)", true, Box::new(|w| w.set_transform(20, Vec3::ZERO, glam::Quat::from_rotation_x(-0.9) * glam::Quat::from_rotation_y(-0.3), Vec3::ONE).unwrap())),
+ ("one colour again (the sun is a light of its own)", true, Box::new(|w| w.set_environment(crate::desc::Environment { sky: sky(serde_json::json!({ "type": "color", "color": [1.0, 1.0, 1.0], "intensity": 0.2, "skyLightIntensity": 1 })), ..w.environment.clone() }))),
+ ("the light turned and made an atmosphere's sun at once", true, Box::new(|w| {
+ w.set_transform(20, Vec3::ZERO, glam::Quat::from_rotation_x(-0.3) * glam::Quat::from_rotation_y(0.8), Vec3::ONE).unwrap();
+ w.set_environment(crate::desc::Environment { sky: sky(atmosphere(false)), ..w.environment.clone() })
+ })),
+ ("no sky", true, Box::new(|w| w.set_environment(crate::desc::Environment { sky: sky(serde_json::json!({ "type": "color", "color": [0, 0, 0], "intensity": 0, "skyLightIntensity": 1 })), ..w.environment.clone() }))),
("the preset's overrides", false, Box::new(|w| w.set_settings(Settings { overrides: Some(serde_json::json!({ "native": { "maxBounces": 1, "energyCompensation": 0.0, "clampIndirect": 3.0 }, "post": { "vignette": 0.9 } })), name: "renamed".into(), ..w.settings.clone() }))),
("another preset", false, Box::new(|w| w.set_settings(Settings { preset: "preview".into(), overrides: None, ..w.settings.clone() }))),
];
for (what, seen, edit) in &edits {
edit(&mut w);
+ let t = std::time::Instant::now();
assert!(!live.commit(&mut w).unwrap(), "{what}: in place");
+ eprintln!("{what}: committed in {:.1} ms", t.elapsed().as_secs_f64() * 1e3);
let mut fresh = open(&w).unwrap();
// (With no history, as the new view has none: the radiance cache and the frames' histories hold the light as
// it was for a while, here as after a rebuild; fog gone was still 5 steps off after 264 frames.)
diff --git a/renderer/src/scene.rs b/renderer/src/scene.rs
index e02e2c2..b508082 100644
--- a/renderer/src/scene.rs
+++ b/renderer/src/scene.rs
@@ -410,7 +410,7 @@ pub enum SkyData {
None,
Color(Vec3),
/// `dynamic`: baked at `sky::DYNAMIC_SKY` (the live view re-bakes it as the sun moves); `glow`: night-sky radiance.
- Atmosphere { sun_dir: Vec3, sun_lux: Vec3, rayleigh: f32, mie: f32, g: f32, ground: Vec3, sun_node: Option<usize>, dynamic: bool, glow: crate::sky::Glow },
+ Atmosphere { sun_dir: Vec3, sun_lux: Vec3, rayleigh: f32, mie: f32, g: f32, ground: Vec3, dynamic: bool, glow: crate::sky::Glow },
Gradient(crate::sky::Gradient),
}
@@ -944,6 +944,65 @@ pub const MAX_MEDIA: usize = 32;
/// (pathtrace.wgsl `medium_span`).
pub const MEDIUM_HIDDEN: u32 = 2;
+/// The scene's sky as the renderer bakes it, and the atmosphere's sun (its light object: `Retained::sun`). `matrix`:
+/// an object's world matrix (the build has its own, a product in another order than `World::world_matrix`'s: the
+/// same to the bit only for an object without a parent).
+pub fn sky_data(w: &World, assets: &Path, matrix: &dyn Fn(u32) -> Mat4) -> Result<(SkyData, Option<u32>)> {
+ let mut sun_id = None;
+ let sky = match &w.environment.sky {
+ Sky::Atmosphere { sun, ground_albedo, rayleigh_scale, mie_scale, mie_anisotropy, dynamic, glow, horizon_glow, .. } => {
+ let sun_light = sun.and_then(|s| w.objects.get(&s).map(|o| (s, o)));
+ let (sun_dir, sun_lux) = match sun_light.map(|(s, o)| (matrix(s), &o.kind)) {
+ Some((m, Kind::Light(Light::Directional { color, intensity, .. }))) => (-m.transform_vector3(Vec3::NEG_Z).normalize(), Vec3::from(*color) * *intensity),
+ _ => (Vec3::Y, Vec3::ZERO),
+ };
+ sun_id = sun_light.map(|(s, _)| s);
+ SkyData::Atmosphere {
+ sun_dir,
+ sun_lux,
+ rayleigh: *rayleigh_scale,
+ mie: *mie_scale,
+ g: *mie_anisotropy,
+ ground: Vec3::from(*ground_albedo),
+ dynamic: *dynamic,
+ glow: crate::sky::glow_of(glow, horizon_glow),
+ }
+ }
+ Sky::Color { color, intensity, .. } if *intensity > 0.0 => SkyData::Color(Vec3::from(*color) * *intensity),
+ Sky::Color { .. } => SkyData::None,
+ Sky::Hdri { .. } => return Err(anyhow!("hdri environments are not supported by the native renderer yet")),
+ Sky::Gradient { zenith, horizon, ground, intensity, horizon_exponent, glow, clouds, .. } => {
+ let cloud_map = match clouds.as_ref().and_then(|c| c.map.map(|m| (c, m))) {
+ Some((c, tid)) => {
+ let t = w.textures.get(&tid).ok_or_else(|| anyhow!("unknown texture {tid}"))?;
+ let (key, image) = texture_image(t, assets)?;
+ Some(crate::sky::CloudMap {
+ key,
+ image,
+ threshold: c.threshold.unwrap_or([0.35, 0.85]),
+ gain: c.gain.unwrap_or(1.8),
+ offset: Vec3::from(c.color) * *intensity,
+ projection: c.projection.unwrap_or(0.35),
+ bias: c.bias.unwrap_or(0.25),
+ fade: c.fade.unwrap_or(4.0),
+ })
+ }
+ None => None,
+ };
+ SkyData::Gradient(crate::sky::Gradient {
+ zenith: Vec3::from(*zenith) * *intensity,
+ horizon: Vec3::from(*horizon) * *intensity,
+ ground: Vec3::from(*ground) * *intensity,
+ horizon_exponent: *horizon_exponent,
+ glow: glow.as_ref().map(|g| (Vec3::from(g.color) * g.intensity * *intensity, g.height.max(1e-3), g.width.map(|w| (w, g.power.unwrap_or(6.0))))),
+ clouds: if cloud_map.is_some() { None } else { clouds.as_ref().map(|c| (c.coverage, Vec3::from(c.color) * *intensity, c.scale.max(0.05), c.seed)) },
+ cloud_map,
+ })
+ }
+ };
+ Ok((sky, sun_id))
+}
+
/// A world's render preset: the preset its settings name, the settings' overrides over it, then `overrides`.
pub fn preset_of(w: &World, presets_dir: &Path, overrides: Option<&serde_json::Value>) -> Result<desc::Preset> {
let st = &w.settings;
@@ -1744,59 +1803,8 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
}
let env = &w.environment;
- let sky = match &env.sky {
- Sky::Atmosphere { sun, ground_albedo, rayleigh_scale, mie_scale, mie_anisotropy, dynamic, glow, horizon_glow, .. } => {
- let sun_light = sun.and_then(|s| w.objects.get(&s).map(|o| (s, o)));
- let (sun_dir, sun_lux) = match sun_light.map(|(s, o)| (worlds.get(&s).copied().unwrap_or(Mat4::IDENTITY), &o.kind)) {
- Some((m, Kind::Light(Light::Directional { color, intensity, .. }))) => (-m.transform_vector3(Vec3::NEG_Z).normalize(), Vec3::from(*color) * *intensity),
- _ => (Vec3::Y, Vec3::ZERO),
- };
- let idx = sun_light.and_then(|(s, _)| retained.light_nodes.iter().position(|id| *id == s));
- retained.sun = sun_light.map(|(s, _)| s);
- SkyData::Atmosphere {
- sun_dir,
- sun_lux,
- rayleigh: *rayleigh_scale,
- mie: *mie_scale,
- g: *mie_anisotropy,
- ground: Vec3::from(*ground_albedo),
- sun_node: idx,
- dynamic: *dynamic,
- glow: crate::sky::glow_of(glow, horizon_glow),
- }
- }
- Sky::Color { color, intensity, .. } if *intensity > 0.0 => SkyData::Color(Vec3::from(*color) * *intensity),
- Sky::Color { .. } => SkyData::None,
- Sky::Hdri { .. } => return Err(anyhow!("hdri environments are not supported by the native renderer yet")),
- Sky::Gradient { zenith, horizon, ground, intensity, horizon_exponent, glow, clouds, .. } => {
- let cloud_map = match clouds.as_ref().and_then(|c| c.map.map(|m| (c, m))) {
- Some((c, tid)) => {
- let t = w.textures.get(&tid).ok_or_else(|| anyhow!("unknown texture {tid}"))?;
- let (key, image) = texture_image(t, assets)?;
- Some(crate::sky::CloudMap {
- key,
- image,
- threshold: c.threshold.unwrap_or([0.35, 0.85]),
- gain: c.gain.unwrap_or(1.8),
- offset: Vec3::from(c.color) * *intensity,
- projection: c.projection.unwrap_or(0.35),
- bias: c.bias.unwrap_or(0.25),
- fade: c.fade.unwrap_or(4.0),
- })
- }
- None => None,
- };
- SkyData::Gradient(crate::sky::Gradient {
- zenith: Vec3::from(*zenith) * *intensity,
- horizon: Vec3::from(*horizon) * *intensity,
- ground: Vec3::from(*ground) * *intensity,
- horizon_exponent: *horizon_exponent,
- glow: glow.as_ref().map(|g| (Vec3::from(g.color) * g.intensity * *intensity, g.height.max(1e-3), g.width.map(|w| (w, g.power.unwrap_or(6.0))))),
- clouds: if cloud_map.is_some() { None } else { clouds.as_ref().map(|c| (c.coverage, Vec3::from(c.color) * *intensity, c.scale.max(0.05), c.seed)) },
- cloud_map,
- })
- }
- };
+ let (sky, sun) = sky_data(w, assets, &|id| worlds.get(&id).copied().unwrap_or(Mat4::IDENTITY))?;
+ retained.sun = sun;
let mut stats = HashMap::new();
stats.insert("load_ms", t0.elapsed().as_secs_f64() * 1000.0);
diff --git a/renderer/src/tables.rs b/renderer/src/tables.rs
index 989247e..0a03707 100644
--- a/renderer/src/tables.rs
+++ b/renderer/src/tables.rs
@@ -195,7 +195,22 @@ impl Tables {
Ok(Some(d))
}
- fn update_light(&mut self, w: &World, id: u32, d: &mut Dirty) {
+ /// The atmosphere's sun: its light's entries as the world has it now (its direction, its size), with the colour the
+ /// atmosphere leaves it (`colour`: illuminance through the atmosphere). Whether any entry was written.
+ pub fn set_sun_light(&mut self, w: &World, id: u32, colour: glam::Vec3) -> bool {
+ let (Some(idx), Some(o)) = (self.light_index.get(&id), w.objects.get(&id)) else { return false };
+ let Kind::Light(l) = &o.kind else { return false };
+ // (The sun: hidden with a rebuild, `World::set_visible`.)
+ let Some(mut gl) = scene::gpu_light(l, w.world_matrix(id), o.power) else { return false };
+ gl.color = [colour.x, colour.y, colour.z, 0.0];
+ for &i in idx {
+ self.lights[i] = gl;
+ }
+ !idx.is_empty()
+ }
+
+ /// A light's entries as its description and place say (not the atmosphere's sun: `retained.sun`).
+ pub fn update_light(&mut self, w: &World, id: u32, d: &mut Dirty) {
if self.retained.sun == Some(id) {
return; // colour comes from the sky bake
}
diff --git a/renderer/src/world.rs b/renderer/src/world.rs
index e7180ce..42d4449 100644
--- a/renderer/src/world.rs
+++ b/renderer/src/world.rs
@@ -290,6 +290,8 @@ pub struct Changes {
pub camera: bool,
/// The atmosphere's sun moved (time of day): the live view rewrites its light and re-bakes the sky in place.
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.)
@@ -972,12 +974,9 @@ impl World {
pub fn set_environment(&mut self, e: desc::Environment) {
// Fog appearing, turning volumetric or going, and a background appearing or going, are kernel features: another
- // variant of the kernel, not another scene. A new sky is baked with the scene (a rebuild).
- if self.environment.sky != e.sky {
- self.changes.structural = true;
- } else {
- self.changes.environment = true;
- }
+ // variant of the kernel, not another scene. Another sky is another environment map.
+ self.changes.sky |= self.environment.sky != e.sky;
+ self.changes.environment = true;
self.environment = e;
}
@@ -1525,7 +1524,7 @@ mod tests {
}
/// three.js's background (F_BACKGROUND) and the fog's shape (F_FOG, F_VOLUME) are kernel features: appearing or
- /// going is a parameter edit, as a new colour is (the live view takes the kernel's other variant). A new sky rebuilds.
+ /// going is a parameter edit, as a new colour is (the live view takes the kernel's other variant). So is another sky.
#[test]
fn a_background_and_fog_come_and_go_in_place() {
let mut w = World::default();
@@ -1543,7 +1542,8 @@ mod tests {
assert!(!c.structural && c.environment, "fog appears");
let sky: desc::Sky = serde_json::from_value(serde_json::json!({ "type": "color", "color": [0, 0, 1], "intensity": 1, "skyLightIntensity": 1 })).unwrap();
w.set_environment(desc::Environment { sky, ..base.clone() });
- assert!(w.take_changes().structural, "another sky");
+ let c = w.take_changes();
+ assert!(!c.structural && c.sky && c.environment, "another sky");
}
/// The scene camera's lens and exposure, and the preset: in place. Another camera's lens: nothing to do.