diff --git a/packages/scene/README.md b/packages/scene/README.md index eefb1eaf..af88d4b8 100644 --- a/packages/scene/README.md +++ b/packages/scene/README.md @@ -70,6 +70,19 @@ This package builds the scene. A ThreeRT client draws it: Games add state and input with [`@threert/gameplay`](https://www.npmjs.com/package/@threert/gameplay); destructible voxel worlds use [`@threert/voxel`](https://www.npmjs.com/package/@threert/voxel). +## HDRI environments + +Use a linear equirectangular OpenEXR or Radiance HDR texture to light the scene, reflect in materials, and show as the sky. + +```typescript +import { HDRIEnvironment, Texture } from "@threert/scene"; + +scene.environment = new HDRIEnvironment(new Texture("assets/sky.exr", "linear"), 1, Math.PI / 2); +scene.backgroundPanorama = new HDRIEnvironment(new Texture("assets/camera-sky.exr", "linear")); +``` + +Rotation is in radians around +Y. `intensity` scales both the lighting and the visible sky. `skyLightIntensity` scales lighting and reflections only. Set `scene.background` for a solid color or `scene.backgroundPanorama` for a separate image with its own intensity and rotation. + ## Links [threert.dev](https://threert.dev) · [Docs](https://threert.dev/docs/) · [Showcase](https://threert.dev/showcase/) · [GitHub](https://github.com/meshy-dev/ThreeRT) diff --git a/packages/scene/src/core.ts b/packages/scene/src/core.ts index 02566c50..93ac359f 100644 --- a/packages/scene/src/core.ts +++ b/packages/scene/src/core.ts @@ -1063,6 +1063,8 @@ export class Scene extends Object3D { environment: Environment | null = null; /** three.js: what camera rays that miss show (a colour, sRGB as given; null: the environment). It lights nothing. */ background: Color | null = null; + /** Equirectangular image for camera rays. Takes precedence over `background` and does not light the scene. */ + backgroundPanorama: HDRIEnvironment | null = null; /** Height fog (three.js's `Fog` / `FogExp2` are kinds of it). */ fog: ExponentialHeightFog | null = null; /** Global surface wetness 0..1 (material functions read it as `i.wetness`: SurfaceMaterial's `wet` / `puddles`, @@ -2384,11 +2386,13 @@ export class SkyColor { } } +/** An equirectangular texture in its scene orientation. Rotation is around +Y, in radians. */ export class HDRIEnvironment { readonly kind = "hdri"; texture: Texture; intensity: number; rotation: number; + /** Lighting and reflections multiplier, in addition to `intensity`. */ skyLightIntensity = 1; constructor(texture: Texture, intensity = 1, rotation = 0) { this.texture = texture; diff --git a/packages/scene/src/engine.ts b/packages/scene/src/engine.ts index 033f1d40..bc46c5a5 100644 --- a/packages/scene/src/engine.ts +++ b/packages/scene/src/engine.ts @@ -100,6 +100,7 @@ export interface EnvironmentDesc { sky: SkyDesc; /** three.js `scene.background`: what camera rays that miss show (linear rgb, displayed as given), lighting nothing. */ background?: Vec3; + backgroundPanorama?: { texture: number; intensity: number; rotation: number }; fog?: FogDesc; wetness?: number; rain?: number; @@ -1554,7 +1555,9 @@ export class SceneBinding { const e: EnvironmentDesc = { sky: this.skyDesc() }; // three.js's background colour is shown as given: here as radiance at the level of the scene's light, so that it // sits with the lit surfaces under any exposure (white: a white diffuse surface in the key light). - if (scene.background) e.background = vec3(scene.background).map((c) => c * this.lightLevel()) as Vec3; + const panorama = scene.backgroundPanorama; + if (panorama) e.backgroundPanorama = { texture: this.textureId(panorama.texture)!, intensity: panorama.intensity, rotation: panorama.rotation }; + else if (scene.background) e.background = vec3(scene.background).map((c) => c * this.lightLevel()) as Vec3; // Ambient lights light the scene, they are not seen: without a background colour, black (three.js's clear colour). else if (!scene.environment && e.sky.type !== "atmosphere" && this.ambientSky()) e.background = [0, 0, 0]; if (scene.fog) { diff --git a/renderer/Cargo.toml b/renderer/Cargo.toml index 216e9e78..67e087c3 100644 --- a/renderer/Cargo.toml +++ b/renderer/Cargo.toml @@ -15,7 +15,7 @@ bytemuck = { version = "1", features = ["derive"] } serde = { version = "1", features = ["derive"] } serde_json = "1" gltf = { version = "1.4", features = ["KHR_materials_emissive_strength", "KHR_texture_transform", "KHR_materials_ior", "KHR_materials_transmission", "extensions"] } -image = { version = "0.25", default-features = false, features = ["png", "jpeg", "exr"] } +image = { version = "0.25", default-features = false, features = ["png", "jpeg", "exr", "hdr"] } glam = { version = "0.30", features = ["bytemuck"] } rayon = "1.10" anyhow = "1" diff --git a/renderer/shaders/pathtrace.wgsl b/renderer/shaders/pathtrace.wgsl index 6eff489b..c25dd174 100644 --- a/renderer/shaders/pathtrace.wgsl +++ b/renderer/shaders/pathtrace.wgsl @@ -103,6 +103,7 @@ struct Params { env: vec4, // has env map, env width, env height, sun light index (-1 none) misc: vec4, // clamp (absolute radiance), - (the emitters' total weight is their table's: `emitter_totals`), env total weight, _ sky_color: vec4, // constant sky radiance when no env map + hdri: vec4, // longitude offset in turns, lighting scale, visible scale, enabled counts2: vec4, // directional lights (first in `lights`), environment NEE on, output height for texture LOD (0 = traced height), first shadowed local light time: vec4, // scene time (s), wetness, rain, - fog: vec4, // density at fog height (1/m), height falloff (1/m), fog height, start distance (m) @@ -118,7 +119,7 @@ struct Params { ltree: vec4, // light tree (ltree.rs): -, its entry count (bits: the moving emitters' first), - (the tail's share is the table's: `emitter_totals`), candidates at camera hits (0 = off) procs: vec4, // procedural geometry (F_PROC): -, object count, first record in `instances`, - aerial: vec4, // the sky's aerial perspective (F_AERIAL): density multiple, Rayleigh scale, Mie scale, - - background: vec4, // three.js scene.background (radiance), 1 (F_BACKGROUND) + background: vec4, // colour (RGB, 1) or panorama (longitude offset, intensity, 0, 2) ltile: vec4, // live light tiles (`lt_list_start`): 1 with last frame's lists (0: none), tiles a row, the grid's offset when they were built (x | y << 16), candidates a vertex the camera sees takes from its list ltile2: vec4, // the traced size they were built at, -, - lt_cam: array, 4>, // the camera they were built under: position (w = tan(fov/2)), forward (w = aspect), right, up @@ -153,6 +154,7 @@ const VERTEX_VEC4: u32 = 3u; @group(0) @binding(7) var textures: texture_2d_array; @group(0) @binding(8) var samp: sampler; @group(0) @binding(9) var env_tex: texture_2d; +@group(0) @binding(20) var background_tex: texture_2d; // The scene's flat arrays, sections of one buffer of 32-bit words (heap.rs `Stream`), each from the word // `P.word_first` names: the environment's CDF (floats: [0, H) the rows' marginal CDF, then H rows of W conditional // entries; `env_cdf_at`), the procedural data (`pword`, `gdata`), the vertex colours (`vcolor_word`), the instances' @@ -1901,8 +1903,20 @@ fn env_uv(d: vec3) -> vec2 { return vec2(u, v); } +// The sampler wraps longitude. Clamp to the edge rows so opposite poles do not blend. +fn panorama_radiance(tex: texture_2d, uv: vec2) -> vec3 { + let edge = 0.5 / f32(textureDimensions(tex).y); + return textureSampleLevel(tex, samp, vec2(uv.x, clamp(uv.y, edge, 1.0 - edge)), 0.0).rgb; +} + +fn hdri_uv(d: vec3, offset: f32) -> vec2 { + let uv = env_uv(d); + return vec2(fract(uv.x + offset), uv.y); +} + fn env_radiance(d: vec3) -> vec3 { if (P.env.x < 0.5) { return P.sky_color.rgb; } + if (P.hdri.w > 0.0) { return panorama_radiance(env_tex, hdri_uv(d, P.hdri.x)) * P.hdri.y; } return textureSampleLevel(env_tex, samp, env_uv(d), 0.0).rgb; } @@ -1910,7 +1924,8 @@ fn env_pdf(d: vec3) -> f32 { if (P.env.x < 0.5) { return 1.0 / (4.0 * PI); } let w = u32(P.env.y); let h = u32(P.env.z); let uv = env_uv(d); - let x = min(u32(uv.x * f32(w)), w - 1u); + let u = select(uv.x, fract(uv.x + P.hdri.x), P.hdri.w > 0.0); + let x = min(u32(u * f32(w)), w - 1u); let y = min(u32(uv.y * f32(h)), h - 1u); @if(!strict) let row_p = env_cdf_at(y) - select(0.0, env_cdf_at(y - 1u), y > 0u); @if(strict) let row_p = env_cdf_at(y) - select(0.0, env_cdf_at(max(y, 1u) - 1u), y > 0u); @@ -1945,7 +1960,7 @@ fn sample_env(rd: u32) -> vec3 { let u = (f32(x) + u4.z) / f32(w); let v = (f32(y) + u4.w) / f32(h); let theta = v * PI; - let phi = (u - 0.5) * 2.0 * PI; + let phi = (u - P.hdri.x - 0.5) * 2.0 * PI; return vec3(sin(theta) * sin(phi), cos(theta), -sin(theta) * cos(phi)); } @@ -1967,11 +1982,21 @@ fn offset_origin(p: vec3, n: vec3) -> vec3 { return p + n * (1e-4 * max(1.0, max(abs(p.x), max(abs(p.y), abs(p.z))))); } -// What a BSDF-sampled ray (solid-angle pdf `pdf`; 0 = the camera ray, no MIS) that left the scene brings back: the -// environment and the directional lights' disks, MIS-weighted against their sampling in `direct_light`. -fn sky_mis(d: vec3, pdf: f32) -> vec3 { +// What a ray that left the scene brings back. A solid-angle PDF of zero disables MIS. +// The environment and the directional lights' disks are weighed against their sampling in `direct_light`. +fn sky_mis(d: vec3, pdf: f32, camera: bool) -> vec3 { // three.js scene.background: what camera rays (and paths bent straight through glass) see where nothing is. - if (has(F_BACKGROUND) && pdf <= 0.0) { return P.background.rgb; } + if (camera) { + if (has(F_BACKGROUND)) { + if (P.background.w > 1.0) { + return panorama_radiance(background_tex, hdri_uv(d, P.background.x)) * P.background.y; + } + return P.background.rgb; + } + if (P.hdri.w > 0.0) { + return panorama_radiance(env_tex, hdri_uv(d, P.hdri.x)) * P.hdri.z; + } + } var wgt = 1.0; if (pdf > 0.0 && P.counts2.y != 0u) { wgt = power_heuristic(pdf, env_pdf(d)); @@ -3707,7 +3732,7 @@ fn cache_train(s0: Surface, d0: vec3, cone0: vec2, depth: u32, insert: tr *= mh.tr; } if (miss) { - gather[k] = g + tr * sky_mis(l, pdf); + gather[k] = g + tr * sky_mis(l, pdf, false); break; } cur_depth = 3u + k; @@ -3902,7 +3927,7 @@ fn guide_hit(origin: vec3, dir: vec3, footprint: f32, through_glass: b let h = trace(o, d, INF, TRACE_CLOSEST); if (h.tri == 0xffffffffu) { var sky = env_radiance(d); - if (through_glass) { sky = sky_mis(d, 0.0); } + if (through_glass) { sky = sky_mis(d, 0.0, true); } return GuideHit(guide_color(sky), -d, 1.0, select(first, 1e4, i == 0u)); } if (i == 0u) { first = h.t; } @@ -4439,7 +4464,8 @@ fn main(@builtin(global_invocation_id) gid: vec3) { } } if (hit.tri == 0xffffffffu) { - var c = thr * sky_mis(d, select(0.0, last_pdf, depth > 0u && !bent)); + let camera_sky = depth == 0u || (straight && behind_glass); + var c = thr * sky_mis(d, select(0.0, last_pdf, depth > 0u && !bent), camera_sky); if (depth > 1u && !straight) { let lum = luminance(c); if (lum > clamp_v) { c *= clamp_v / lum; } diff --git a/renderer/src/desc.rs b/renderer/src/desc.rs index a9baeb1d..6944784e 100644 --- a/renderer/src/desc.rs +++ b/renderer/src/desc.rs @@ -137,6 +137,8 @@ pub struct Environment { /// three.js `scene.background`: what camera rays that miss see (radiance, linear rgb), lighting nothing. #[serde(default)] pub background: Option, + #[serde(default, rename = "backgroundPanorama")] + pub background_panorama: Option, /// Global surface wetness 0..1 (material functions' `i.wetness`). #[serde(default)] pub wetness: f32, @@ -149,6 +151,14 @@ pub struct Environment { pub cloud_cover: f32, } +/// Equirectangular background radiance for camera rays. +#[derive(Deserialize, Debug, Clone)] +pub struct BackgroundPanorama { + pub texture: u32, + pub intensity: f32, + pub rotation: f32, +} + /// Exponential height fog (UE ExponentialHeightFog): extinction `density * exp(-heightFalloff * (y - height))`. #[derive(Deserialize, Debug, Clone)] #[serde(rename_all = "camelCase")] diff --git a/renderer/src/files.rs b/renderer/src/files.rs index 5ee603f8..7a11611e 100644 --- a/renderer/src/files.rs +++ b/renderer/src/files.rs @@ -103,10 +103,15 @@ pub fn version(path: &Path) -> (u64, u128) { /// A texture file decoded to RGBA8. pub fn image(path: &Path) -> Result { + Ok(image_data(path)?.into_rgba8()) +} + +/// Decode a file without reducing its colour depth. +pub fn image_data(path: &Path) -> Result { #[cfg(not(target_arch = "wasm32"))] - return Ok(image::open(path)?.to_rgba8()); + return Ok(image::open(path)?); #[cfg(target_arch = "wasm32")] - return Ok(image::load_from_memory(&read(path)?)?.to_rgba8()); + return Ok(image::load_from_memory(&read(path)?)?); } /// A glTF / GLB file: its document, and the binary chunk of a GLB. (The buffers and images it names beside it are diff --git a/renderer/src/gpu.rs b/renderer/src/gpu.rs index c7cee565..55fcdf15 100644 --- a/renderer/src/gpu.rs +++ b/renderer/src/gpu.rs @@ -136,6 +136,8 @@ pub struct Params { pub env: [f32; 4], pub misc: [f32; 4], pub sky_color: [f32; 4], + /// HDRI longitude offset in turns, lighting scale, visible scale, enabled. + pub hdri: [f32; 4], pub counts2: [u32; 4], // directional lights (first in the light list), -, -, - pub time: [f32; 4], // scene time (s), wetness, rain, - pub fog: [f32; 4], // density at fog height (1/m), height falloff (1/m), fog height (m), start distance (m) @@ -160,7 +162,7 @@ pub struct Params { pub procs: [u32; 4], /// The sky's aerial perspective (F_AERIAL; `scene::aerial_params`): density multiple, Rayleigh scale, Mie scale, -. pub aerial: [f32; 4], - /// three.js `scene.background` (F_BACKGROUND): its radiance, 1. + /// Camera background (F_BACKGROUND): RGB, 1 for a colour, or longitude offset, intensity, 0, 2 for a panorama. pub background: [f32; 4], /// The live light tiles (pathtrace.wgsl "Light tiles"; live/frame.rs): 1 with the last frame's lists (0: none /// this frame), tiles a row, the grid's offset when they were built (x | y << 16), candidates a @@ -340,6 +342,7 @@ pub(crate) fn kernel_layout_entries(shape: LayoutShape) -> [Vec, pub sampler: wgpu::Sampler, /// The density grids' atlas (binding 19), or the one-cell texture of a scene without grids. pub grid_view: wgpu::TextureView, @@ -2056,10 +2060,11 @@ pub fn features_of(ms: &[crate::scene::GpuMaterial], environment: u32, textures: f } +#[derive(Clone)] pub struct EnvMap { pub width: u32, pub height: u32, - pub texels: Vec<[f32; 4]>, + pub texels: std::sync::Arc<[[f32; 4]]>, } pub struct Frame { @@ -2691,8 +2696,10 @@ 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 = self.env_texture(env); + let env_tex = self.env_texture(env)?; let env_view = env_tex.create_view(&Default::default()); + let background_view = scene.background_map.as_ref() + .map(|map| self.env_texture(map).map(|t| t.create_view(&Default::default()))).transpose()?; let sampler = d.create_sampler(&wgpu::SamplerDescriptor { address_mode_u: wgpu::AddressMode::Repeat, address_mode_v: wgpu::AddressMode::Repeat, @@ -2859,7 +2866,7 @@ impl Gpu { fn e(binding: u32, b: &wgpu::Buffer) -> wgpu::BindGroupEntry<'_> { wgpu::BindGroupEntry { binding, resource: b.as_entire_binding() } } - let bg_parts = BindParts { nodes: b_nodes, leaves: b_leaves, tex_view, env_view, sampler, grid_view }; + let bg_parts = BindParts { nodes: b_nodes, leaves: b_leaves, tex_view, env_view, background_view, sampler, grid_view }; let bg = self.scene_bind_group(&SceneBuffers { params: &b_params, vertices: &b_vertices, heap: &heap, words: &words, prev_vertices: &b_prev, accum: &b_accum, parts: &bg_parts, accel: accel.as_ref() }); let kernel = Kernel { approx: self.approx, ..Kernel::new(scene) }; // Translucent particles (hardware RT): the translucency pass's own TLAS, built again after the particle pass: @@ -3540,7 +3547,9 @@ impl Gpu { } /// An environment map's texture, with its texels. - fn env_texture(&self, env: &EnvMap) -> wgpu::Texture { + fn env_texture(&self, env: &EnvMap) -> Result { + let limit = self.device.limits().max_texture_dimension_2d; + anyhow::ensure!(env.width.max(env.height) <= limit, "environment map {} x {} exceeds device texture limit {limit}", env.width, env.height); 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 }, @@ -3552,7 +3561,7 @@ impl Gpu { view_formats: &[], }); self.write_env_texels(&t, env); - t + Ok(t) } fn write_env_texels(&self, t: &wgpu::Texture, env: &EnvMap) { @@ -3583,13 +3592,15 @@ impl Gpu { 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; - } + let grow = bytes > up.words.cap(Stream::EnvCdf); + if grow && !self.buffer_fits(up.words.size_with(Stream::EnvCdf, bytes)) { + return false; + } + let Ok(texture) = self.env_texture(env) else { return false }; + if grow { up.words.grow(&self.device, &self.queue, Stream::EnvCdf, bytes); } - up.env_tex = self.env_texture(env); + up.env_tex = texture; 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(); @@ -3867,6 +3878,7 @@ impl Gpu { view(9, &p.env_view), view(10, &p.grid_view), buffer_entry(11, b.accum), + view(20, p.background_view.as_ref().unwrap_or(&p.env_view)), ]; if !self.hwrt { entries.push(buffer_entry(2, &p.leaves)); diff --git a/renderer/src/lib.rs b/renderer/src/lib.rs index 094dd2c9..e675e3e1 100644 --- a/renderer/src/lib.rs +++ b/renderer/src/lib.rs @@ -74,6 +74,8 @@ pub struct Prepared { pub emitter_runs: EmitterRuns, pub env: gpu::EnvMap, pub env_cdf: Vec, + /// The sky's peak luminance before applying any HDRI intensity. + pub env_brightest: f32, pub params: gpu::Params, pub energy: Vec<[f32; 4]>, /// Emissive triangles (also those at power 0), for re-weighting `emitters` after power / material edits. @@ -722,6 +724,7 @@ pub fn prepare_as(hwrt: bool, sc: &mut scene::Scene, timings: &mut Vec<(String, env: [0.0, 0.0, 0.0, -1.0], misc: [0.0, total, 0.0, 0.0], sky_color: [0.0; 4], + hdri: [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], @@ -752,7 +755,7 @@ pub fn prepare_as(hwrt: bool, sc: &mut scene::Scene, timings: &mut Vec<(String, }; let mut params = params; params.set_preset(&sc.preset.native, &cam.exposure); - baked.write(&mut params, env_nee_floor); + let env_brightest = baked.write(&mut params, env_nee_floor); sc.environment.write(&mut params); let env = baked.env; let energy = energy_lut(); @@ -781,7 +784,7 @@ pub fn prepare_as(hwrt: bool, sc: &mut scene::Scene, timings: &mut Vec<(String, sc.gpu_instances[r].info[2] = i.verts; sc.gpu_instances[r].n[2][3] = f32::from_bits(i.prev); } - Prepared { tri_verts, nodes, emitters, gpu_emitter_tris, emitter_runs, env, env_cdf, params, energy, emitter_tris, light_tree, env_nee_floor, moving_mats } + Prepared { tri_verts, nodes, emitters, gpu_emitter_tris, emitter_runs, env, env_cdf, env_brightest, params, energy, emitter_tris, light_tree, env_nee_floor, moving_mats } } /// The scene's triangles, in the GPU's order (`tri_verts`, `sc.attrs`), as vertices and indices (indexed.rs). Each @@ -947,6 +950,7 @@ pub struct SkyBaked { pub env: gpu::EnvMap, pub color: Vec3, pub has_env: bool, + pub hdri: [f32; 4], pub sun: Option, /// A planet's limb row (`sky::SkyBake::horizon_v`), 0 otherwise: `Params::sky_color[3]`. pub horizon_v: f32, @@ -979,7 +983,7 @@ pub fn bake_sky(sky: &scene::SkyData, cloud_cover: f32, altitude: f32) -> SkyBak 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), horizon_v: bake.horizon_v } + SkyBaked { env: gpu::EnvMap { width: bake.width, height: bake.height, texels: bake.texels.clone().into() }, color: Vec3::ZERO, has_env: true, hdri: [0.0; 4], sun: Some(bake.sun_illuminance), horizon_v: bake.horizon_v } } scene::SkyData::Gradient(gr) => { static LAST: std::sync::Mutex)>> = std::sync::Mutex::new(None); @@ -992,23 +996,41 @@ pub fn bake_sky(sky: &scene::SkyData, cloud_cover: f32, altitude: f32) -> SkyBak b } }; - SkyBaked { env: gpu::EnvMap { width: bake.width, height: bake.height, texels: bake.texels.clone() }, color: Vec3::ZERO, has_env: true, sun: None, horizon_v: 0.0 } + SkyBaked { env: gpu::EnvMap { width: bake.width, height: bake.height, texels: bake.texels.clone().into() }, color: Vec3::ZERO, has_env: true, hdri: [0.0; 4], sun: None, horizon_v: 0.0 } } - 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, horizon_v: 0.0 }, - scene::SkyData::None => SkyBaked { env: gpu::EnvMap { width: 1, height: 1, texels: vec![[0.0; 4]] }, color: Vec3::ZERO, has_env: false, sun: None, horizon_v: 0.0 }, + scene::SkyData::Hdri { map, rotation, intensity, sky_light_intensity } => SkyBaked { + env: map.clone(), color: Vec3::ZERO, has_env: true, + hdri: hdri_params(*rotation, *intensity, *sky_light_intensity), + sun: None, horizon_v: 0.0, + }, + scene::SkyData::Color(c) => SkyBaked { env: gpu::EnvMap { width: 1, height: 1, texels: [[c.x, c.y, c.z, 1.0]].into() }, color: *c, has_env: false, hdri: [0.0; 4], sun: None, horizon_v: 0.0 }, + scene::SkyData::None => SkyBaked { env: gpu::EnvMap { width: 1, height: 1, texels: [[0.0; 4]].into() }, color: Vec3::ZERO, has_env: false, hdri: [0.0; 4], sun: None, horizon_v: 0.0 }, } } 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) { + /// light-sampled (`floor`: `Prepared::env_nee_floor`). Returns the peak luminance before scaling. + pub fn write(&self, p: &mut gpu::Params, floor: f32) -> 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, self.horizon_v]; - p.counts2[1] = sky_sampled(sky_brightest(&self.env, self.color), floor, self.has_env) as u32; + p.hdri = self.hdri; + let brightest = sky_brightest(&self.env, self.color); + write_sky_sampling(p, brightest, floor, self.has_env); + brightest } } +fn hdri_params(rotation: f32, intensity: f32, sky_light_intensity: f32) -> [f32; 4] { + let intensity = intensity.max(0.0); + [scene::panorama_offset(rotation), intensity * sky_light_intensity.max(0.0), intensity, 1.0] +} + +fn write_sky_sampling(p: &mut gpu::Params, brightest: f32, floor: f32, has_env: bool) { + let brightest = if p.hdri[3] > 0.0 { brightest * p.hdri[1] } else { brightest }; + p.counts2[1] = (brightest > 0.0 && sky_sampled(brightest, floor, 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.rs index b1b9de1a..fa66db85 100644 --- a/renderer/src/live/edits.rs +++ b/renderer/src/live/edits.rs @@ -1248,6 +1248,21 @@ impl LiveCore { /// 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 { + let floor = self.env.sky.floor; + let hdri_texture = match &world.environment.sky { + crate::desc::Sky::Hdri { texture, rotation, intensity, sky_light_intensity } => { + // HDRI texture edits mark the world structural, so this path only sees edits to the sky's parameters. + if let Some((_, brightest)) = self.env.sky.hdri.filter(|(loaded, _)| loaded == texture) { + let params = &mut self.sc.base; + params.hdri = crate::hdri_params(*rotation, *intensity, *sky_light_intensity); + crate::write_sky_sampling(params, brightest, floor, true); + self.lit_changed = self.frame.max(1); + return Ok(true); + } + Some(*texture) + } + _ => None, + }; let (sky, sun) = scene::sky_data(world, &self.assets, &|id| world.world_matrix(id))?; let altitude = super::load::sky_altitude(&sky).unwrap_or_else(|| 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; @@ -1255,8 +1270,7 @@ impl LiveCore { if !self.g.put_env(&mut self.sc.up, &baked.env, &crate::build_env_cdf(&baked.env)) { return Ok(false); } - let floor = self.env.sky.floor; - baked.write(&mut self.sc.base, floor); + let brightest = 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); @@ -1273,7 +1287,8 @@ 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.env.sky = SkyState { map: (baked.env.width, baked.env.height), altitude, floor, cover, worker: None }; + let hdri = hdri_texture.map(|texture| (texture, brightest)); + self.env.sky = SkyState { map: (baked.env.width, baked.env.height), hdri, altitude, floor, cover, worker: None }; self.lit_changed = self.frame.max(1); Ok(true) } diff --git a/renderer/src/live/inplace_tests.rs b/renderer/src/live/inplace_tests.rs index a428ca32..0f22e4a1 100644 --- a/renderer/src/live/inplace_tests.rs +++ b/renderer/src/live/inplace_tests.rs @@ -787,6 +787,53 @@ fn a_skinned_primitive_without_normals_is_shaded_by_its_triangles() { assert!(seen.dot(normal).abs() > 0.999 && (seen.length() - 1.0).abs() < 1e-3, "the picture's middle has the normal {seen}; the triangle's is {normal}"); } +#[test] +fn hdri_parameter_edits_reuse_the_uploaded_panorama() { + let g = match gpu::Gpu::new() { + Ok(g) => g, + Err(e) => return eprintln!("skipped: {e}"), + }; + let mut w = world(); + let panorama = |width, value| crate::world::Texture { + source: crate::world::TextureSource::Pixels { + width, height: 1, rgba: std::sync::Arc::new([value, value, value, 255].repeat(width as usize)), + }, + srgb: false, wrap: true, repeat: [1.0; 2], offset: [0.0; 2], + }; + w.set_texture(1, panorama(2, 255)).unwrap(); + w.set_texture(2, panorama(4, 0)).unwrap(); + let environment = |texture, rotation, intensity, sky_light_intensity| crate::desc::Environment { + sky: crate::desc::Sky::Hdri { texture, rotation, intensity, sky_light_intensity }, + ..World::default().environment + }; + w.set_environment(environment(1, 0.0, 1.0, 1.0)); + let mut live = LiveCore::new(g, &w, Path::new("."), &crate::default_presets_dir(), 96, 54).unwrap(); + w.take_changes(); + + // Make the source unavailable without issuing a texture edit, so a second decode would fail. + w.textures.remove(&1).unwrap(); + let turn = std::f32::consts::FRAC_PI_2; + w.set_environment(environment(1, turn, 2.0, 0.0)); + assert!(!live.commit(&mut w).unwrap()); + assert_eq!(live.sc.base.hdri, [0.0, 0.0, 2.0, 1.0]); + assert_eq!(live.sc.base.counts2[1], 0); + + w.set_environment(environment(1, turn, 2.0, 0.5)); + assert!(!live.commit(&mut w).unwrap()); + assert_eq!(live.sc.base.hdri, [0.0, 1.0, 2.0, 1.0]); + assert_eq!(live.sc.base.counts2[1], crate::env_nee_on() as u32); + + w.set_environment(environment(2, turn, 2.0, 0.5)); + assert!(!live.commit(&mut w).unwrap()); + assert_eq!(live.env.sky.map, (4, 1)); + assert_eq!(live.sc.base.counts2[1], 0); + + w.set_texture(2, panorama(6, 255)).unwrap(); + assert!(live.commit(&mut w).unwrap()); + assert_eq!(live.env.sky.map, (6, 1)); + assert_eq!(live.sc.base.counts2[1], crate::env_nee_on() as u32); +} + /// Each edit, on one view that takes them one after another, against a view built from the world as it is then. #[test] fn edits_in_place_leave_what_a_build_does() { diff --git a/renderer/src/live/load.rs b/renderer/src/live/load.rs index e1b11a87..4a673315 100644 --- a/renderer/src/live/load.rs +++ b/renderer/src/live/load.rs @@ -114,7 +114,7 @@ impl DynamicSky { }; let bake = |sun: SkyAsk| { let b = crate::sky::bake_atmosphere_tables(&a, &tables, sun.0, sun.1, sun.3, w, h, glow, sun.2, horizon); - let env = gpu::EnvMap { width: b.width, height: b.height, texels: b.texels }; + let env = gpu::EnvMap { width: b.width, height: b.height, texels: b.texels.into() }; let cdf = crate::build_env_cdf(&env); let max = env.texels.iter().map(|t| 0.2126 * t[0] + 0.7152 * t[1] + 0.0722 * t[2]).fold(0.0f32, f32::max); (env, cdf, max, b.horizon_v) @@ -173,8 +173,12 @@ pub(super) fn load_scene(g: &gpu::Gpu, world: &World, assets: &Path, presets: &P let _ = g.kernel_pass(&up.kernel, "media_train"); let _ = g.kernel_pass(&up.kernel, "media_composite"); } + let hdri = match &world.environment.sky { + crate::desc::Sky::Hdri { texture, .. } => Some((*texture, prep.env_brightest)), + _ => None, + }; let env = Environment { - sky: SkyState { map: (prep.env.width, prep.env.height), altitude: sky_altitude(&sc.sky).unwrap_or(sc.camera.position.y.max(0.0)), floor: prep.env_nee_floor, cover: sc.environment.cloud_cover, worker: None }, + sky: SkyState { map: (prep.env.width, prep.env.height), hdri, altitude: sky_altitude(&sc.sky).unwrap_or(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())); diff --git a/renderer/src/live/state.rs b/renderer/src/live/state.rs index 043fe97e..433eeed5 100644 --- a/renderer/src/live/state.rs +++ b/renderer/src/live/state.rs @@ -93,6 +93,8 @@ pub(super) struct Environment { pub(super) struct SkyState { /// The environment map's size. pub(super) map: (u32, u32), + /// The uploaded HDRI's texture ID and peak luminance before scaling. + pub(super) hdri: Option<(u32, f32)>, /// 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`). diff --git a/renderer/src/scene.rs b/renderer/src/scene.rs index 20eb1cc1..4d2fa1fb 100644 --- a/renderer/src/scene.rs +++ b/renderer/src/scene.rs @@ -528,6 +528,7 @@ pub struct EnvSettings { pub fog: Option, /// three.js `scene.background` (`desc::Environment::background`): the kernel's F_BACKGROUND, `Params::background`. pub background: Option<[f32; 3]>, + pub background_panorama: Option, /// 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). @@ -540,21 +541,25 @@ pub struct EnvSettings { 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) } + EnvSettings { fog: e.fog.clone(), background: e.background, background_panorama: e.background_panorama.clone(), 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.background = if let Some(b) = &self.background_panorama { + [panorama_offset(b.rotation), b.intensity.max(0.0), 0.0, 2.0] + } else { + 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) + crate::gpu::environment_features(self.fog.as_ref(), self.background.is_some() || self.background_panorama.is_some(), self.aerial) } } @@ -565,6 +570,12 @@ pub enum SkyData { /// `altitude`: a planet's viewer altitude (m, `desc::Sky::Atmosphere::altitude`), or a flat world's sky. Atmosphere { sun_dir: Vec3, sun_lux: Vec3, rayleigh: f32, mie: f32, g: f32, ground: Vec3, dynamic: bool, glow: crate::sky::Glow, altitude: Option }, Gradient(crate::sky::Gradient), + Hdri { map: crate::gpu::EnvMap, rotation: f32, intensity: f32, sky_light_intensity: f32 }, +} + +/// The file uses three.js longitude (u = atan2(z, x) / 2pi + 0.5). +pub fn panorama_offset(rotation: f32) -> f32 { + (rotation / std::f32::consts::TAU - 0.25).rem_euclid(1.0) } /// The atmosphere's sun as the scene sees it now: the direction toward it (Y up) and its illuminance above the @@ -604,6 +615,7 @@ pub struct Scene { pub lights: Vec, pub camera: CameraData, pub sky: SkyData, + pub background_map: Option, /// The environment beside its sky (`EnvSettings::of`). pub environment: EnvSettings, pub preset: desc::Preset, @@ -1415,7 +1427,12 @@ pub fn sky_data(w: &World, assets: &Path, matrix: &dyn Fn(u32) -> Mat4) -> Resul } 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::Hdri { texture, intensity, rotation, sky_light_intensity } => SkyData::Hdri { + map: panorama(w, assets, *texture).context("HDRI environment")?, + rotation: *rotation, + intensity: *intensity, + sky_light_intensity: *sky_light_intensity, + }, 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)) => { @@ -1448,6 +1465,32 @@ pub fn sky_data(w: &World, assets: &Path, matrix: &dyn Fn(u32) -> Mat4) -> Resul Ok((sky, sun_id)) } +fn panorama(w: &World, assets: &Path, id: u32) -> Result { + let t = w.textures.get(&id).ok_or_else(|| anyhow!("unknown texture {id}"))?; + let image = match &t.source { + world::TextureSource::File(uri) => crate::files::image_data(&crate::files::asset_path(assets, uri)) + .with_context(|| format!("texture {uri}"))?, + world::TextureSource::Encoded(bytes) => image::load_from_memory(bytes).context("generated panorama")?, + _ => image::DynamicImage::ImageRgba8((*texture_image(t, assets)?.1).clone()), + }; + // OpenEXR and Radiance HDR store linear values. Apply the texture's colour space to integer images. + let srgb = t.srgb && !matches!(&image, image::DynamicImage::ImageRgb32F(_) | image::DynamicImage::ImageRgba32F(_)); + let image = image.into_rgba32f(); + let (width, height) = image.dimensions(); + anyhow::ensure!(width != 0 && height != 0, "empty panorama"); + let texels = image.pixels().map(|p| { + let rgb = [p[0], p[1], p[2]].map(|c| { + if srgb { + if c <= 0.04045 { c / 12.92 } else { ((c + 0.055) / 1.055).powf(2.4) } + } else { + c.max(0.0).min(65000.0) + } + }); + [rgb[0], rgb[1], rgb[2], 1.0] + }).collect(); + Ok(crate::gpu::EnvMap { width, height, texels }) +} + /// 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 { let st = &w.settings; @@ -2094,6 +2137,8 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se lights, camera: camera.ok_or_else(|| anyhow!("no camera (settings.camera must name a camera object)"))?, sky, + background_map: w.environment.background_panorama.as_ref() + .map(|b| panorama(w, assets, b.texture).context("background panorama")).transpose()?, environment: EnvSettings::of(w), preset, stats, @@ -2603,6 +2648,30 @@ mod spot_cone_tests { } } +#[cfg(test)] +#[test] +fn hdri_keeps_openexr_radiance_and_separates_lighting_intensity() { + let image = image::Rgb32FImage::from_fn(4, 2, |x, y| image::Rgb([x as f32 * 4.0, y as f32 * 2.0, 0.25])); + let mut bytes = std::io::Cursor::new(Vec::new()); + image.write_to(&mut bytes, image::ImageFormat::OpenExr).unwrap(); + let mut w = World::default(); + w.set_texture(1, world::Texture { + source: world::TextureSource::Encoded(Arc::new(bytes.into_inner())), + srgb: false, wrap: true, repeat: [1.0; 2], offset: [0.0; 2], + }).unwrap(); + w.environment.sky = Sky::Hdri { texture: 1, intensity: 2.0, rotation: std::f32::consts::FRAC_PI_2, sky_light_intensity: 0.25 }; + + let (sky, sun) = sky_data(&w, Path::new("."), &|_| Mat4::IDENTITY).unwrap(); + let baked = crate::bake_sky(&sky, 0.0, 0.0); + assert!(sun.is_none()); + assert_eq!((baked.env.width, baked.env.height), (4, 2)); + assert_eq!(baked.env.texels[3], [12.0, 0.0, 0.25, 1.0]); + assert_eq!(baked.env.texels[7], [12.0, 2.0, 0.25, 1.0]); + let mut params = crate::gpu::Params::default(); + baked.write(&mut params, 0.0); + assert_eq!(params.hdri, [0.0, 0.5, 2.0, 1.0]); +} + #[cfg(test)] mod instance_tests { use super::*; diff --git a/renderer/src/world.rs b/renderer/src/world.rs index 2cc609ff..df23f9c4 100644 --- a/renderer/src/world.rs +++ b/renderer/src/world.rs @@ -431,7 +431,7 @@ impl Default for World { geometry_fns: BTreeMap::new(), proc_geometries: HashMap::new(), instanced: HashMap::new(), - environment: desc::Environment { sky: desc::Sky::Color { color: [0.0; 3], intensity: 0.0, sky_light_intensity: 1.0 }, fog: None, background: None, wetness: 0.0, rain: 0.0, cloud_cover: 0.0 }, + environment: desc::Environment { sky: desc::Sky::Color { color: [0.0; 3], intensity: 0.0, sky_light_intensity: 1.0 }, fog: None, background: None, background_panorama: None, wetness: 0.0, rain: 0.0, cloud_cover: 0.0 }, settings: Settings::default(), changes: Changes { structural: true, ..Default::default() }, } @@ -538,6 +538,11 @@ impl World { matches!(k, Kind::Light(l) if !sun && !matches!(l, desc::Light::Rect { visible: true, .. })) } + fn environment_uses_texture(&self, id: u32) -> bool { + matches!(&self.environment.sky, desc::Sky::Hdri { texture, .. } if *texture == id) + || self.environment.background_panorama.as_ref().is_some_and(|b| b.texture == id) + } + /// Creates or replaces a texture. A new one is placed in the texture pages when a material first names it; one /// that changed (its pixels, its wrap, its repeat or offset) has its materials made again, in place /// (`Changes::textures`). The same texture set again changes nothing. @@ -549,6 +554,9 @@ impl World { Some(old) if *old == t => return Ok(()), Some(_) => { self.changes.textures.insert(id); + if self.environment_uses_texture(id) { + mark_structural(&mut self.changes, line!()); + } } None => {} } @@ -1159,6 +1167,7 @@ impl World { } else { self.changes.sky |= self.environment.sky != e.sky; } + self.changes.structural |= self.environment.background_panorama.as_ref().map(|b| b.texture) != e.background_panorama.as_ref().map(|b| b.texture); self.changes.environment = true; self.environment = e; } diff --git a/tools/three/engine.ts b/tools/three/engine.ts index e03e3032..06f58672 100644 --- a/tools/three/engine.ts +++ b/tools/three/engine.ts @@ -811,6 +811,8 @@ export class ThreeEngine implements Engine { if (desc.rain) this.drop("rain (ripples)", "scene"); if (desc.fog?.volumetric) this.drop("volumetric fog (lit in-scattering)", "scene"); if (desc.fog) this.notes.add("ExponentialHeightFog -> FogExp2 at the camera height (no height falloff)"); + const panorama = desc.backgroundPanorama && this.textures.get(desc.backgroundPanorama.texture); + if (panorama) this.load(panorama); const sky = desc.sky; if (sky.type === "gradient") { const map = sky.clouds?.map; @@ -834,7 +836,8 @@ export class ThreeEngine implements Engine { })()); } } - // atmosphere: built in `prepare` (needs the sun's final direction) + // Atmosphere: built in `prepare` (needs the sun's final direction). + if (sky.type === "atmosphere" && this.sky) this.applyBackgroundPanorama(); } private setEquirect(t: THREE.Texture | null, envIntensity: number, bgIntensity: number, rotation: number): void { @@ -845,13 +848,10 @@ export class ThreeEngine implements Engine { if (!t) { this.scene.background = bg ? new THREE.Color(bg[0], bg[1], bg[2]) : null; this.scene.environment = null; + this.applyBackgroundPanorama(); return; } - t.mapping = THREE.EquirectangularReflectionMapping; - t.magFilter = THREE.LinearFilter; - t.minFilter = THREE.LinearFilter; - t.generateMipmaps = false; - t.needsUpdate = true; + this.equirectTexture(t); this.scene.background = bg ? new THREE.Color(bg[0], bg[1], bg[2]) : t; this.scene.backgroundIntensity = bgIntensity; this.scene.backgroundRotation.set(0, rotation, 0); @@ -859,6 +859,30 @@ export class ThreeEngine implements Engine { this.scene.environment = this.envTexture; this.scene.environmentIntensity = envIntensity; this.scene.environmentRotation.set(0, rotation, 0); + this.applyBackgroundPanorama(); + } + + private applyBackgroundPanorama(): void { + const background = this.envDesc?.backgroundPanorama; + const t = background && this.textures.get(background.texture)?.base; + if (this.sky) { + this.sky.visible = !t; + this.scene.background = null; + } + if (background && t) { + this.equirectTexture(t); + this.scene.background = t; + this.scene.backgroundIntensity = background.intensity; + this.scene.backgroundRotation.set(0, background.rotation, 0); + } + } + + private equirectTexture(t: THREE.Texture): void { + t.mapping = THREE.EquirectangularReflectionMapping; + t.magFilter = THREE.LinearFilter; + t.minFilter = THREE.LinearFilter; + t.generateMipmaps = false; + t.needsUpdate = true; } private removeSky(): void { @@ -1109,6 +1133,7 @@ export class ThreeEngine implements Engine { this.sky = make(false); this.sky.frustumCulled = false; this.scene.add(this.sky); + this.applyBackgroundPanorama(); } /**