| 1 | //! 3D scene graph & `wgpu` rasterizer for Fusion's `Renderer3D`, `Camera3D`, |
| 2 | //! `ImagePlane3D`, `Shape3D` (Sphere, Cylinder, Plane, Cube), `Merge3D`, `Transform3D`, |
| 3 | //! `LightAmbient`, `LightDirectional`, and `MtlCookTorrance` nodes. |
| 4 | //! |
| 5 | //! Matches Fusion's right-handed +Y-up / -Z-forward coordinate system, |
| 6 | //! `Transform3DOp` Euler rotation orders (`XYZ`, `XZY`, etc.), `ScaleLock`, |
| 7 | //! and `Camera3D` film-gate `AoV` / `ApertureW` / `ApertureH` projection. |
| 8 | |
| 9 | mod collect; |
| 10 | mod deform; |
| 11 | mod fbx; |
| 12 | mod math; |
| 13 | mod mesh; |
| 14 | mod shader; |
| 15 | |
| 16 | pub use collect::{collect_scene, collect_scene_with_nodes, eval_transform3d, mat4_inverse}; |
| 17 | pub use math::{ |
| 18 | mat4_identity, mat4_inverse_rigid, mat4_mul, mat4_perspective_wgpu, mat4_rot_x, mat4_rot_y, |
| 19 | mat4_rot_z, mat4_scale, mat4_translate, |
| 20 | }; |
| 21 | pub use shader::Vertex3D; |
| 22 | |
| 23 | use std::collections::HashMap; |
| 24 | use std::sync::{Arc, Mutex, MutexGuard}; |
| 25 | |
| 26 | fn lock_or_recover<T>(m: &Mutex<T>) -> MutexGuard<'_, T> { |
| 27 | m.lock().unwrap_or_else(|e| e.into_inner()) |
| 28 | } |
| 29 | |
| 30 | use crate::cache::{AuxChannelTex, AuxChannels, CachedTexture, EMPTY_Z_SENTINEL}; |
| 31 | use mesh::{apply_heightmap_displace, build_shape_mesh, triangle_edges}; |
| 32 | use model::NodeId; |
| 33 | use shader::{ |
| 34 | DepthToEyeZUniform, MeshUniform, ShadowUniform, DEPTH_TO_EYE_Z_SHADER, MAX_DIR_LIGHTS, |
| 35 | MAX_LIGHTS, MAX_SHADOW_LIGHTS, SHADER_3D, SHADOW_MAP_SIZE, SHADOW_SHADER, UV_XFORM_WGSL, |
| 36 | }; |
| 37 | |
| 38 | pub type Mat4 = [f32; 16]; // Column-major 4x4 |
| 39 | |
| 40 | pub struct Scene3DRenderer { |
| 41 | bgl: wgpu::BindGroupLayout, |
| 42 | /// `[triangles, lines][back-facing, front-facing]`; back faces draw first so translucent |
| 43 | /// faces show the inside of closed meshes. |
| 44 | pipelines: [[wgpu::RenderPipeline; 2]; 2], |
| 45 | /// Normal-channel pass `[triangles, lines][back-facing, front-facing]` writing `Rgba16Float`. |
| 46 | normal_pipelines: [[wgpu::RenderPipeline; 2]; 2], |
| 47 | /// Compute pass converting `Depth32Float` into eye-space `Z` (`R32Float`). |
| 48 | depth_z_bgl: wgpu::BindGroupLayout, |
| 49 | depth_z_pipeline: wgpu::ComputePipeline, |
| 50 | sampler: wgpu::Sampler, |
| 51 | meshes: Mutex<Lru<MeshKey, Option<GpuMesh>>>, |
| 52 | /// Memoized CPU `Text3D` extruded meshes keyed by deterministic geometry content hash. |
| 53 | text3d_mesh_cache: Mutex<Lru<u64, Arc<Vec<Vertex3D>>>>, |
| 54 | shadow_pipeline: wgpu::RenderPipeline, |
| 55 | /// `Caster` uniform (dynamic offset), material texture and sampler: group 0 of the shadow pass. |
| 56 | shadow_caster_bgl: wgpu::BindGroupLayout, |
| 57 | /// `Face` uniform (dynamic offset): group 1 of the shadow pass. |
| 58 | shadow_face_bgl: wgpu::BindGroupLayout, |
| 59 | /// 1x1 map bound when no light casts shadows. |
| 60 | shadow_dummy: wgpu::TextureView, |
| 61 | /// Immutable default `ShadowUniform` bound when no light casts shadows. |
| 62 | shadow_dummy_ubuf: wgpu::Buffer, |
| 63 | /// Cube maps and depth buffer reused across renders; grown, never shrunk. |
| 64 | shadow_targets: Mutex<Option<ShadowTargets>>, |
| 65 | /// Main-pass `Depth32Float` targets pooled by `[width, height]`. |
| 66 | depth_targets: Mutex<Lru<[u32; 2], DepthTarget>>, |
| 67 | /// Content-addressed LRU cache of immutable GPU uniform buffers (per-render `MeshUniform`, |
| 68 | /// `ShadowUniform`, and dynamic shadow caster/face uniforms). Never mutated after upload, |
| 69 | /// so multiple `Renderer3D` evaluations in the same unsubmitted `CommandEncoder` cannot alias. |
| 70 | uniform_cache: Mutex<Lru<(u64, usize), wgpu::Buffer>>, |
| 71 | } |
| 72 | |
| 73 | const UNIFORM_CACHE_CAP: usize = 64; |
| 74 | pub(crate) const MAX_CACHED_UNIFORM_BYTES: u64 = 16 * 1024 * 1024; |
| 75 | |
| 76 | fn cached_uniform_buffer( |
| 77 | cache: &Mutex<Lru<(u64, usize), wgpu::Buffer>>, |
| 78 | device: &wgpu::Device, |
| 79 | label: &'static str, |
| 80 | bytes: &[u8], |
| 81 | ) -> wgpu::Buffer { |
| 82 | use std::hash::{DefaultHasher, Hash, Hasher}; |
| 83 | let mut h = DefaultHasher::new(); |
| 84 | label.hash(&mut h); |
| 85 | bytes.len().hash(&mut h); |
| 86 | h.write(bytes); |
| 87 | let key = (h.finish(), bytes.len()); |
| 88 | lock_or_recover(cache).get_or_insert_with(key, || { |
| 89 | let size = (bytes.len() as u64).max(16); |
| 90 | let buf = device.create_buffer(&wgpu::BufferDescriptor { |
| 91 | label: Some(label), |
| 92 | size, |
| 93 | usage: wgpu::BufferUsages::UNIFORM, |
| 94 | mapped_at_creation: true, |
| 95 | }); |
| 96 | buf.slice(..bytes.len() as u64) |
| 97 | .get_mapped_range_mut() |
| 98 | .expect("mapped uniform buffer") |
| 99 | .copy_from_slice(bytes); |
| 100 | buf.unmap(); |
| 101 | buf |
| 102 | }) |
| 103 | } |
| 104 | |
| 105 | #[derive(Clone)] |
| 106 | struct DepthTarget { |
| 107 | tex: wgpu::Texture, |
| 108 | view: wgpu::TextureView, |
| 109 | } |
| 110 | |
| 111 | #[derive(Clone)] |
| 112 | struct ShadowTargets { |
| 113 | /// Array layers of the shadow cube-map texture (six per shadow light). |
| 114 | layers: u32, |
| 115 | /// `D2Array` view over all shadow-map layers. |
| 116 | array_view: wgpu::TextureView, |
| 117 | /// Per-layer `D2` views used as shadow-pass color attachments. |
| 118 | layer_views: Vec<wgpu::TextureView>, |
| 119 | depth: wgpu::TextureView, |
| 120 | } |
| 121 | |
| 122 | /// Bytes of the shadow pass's `Caster` and `Face` uniforms. |
| 123 | const CASTER_BYTES: usize = 64; |
| 124 | const FACE_BYTES: usize = 80; |
| 125 | |
| 126 | /// Most meshes kept resident on the GPU across frames. |
| 127 | pub(crate) const MAX_CACHED_MESH_BUFFERS: usize = 128; |
| 128 | /// Maximum GPU VRAM kept resident in `Scene3DRenderer::meshes`. |
| 129 | pub(crate) const MAX_CACHED_MESH_BYTES: u64 = 128 * 1024 * 1024; |
| 130 | /// Most main-pass depth targets pooled across distinct `Renderer3D` sizes. |
| 131 | const DEPTH_CACHE_CAP: usize = 8; |
| 132 | |
| 133 | /// Content-based key (64-bit hash + byte len + element count + aspect + wireframe) so |
| 134 | /// GPU mesh cache lookups are ABA-safe even after source CPU meshes are dropped. |
| 135 | #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] |
| 136 | struct MeshKey { |
| 137 | content_hash: u64, |
| 138 | byte_len: usize, |
| 139 | elem_count: usize, |
| 140 | aspect_bits: u32, |
| 141 | wireframe: bool, |
| 142 | } |
| 143 | |
| 144 | #[derive(Clone)] |
| 145 | struct GpuMesh { |
| 146 | vbuf: wgpu::Buffer, |
| 147 | ibuf: wgpu::Buffer, |
| 148 | idx_count: u32, |
| 149 | vbuf_bytes: u64, |
| 150 | ibuf_bytes: u64, |
| 151 | } |
| 152 | |
| 153 | /// Bounded map evicting the least recently used entry by count and optional byte budget. |
| 154 | struct Lru<K, V> { |
| 155 | cap: usize, |
| 156 | max_bytes: u64, |
| 157 | total_bytes: u64, |
| 158 | size_fn: fn(&V) -> u64, |
| 159 | tick: u64, |
| 160 | entries: HashMap<K, (u64, V)>, |
| 161 | } |
| 162 | |
| 163 | impl<K: std::hash::Hash + Eq + Copy, V: Clone> Lru<K, V> { |
| 164 | fn new(cap: usize) -> Self { |
| 165 | Self::with_byte_cap(cap, u64::MAX, |_| 0) |
| 166 | } |
| 167 | |
| 168 | fn with_byte_cap(cap: usize, max_bytes: u64, size_fn: fn(&V) -> u64) -> Self { |
| 169 | Self { cap, max_bytes, total_bytes: 0, size_fn, tick: 0, entries: HashMap::new() } |
| 170 | } |
| 171 | |
| 172 | fn get(&mut self, key: K) -> Option<V> { |
| 173 | self.tick += 1; |
| 174 | if let Some((used, v)) = self.entries.get_mut(&key) { |
| 175 | *used = self.tick; |
| 176 | Some(v.clone()) |
| 177 | } else { |
| 178 | None |
| 179 | } |
| 180 | } |
| 181 | |
| 182 | fn get_or_insert_with(&mut self, key: K, make: impl FnOnce() -> V) -> V { |
| 183 | self.tick += 1; |
| 184 | if let Some((used, v)) = self.entries.get_mut(&key) { |
| 185 | *used = self.tick; |
| 186 | return v.clone(); |
| 187 | } |
| 188 | let v = make(); |
| 189 | let new_bytes = (self.size_fn)(&v); |
| 190 | if self.cap == 0 || new_bytes > self.max_bytes { |
| 191 | return v; |
| 192 | } |
| 193 | while !self.entries.is_empty() |
| 194 | && (self.entries.len() >= self.cap |
| 195 | || self.total_bytes.saturating_add(new_bytes) > self.max_bytes) |
| 196 | { |
| 197 | let Some(oldest) = self.entries.iter().min_by_key(|(_, (used, _))| *used).map(|(k, _)| *k) else { |
| 198 | break; |
| 199 | }; |
| 200 | if let Some((_, evicted)) = self.entries.remove(&oldest) { |
| 201 | self.total_bytes = self.total_bytes.saturating_sub((self.size_fn)(&evicted)); |
| 202 | } |
| 203 | } |
| 204 | self.total_bytes = self.total_bytes.saturating_add(new_bytes); |
| 205 | self.entries.insert(key, (self.tick, v.clone())); |
| 206 | v |
| 207 | } |
| 208 | |
| 209 | fn clear(&mut self) { |
| 210 | self.entries.clear(); |
| 211 | self.total_bytes = 0; |
| 212 | self.tick = 0; |
| 213 | } |
| 214 | } |
| 215 | |
| 216 | #[derive(Clone)] |
| 217 | pub struct CameraInstance { |
| 218 | /// Node name, matched against a renderer's `CameraSelector`. |
| 219 | pub name: String, |
| 220 | pub orthographic: bool, |
| 221 | pub world: Mat4, |
| 222 | pub vfov_rad: f32, |
| 223 | pub near: f32, |
| 224 | pub far: f32, |
| 225 | } |
| 226 | |
| 227 | #[derive(Clone, Debug)] |
| 228 | pub enum ShapeKind { |
| 229 | ImagePlane, |
| 230 | Sphere { radius: f32, sub_base: u32, sub_height: u32 }, |
| 231 | Cylinder { radius: f32, height: f32, start_sweep_deg: f32, end_sweep_deg: f32, sub_base: u32, top_cap: bool, bottom_cap: bool }, |
| 232 | Plane { width: f32, height: f32, sub_w: u32, sub_h: u32 }, |
| 233 | /// Uniform cube with `sub` cells per edge; `faces` is a bitmask over `CUBE_FACES` order. |
| 234 | Cube { width: f32, sub: u32, faces: u8 }, |
| 235 | TextPlate { width: f32, height: f32, depth: f32, slices: u32 }, |
| 236 | CustomMesh(Arc<Vec<Vertex3D>>), |
| 237 | /// Carries the material's UV transform and bump parameters through `DrawMesh`. |
| 238 | WithMaterialFx { inner: Box<ShapeKind>, fx: MaterialFx }, |
| 239 | } |
| 240 | |
| 241 | /// Face order shared by `Cube3D` material inputs and `build_cube`. |
| 242 | pub const CUBE_FACES: [&str; 6] = ["Front", "Back", "Right", "Left", "Top", "Bottom"]; |
| 243 | |
| 244 | /// Affine map from mesh UV (V down) to texture UV: `uv' = m * uv + t`, `m` column-major. |
| 245 | #[derive(Clone, Copy, Debug, PartialEq)] |
| 246 | pub struct UvAffine { |
| 247 | pub m: [f32; 4], |
| 248 | pub t: [f32; 2], |
| 249 | } |
| 250 | |
| 251 | impl UvAffine { |
| 252 | pub const IDENTITY: Self = Self { m: [1.0, 0.0, 0.0, 1.0], t: [0.0, 0.0] }; |
| 253 | |
| 254 | pub fn apply(&self, uv: [f32; 2]) -> [f32; 2] { |
| 255 | [ |
| 256 | self.m[0] * uv[0] + self.m[2] * uv[1] + self.t[0], |
| 257 | self.m[1] * uv[0] + self.m[3] * uv[1] + self.t[1], |
| 258 | ] |
| 259 | } |
| 260 | |
| 261 | /// The map applying `self` first, then `outer`. |
| 262 | pub fn then(&self, outer: &Self) -> Self { |
| 263 | let o = outer.apply(self.t); |
| 264 | Self { |
| 265 | m: [ |
| 266 | outer.m[0] * self.m[0] + outer.m[2] * self.m[1], |
| 267 | outer.m[1] * self.m[0] + outer.m[3] * self.m[1], |
| 268 | outer.m[0] * self.m[2] + outer.m[2] * self.m[3], |
| 269 | outer.m[1] * self.m[2] + outer.m[3] * self.m[3], |
| 270 | ], |
| 271 | t: o, |
| 272 | } |
| 273 | } |
| 274 | |
| 275 | pub fn hash_into(&self, h: &mut impl std::hash::Hasher) { |
| 276 | use std::hash::Hash; |
| 277 | for v in self.m { |
| 278 | v.to_bits().hash(h); |
| 279 | } |
| 280 | for v in self.t { |
| 281 | v.to_bits().hash(h); |
| 282 | } |
| 283 | } |
| 284 | } |
| 285 | |
| 286 | /// Specular lobe of a material; `MeshInstance::specular_exponent` is the exponent for |
| 287 | /// `Blinn`/`Phong`, the roughness for `CookTorrance`, and `SpreadU` for `Ward`. |
| 288 | #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] |
| 289 | pub enum SpecModel { |
| 290 | #[default] |
| 291 | Blinn, |
| 292 | Phong, |
| 293 | CookTorrance, |
| 294 | /// `EnablePBRMaterial`: diffuse-only lights at 1/pi, no specular lobe. |
| 295 | Pbr, |
| 296 | /// Anisotropic Ward BRDF (`MtlWard`). |
| 297 | Ward, |
| 298 | } |
| 299 | |
| 300 | #[derive(Clone, Copy, Debug, PartialEq)] |
| 301 | pub struct MaterialFx { |
| 302 | pub uv: UvAffine, |
| 303 | /// 0 = clamp, 1 = wrap, 2 = mirror |
| 304 | pub uv_wrap: u32, |
| 305 | pub bump_scale: f32, |
| 306 | /// 0 = height map, 1 = normal map |
| 307 | pub bump_mode: u32, |
| 308 | /// The bound texture only perturbs normals; it does not color the surface. |
| 309 | pub bump_only: bool, |
| 310 | pub bump_uv: UvAffine, |
| 311 | /// 0 = clamp, 1 = wrap, 2 = mirror |
| 312 | pub bump_wrap: u32, |
| 313 | pub bump_clamp_z: f32, |
| 314 | /// 0=Luminance, 1=Average, 2=Max, 3=Min, 4=Red, 5=Green, 6=Blue, 7=Alpha |
| 315 | pub bump_channel: u32, |
| 316 | pub spec_model: SpecModel, |
| 317 | /// Draw the mesh edges as lines instead of filled triangles. |
| 318 | pub wireframe: bool, |
| 319 | pub cull_back: bool, |
| 320 | pub cull_front: bool, |
| 321 | /// Unlit surface that Fusion draws once per light, so it brightens with the light count. |
| 322 | pub per_light_unlit: bool, |
| 323 | /// `Diffuse.Color.Alpha`: modulates output alpha independently of `Diffuse.Opacity`. |
| 324 | pub diffuse_color_alpha: f32, |
| 325 | /// `MtlCookTorrance` `Specular.RefractiveIndex` (used when `do_fresnel` is true). |
| 326 | pub refractive_index: f32, |
| 327 | /// `MtlCookTorrance` `Specular.DoFresnel` toggle. |
| 328 | pub do_fresnel: bool, |
| 329 | /// `MtlWard` `Specular.SpreadV` anisotropic roughness along V. |
| 330 | pub ward_spread_v: f32, |
| 331 | /// Environment shading mode: `0 = none`, `1 = standalone SphereMap`, `2 = MtlReflect`. |
| 332 | pub env_mode: u32, |
| 333 | /// `SphereMap.MapMode`: `0 = equirectangular`, `1 = angular`. |
| 334 | pub env_map_mode: u32, |
| 335 | /// Texture slot carrying the environment image: `0 = solid/none`, `1 = mat_tex`, `2 = bump_tex`. |
| 336 | pub env_tex_slot: u32, |
| 337 | /// Column-major 3x3 inverse rotation matrix for `SphereMap` direction lookup. |
| 338 | pub env_rot: [f32; 9], |
| 339 | /// `SphereMap.StartAngle` in degrees. |
| 340 | pub env_start_angle: f32, |
| 341 | /// `SphereMap.EndAngle` in degrees. |
| 342 | pub env_end_angle: f32, |
| 343 | /// `MtlReflect.Reflection.StrengthVariability`: `0 = Constant`, `1 = By Angle`. |
| 344 | pub refl_strength_var: u32, |
| 345 | pub refl_constant_strength: f32, |
| 346 | pub refl_glancing_strength: f32, |
| 347 | pub refl_face_on_strength: f32, |
| 348 | pub refl_falloff: f32, |
| 349 | pub refl_tint: [f32; 3], |
| 350 | pub refl_has_bg: bool, |
| 351 | pub refract_ior: f32, |
| 352 | pub refract_tint: [f32; 3], |
| 353 | /// `MtlChanBool` per-channel boolean evaluation. |
| 354 | pub cb_enabled: bool, |
| 355 | pub cb_ops_a: [u8; 4], |
| 356 | pub cb_ops: [u8; 4], |
| 357 | pub cb_ops_b: [u8; 4], |
| 358 | pub cb_fg_col: [f32; 4], |
| 359 | /// `0 = Model`, `1 = World`, `2 = Eye`. |
| 360 | pub cb_coord_space: u8, |
| 361 | /// `0 = constant fg_col`, `2 = sample bump_tex for FG`. |
| 362 | pub cb_fg_tex_slot: u8, |
| 363 | } |
| 364 | |
| 365 | impl Default for MaterialFx { |
| 366 | fn default() -> Self { |
| 367 | Self { |
| 368 | uv: UvAffine::IDENTITY, |
| 369 | uv_wrap: 0, |
| 370 | bump_scale: 0.0, |
| 371 | bump_mode: 0, |
| 372 | bump_only: false, |
| 373 | bump_uv: UvAffine::IDENTITY, |
| 374 | bump_wrap: 0, |
| 375 | bump_clamp_z: 0.0, |
| 376 | bump_channel: 0, |
| 377 | spec_model: SpecModel::Blinn, |
| 378 | wireframe: false, |
| 379 | cull_back: false, |
| 380 | cull_front: false, |
| 381 | per_light_unlit: false, |
| 382 | diffuse_color_alpha: 1.0, |
| 383 | refractive_index: 2.0, |
| 384 | do_fresnel: true, |
| 385 | ward_spread_v: 0.16, |
| 386 | env_mode: 0, |
| 387 | env_map_mode: 0, |
| 388 | env_tex_slot: 0, |
| 389 | env_rot: [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0], |
| 390 | env_start_angle: 0.0, |
| 391 | env_end_angle: 360.0, |
| 392 | refl_strength_var: 1, |
| 393 | refl_constant_strength: 1.0, |
| 394 | refl_glancing_strength: 0.8, |
| 395 | refl_face_on_strength: 0.0, |
| 396 | refl_falloff: 2.0, |
| 397 | refl_tint: [1.0, 1.0, 1.0], |
| 398 | refl_has_bg: true, |
| 399 | refract_ior: 1.333, |
| 400 | refract_tint: [1.0, 1.0, 1.0], |
| 401 | cb_enabled: false, |
| 402 | cb_ops_a: [4, 5, 6, 7], |
| 403 | cb_ops: [0, 0, 0, 0], |
| 404 | cb_ops_b: [0, 1, 2, 3], |
| 405 | cb_fg_col: [0.0, 0.0, 0.0, 0.0], |
| 406 | cb_coord_space: 2, |
| 407 | cb_fg_tex_slot: 0, |
| 408 | } |
| 409 | } |
| 410 | } |
| 411 | |
| 412 | impl MaterialFx { |
| 413 | pub fn hash_into(&self, h: &mut impl std::hash::Hasher) { |
| 414 | use std::hash::Hash; |
| 415 | self.uv.hash_into(h); |
| 416 | self.uv_wrap.hash(h); |
| 417 | self.bump_scale.to_bits().hash(h); |
| 418 | self.bump_mode.hash(h); |
| 419 | self.bump_only.hash(h); |
| 420 | self.bump_uv.hash_into(h); |
| 421 | self.bump_wrap.hash(h); |
| 422 | self.bump_clamp_z.to_bits().hash(h); |
| 423 | self.bump_channel.hash(h); |
| 424 | (self.spec_model as u8).hash(h); |
| 425 | self.wireframe.hash(h); |
| 426 | self.cull_back.hash(h); |
| 427 | self.cull_front.hash(h); |
| 428 | self.per_light_unlit.hash(h); |
| 429 | self.diffuse_color_alpha.to_bits().hash(h); |
| 430 | self.refractive_index.to_bits().hash(h); |
| 431 | self.do_fresnel.hash(h); |
| 432 | self.ward_spread_v.to_bits().hash(h); |
| 433 | self.env_mode.hash(h); |
| 434 | self.env_map_mode.hash(h); |
| 435 | self.env_tex_slot.hash(h); |
| 436 | for v in self.env_rot { |
| 437 | v.to_bits().hash(h); |
| 438 | } |
| 439 | self.env_start_angle.to_bits().hash(h); |
| 440 | self.env_end_angle.to_bits().hash(h); |
| 441 | self.refl_strength_var.hash(h); |
| 442 | self.refl_constant_strength.to_bits().hash(h); |
| 443 | self.refl_glancing_strength.to_bits().hash(h); |
| 444 | self.refl_face_on_strength.to_bits().hash(h); |
| 445 | self.refl_falloff.to_bits().hash(h); |
| 446 | for v in self.refl_tint { |
| 447 | v.to_bits().hash(h); |
| 448 | } |
| 449 | self.refl_has_bg.hash(h); |
| 450 | self.refract_ior.to_bits().hash(h); |
| 451 | for v in self.refract_tint { |
| 452 | v.to_bits().hash(h); |
| 453 | } |
| 454 | self.cb_enabled.hash(h); |
| 455 | self.cb_ops_a.hash(h); |
| 456 | self.cb_ops.hash(h); |
| 457 | self.cb_ops_b.hash(h); |
| 458 | for v in self.cb_fg_col { |
| 459 | v.to_bits().hash(h); |
| 460 | } |
| 461 | self.cb_coord_space.hash(h); |
| 462 | self.cb_fg_tex_slot.hash(h); |
| 463 | } |
| 464 | } |
| 465 | |
| 466 | impl ShapeKind { |
| 467 | /// Returns the underlying geometry shape without any `WithMaterialFx` wrapper. |
| 468 | pub fn base_shape(&self) -> &ShapeKind { |
| 469 | self.split_fx().0 |
| 470 | } |
| 471 | |
| 472 | pub fn split_fx(&self) -> (&ShapeKind, MaterialFx) { |
| 473 | match self { |
| 474 | ShapeKind::WithMaterialFx { inner, fx } => (inner.base_shape(), *fx), |
| 475 | other => (other, MaterialFx::default()), |
| 476 | } |
| 477 | } |
| 478 | |
| 479 | pub fn hash_into(&self, h: &mut impl std::hash::Hasher) { |
| 480 | use std::hash::Hash; |
| 481 | match self { |
| 482 | ShapeKind::ImagePlane => 0u8.hash(h), |
| 483 | ShapeKind::Sphere { radius, sub_base, sub_height } => { |
| 484 | 1u8.hash(h); |
| 485 | radius.to_bits().hash(h); |
| 486 | sub_base.hash(h); |
| 487 | sub_height.hash(h); |
| 488 | } |
| 489 | ShapeKind::Cylinder { radius, height, start_sweep_deg, end_sweep_deg, sub_base, top_cap, bottom_cap } => { |
| 490 | 2u8.hash(h); |
| 491 | (*top_cap, *bottom_cap).hash(h); |
| 492 | radius.to_bits().hash(h); |
| 493 | height.to_bits().hash(h); |
| 494 | start_sweep_deg.to_bits().hash(h); |
| 495 | end_sweep_deg.to_bits().hash(h); |
| 496 | sub_base.hash(h); |
| 497 | } |
| 498 | ShapeKind::Plane { width, height, sub_w, sub_h } => { |
| 499 | 3u8.hash(h); |
| 500 | width.to_bits().hash(h); |
| 501 | height.to_bits().hash(h); |
| 502 | sub_w.hash(h); |
| 503 | sub_h.hash(h); |
| 504 | } |
| 505 | ShapeKind::Cube { width, sub, faces } => { |
| 506 | 4u8.hash(h); |
| 507 | width.to_bits().hash(h); |
| 508 | sub.hash(h); |
| 509 | faces.hash(h); |
| 510 | } |
| 511 | ShapeKind::TextPlate { width, height, depth, slices } => { |
| 512 | 5u8.hash(h); |
| 513 | width.to_bits().hash(h); |
| 514 | height.to_bits().hash(h); |
| 515 | depth.to_bits().hash(h); |
| 516 | slices.hash(h); |
| 517 | } |
| 518 | ShapeKind::CustomMesh(verts) => { |
| 519 | 6u8.hash(h); |
| 520 | verts.len().hash(h); |
| 521 | let step = (verts.len() / 64).max(1); |
| 522 | for v in verts.iter().step_by(step) { |
| 523 | bytemuck::bytes_of(v).hash(h); |
| 524 | } |
| 525 | } |
| 526 | ShapeKind::WithMaterialFx { inner, fx } => { |
| 527 | 7u8.hash(h); |
| 528 | inner.hash_into(h); |
| 529 | fx.hash_into(h); |
| 530 | } |
| 531 | } |
| 532 | } |
| 533 | } |
| 534 | |
| 535 | #[derive(Clone, Debug)] |
| 536 | pub struct Displace3DSpec { |
| 537 | pub input_node: NodeId, |
| 538 | pub scale: f32, |
| 539 | pub bias: f32, |
| 540 | pub channel: i32, // 0=Luma (default), 1=R, 2=G, 3=B, 4=A |
| 541 | } |
| 542 | |
| 543 | #[derive(Clone, Debug)] |
| 544 | pub struct DisplaceHeightmap { |
| 545 | pub size: [u32; 2], |
| 546 | pub rgba: Vec<u8>, |
| 547 | pub scale: f32, |
| 548 | pub bias: f32, |
| 549 | pub channel: i32, |
| 550 | } |
| 551 | |
| 552 | #[derive(Clone, Debug)] |
| 553 | pub struct Text3DSpec { |
| 554 | pub node_id: NodeId, |
| 555 | } |
| 556 | |
| 557 | #[derive(Clone)] |
| 558 | pub struct MeshInstance { |
| 559 | pub world: Mat4, |
| 560 | pub shape: ShapeKind, |
| 561 | pub material_node: Option<NodeId>, |
| 562 | pub bump_node: Option<NodeId>, |
| 563 | pub text3d: Option<Text3DSpec>, |
| 564 | pub diffuse_col: [f32; 4], |
| 565 | pub specular_col: [f32; 3], |
| 566 | pub specular_intensity: f32, |
| 567 | pub specular_exponent: f32, |
| 568 | pub affected_by_lights: bool, |
| 569 | pub casts_shadow: bool, |
| 570 | pub receives_shadows: bool, |
| 571 | pub flip_normals: bool, |
| 572 | pub displace: Option<Displace3DSpec>, |
| 573 | } |
| 574 | |
| 575 | #[derive(Clone, Copy, Debug)] |
| 576 | pub struct PointLight { |
| 577 | pub pos: [f32; 3], |
| 578 | pub color: [f32; 3], |
| 579 | /// 0 = none, 1 = linear (1/d), 2 = quadratic (1/d²) |
| 580 | pub decay_type: f32, |
| 581 | /// Unused by the shader; `Renderer3D` still folds it into its cache key. |
| 582 | pub decay_rate: f32, |
| 583 | /// Shadow density in `0..=1` when the light casts shadows. |
| 584 | pub shadow_density: Option<f32>, |
| 585 | } |
| 586 | |
| 587 | #[derive(Clone, Copy, Debug)] |
| 588 | pub struct SpotLight { |
| 589 | pub pos: [f32; 3], |
| 590 | pub dir: [f32; 3], |
| 591 | pub color: [f32; 3], |
| 592 | pub cos_inner: f32, |
| 593 | pub cos_outer: f32, |
| 594 | pub decay_type: f32, |
| 595 | } |
| 596 | |
| 597 | #[derive(Clone, Copy, Debug)] |
| 598 | pub struct DirLight { |
| 599 | pub to_light: [f32; 3], |
| 600 | pub color: [f32; 3], |
| 601 | } |
| 602 | |
| 603 | #[derive(Clone, Debug, Default)] |
| 604 | pub struct SceneLights { |
| 605 | pub ambient: [f32; 3], |
| 606 | /// Only the first `MAX_DIR_LIGHTS` reach the shader. |
| 607 | pub dirs: Vec<DirLight>, |
| 608 | pub points: Vec<PointLight>, |
| 609 | pub spots: Vec<SpotLight>, |
| 610 | /// Enabled light nodes of every kind, including black ones. |
| 611 | pub count: u32, |
| 612 | } |
| 613 | |
| 614 | pub struct DrawMesh { |
| 615 | pub world: Mat4, |
| 616 | pub shape: ShapeKind, |
| 617 | /// Optional deterministic content key for `ShapeKind::CustomMesh` so GPU mesh LRU avoids pointer hashing. |
| 618 | pub custom_mesh_key: Option<u64>, |
| 619 | pub tex: Option<CachedTexture>, |
| 620 | pub bump_tex: Option<CachedTexture>, |
| 621 | pub diffuse_col: [f32; 4], |
| 622 | pub specular_col: [f32; 3], |
| 623 | pub specular_intensity: f32, |
| 624 | pub specular_exponent: f32, |
| 625 | pub affected_by_lights: bool, |
| 626 | pub casts_shadow: bool, |
| 627 | pub receives_shadows: bool, |
| 628 | pub flip_normals: bool, |
| 629 | pub displace: Option<DisplaceHeightmap>, |
| 630 | } |
| 631 | |
| 632 | fn mesh_key(base_shape: &ShapeKind, custom_mesh_key: Option<u64>, aspect: f32, wireframe: bool) -> MeshKey { |
| 633 | use std::hash::{DefaultHasher, Hash, Hasher}; |
| 634 | let mut h = DefaultHasher::new(); |
| 635 | let (byte_len, elem_count) = match base_shape { |
| 636 | ShapeKind::CustomMesh(verts) => { |
| 637 | let elems = verts.len(); |
| 638 | let bytes = std::mem::size_of_val(verts.as_slice()); |
| 639 | 6u8.hash(&mut h); |
| 640 | elems.hash(&mut h); |
| 641 | bytes.hash(&mut h); |
| 642 | if let Some(ck) = custom_mesh_key { |
| 643 | ck.hash(&mut h); |
| 644 | } else { |
| 645 | h.write(bytemuck::cast_slice(verts.as_slice())); |
| 646 | } |
| 647 | (bytes, elems) |
| 648 | } |
| 649 | _ => { |
| 650 | base_shape.hash_into(&mut h); |
| 651 | (0, 0) |
| 652 | } |
| 653 | }; |
| 654 | let aspect_bits = if matches!(base_shape, ShapeKind::ImagePlane) { aspect.to_bits() } else { 0 }; |
| 655 | MeshKey { |
| 656 | content_hash: h.finish(), |
| 657 | byte_len, |
| 658 | elem_count, |
| 659 | aspect_bits, |
| 660 | wireframe, |
| 661 | } |
| 662 | } |
| 663 | |
| 664 | /// Returns the local-space centroid of partial `Cube` face subsets so separate face |
| 665 | /// material groups sort front-to-back / back-to-front by their true face depth. |
| 666 | fn shape_local_center(shape: &ShapeKind) -> [f32; 3] { |
| 667 | let ShapeKind::Cube { width, faces, .. } = shape.base_shape() else { |
| 668 | return [0.0; 3]; |
| 669 | }; |
| 670 | let mask = *faces & 0b11_1111; |
| 671 | if mask == 0 || mask == 0b11_1111 { |
| 672 | return [0.0; 3]; |
| 673 | } |
| 674 | let hw = width * 0.5; |
| 675 | let face_centers: [[f32; 3]; 6] = [ |
| 676 | [0.0, 0.0, hw], |
| 677 | [0.0, 0.0, -hw], |
| 678 | [hw, 0.0, 0.0], |
| 679 | [-hw, 0.0, 0.0], |
| 680 | [0.0, hw, 0.0], |
| 681 | [0.0, -hw, 0.0], |
| 682 | ]; |
| 683 | let mut sum = [0.0_f32; 3]; |
| 684 | let mut count = 0u32; |
| 685 | for (i, c) in face_centers.iter().enumerate() { |
| 686 | if mask & (1 << i) != 0 { |
| 687 | sum[0] += c[0]; |
| 688 | sum[1] += c[1]; |
| 689 | sum[2] += c[2]; |
| 690 | count += 1; |
| 691 | } |
| 692 | } |
| 693 | let inv = 1.0 / (count.max(1) as f32); |
| 694 | [sum[0] * inv, sum[1] * inv, sum[2] * inv] |
| 695 | } |
| 696 | |
| 697 | /// View-projections of the six 90 degree faces (`+X -X +Y -Y +Z -Z`) around `eye`. |
| 698 | fn cube_face_view_projections(eye: [f32; 3], far: f32) -> [Mat4; 6] { |
| 699 | let proj = mat4_perspective_wgpu(std::f32::consts::FRAC_PI_2, 1.0, 0.01, far); |
| 700 | [ |
| 701 | ([1.0, 0.0, 0.0], [0.0, 1.0, 0.0]), |
| 702 | ([-1.0, 0.0, 0.0], [0.0, 1.0, 0.0]), |
| 703 | ([0.0, 1.0, 0.0], [0.0, 0.0, 1.0]), |
| 704 | ([0.0, -1.0, 0.0], [0.0, 0.0, 1.0]), |
| 705 | ([0.0, 0.0, 1.0], [0.0, 1.0, 0.0]), |
| 706 | ([0.0, 0.0, -1.0], [0.0, 1.0, 0.0]), |
| 707 | ] |
| 708 | .map(|(f, up)| { |
| 709 | let right = [f[1] * up[2] - f[2] * up[1], f[2] * up[0] - f[0] * up[2], f[0] * up[1] - f[1] * up[0]]; |
| 710 | let up = [right[1] * f[2] - right[2] * f[1], right[2] * f[0] - right[0] * f[2], right[0] * f[1] - right[1] * f[0]]; |
| 711 | let dot = |a: [f32; 3]| a[0] * eye[0] + a[1] * eye[1] + a[2] * eye[2]; |
| 712 | let view = [ |
| 713 | right[0], up[0], -f[0], 0.0, |
| 714 | right[1], up[1], -f[1], 0.0, |
| 715 | right[2], up[2], -f[2], 0.0, |
| 716 | -dot(right), -dot(up), dot(f), 1.0, |
| 717 | ]; |
| 718 | mat4_mul(proj, view) |
| 719 | }) |
| 720 | } |
| 721 | |
| 722 | impl Scene3DRenderer { |
| 723 | pub fn new(device: &wgpu::Device) -> Self { |
| 724 | let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { |
| 725 | label: Some("scene3d-shader"), |
| 726 | source: wgpu::ShaderSource::Wgsl( |
| 727 | format!("{UV_XFORM_WGSL}{SHADER_3D}") |
| 728 | .replace("MAX_SHADOW_LIGHTS", &MAX_SHADOW_LIGHTS.to_string()) |
| 729 | .replace("MAX_DIR_LIGHTS", &MAX_DIR_LIGHTS.to_string()) |
| 730 | .replace("MAX_LIGHTS", &MAX_LIGHTS.to_string()) |
| 731 | .replace("SHADOW_MAP_SIZE", &SHADOW_MAP_SIZE.to_string()) |
| 732 | .into(), |
| 733 | ), |
| 734 | }); |
| 735 | let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { |
| 736 | label: Some("scene3d-bgl"), |
| 737 | entries: &[ |
| 738 | wgpu::BindGroupLayoutEntry { |
| 739 | binding: 0, |
| 740 | visibility: wgpu::ShaderStages::VERTEX_FRAGMENT, |
| 741 | ty: wgpu::BindingType::Buffer { |
| 742 | ty: wgpu::BufferBindingType::Uniform, |
| 743 | has_dynamic_offset: true, |
| 744 | min_binding_size: std::num::NonZeroU64::new(std::mem::size_of::<MeshUniform>() as u64), |
| 745 | }, |
| 746 | count: None, |
| 747 | }, |
| 748 | wgpu::BindGroupLayoutEntry { |
| 749 | binding: 1, |
| 750 | visibility: wgpu::ShaderStages::FRAGMENT, |
| 751 | ty: wgpu::BindingType::Texture { |
| 752 | sample_type: wgpu::TextureSampleType::Float { filterable: true }, |
| 753 | view_dimension: wgpu::TextureViewDimension::D2, |
| 754 | multisampled: false, |
| 755 | }, |
| 756 | count: None, |
| 757 | }, |
| 758 | wgpu::BindGroupLayoutEntry { |
| 759 | binding: 2, |
| 760 | visibility: wgpu::ShaderStages::FRAGMENT, |
| 761 | ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), |
| 762 | count: None, |
| 763 | }, |
| 764 | wgpu::BindGroupLayoutEntry { |
| 765 | binding: 3, |
| 766 | visibility: wgpu::ShaderStages::FRAGMENT, |
| 767 | ty: wgpu::BindingType::Buffer { |
| 768 | ty: wgpu::BufferBindingType::Uniform, |
| 769 | has_dynamic_offset: false, |
| 770 | min_binding_size: None, |
| 771 | }, |
| 772 | count: None, |
| 773 | }, |
| 774 | wgpu::BindGroupLayoutEntry { |
| 775 | binding: 4, |
| 776 | visibility: wgpu::ShaderStages::FRAGMENT, |
| 777 | ty: wgpu::BindingType::Texture { |
| 778 | sample_type: wgpu::TextureSampleType::Float { filterable: false }, |
| 779 | view_dimension: wgpu::TextureViewDimension::D2Array, |
| 780 | multisampled: false, |
| 781 | }, |
| 782 | count: None, |
| 783 | }, |
| 784 | wgpu::BindGroupLayoutEntry { |
| 785 | binding: 5, |
| 786 | visibility: wgpu::ShaderStages::FRAGMENT, |
| 787 | ty: wgpu::BindingType::Texture { |
| 788 | sample_type: wgpu::TextureSampleType::Float { filterable: true }, |
| 789 | view_dimension: wgpu::TextureViewDimension::D2, |
| 790 | multisampled: false, |
| 791 | }, |
| 792 | count: None, |
| 793 | }, |
| 794 | ], |
| 795 | }); |
| 796 | let pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { |
| 797 | label: Some("scene3d-pl"), |
| 798 | bind_group_layouts: &[Some(&bgl)], |
| 799 | immediate_size: 0, |
| 800 | }); |
| 801 | let vbuf_layout = wgpu::VertexBufferLayout { |
| 802 | array_stride: std::mem::size_of::<Vertex3D>() as u64, |
| 803 | step_mode: wgpu::VertexStepMode::Vertex, |
| 804 | attributes: &[ |
| 805 | wgpu::VertexAttribute { format: wgpu::VertexFormat::Float32x3, offset: 0, shader_location: 0 }, |
| 806 | wgpu::VertexAttribute { format: wgpu::VertexFormat::Float32x3, offset: 12, shader_location: 1 }, |
| 807 | wgpu::VertexAttribute { format: wgpu::VertexFormat::Float32x2, offset: 24, shader_location: 2 }, |
| 808 | ], |
| 809 | }; |
| 810 | let make_pipeline = |topology: wgpu::PrimitiveTopology, |
| 811 | back_pass: bool, |
| 812 | fs_entry: &'static str, |
| 813 | target_format: wgpu::TextureFormat, |
| 814 | blend: Option<wgpu::BlendState>| { |
| 815 | device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { |
| 816 | label: Some("scene3d-mesh"), |
| 817 | layout: Some(&pl), |
| 818 | vertex: wgpu::VertexState { |
| 819 | module: &shader, |
| 820 | entry_point: Some("vs_mesh"), |
| 821 | compilation_options: Default::default(), |
| 822 | buffers: &[Some(vbuf_layout.clone())], |
| 823 | }, |
| 824 | fragment: Some(wgpu::FragmentState { |
| 825 | module: &shader, |
| 826 | entry_point: Some(fs_entry), |
| 827 | compilation_options: wgpu::PipelineCompilationOptions { |
| 828 | constants: &[("BACK_PASS", if back_pass { 1.0 } else { 0.0 })], |
| 829 | ..Default::default() |
| 830 | }, |
| 831 | targets: &[Some(wgpu::ColorTargetState { |
| 832 | format: target_format, |
| 833 | blend, |
| 834 | write_mask: wgpu::ColorWrites::ALL, |
| 835 | })], |
| 836 | }), |
| 837 | primitive: wgpu::PrimitiveState { |
| 838 | topology, |
| 839 | cull_mode: None, |
| 840 | ..Default::default() |
| 841 | }, |
| 842 | depth_stencil: Some(wgpu::DepthStencilState { |
| 843 | format: wgpu::TextureFormat::Depth32Float, |
| 844 | depth_write_enabled: Some(true), |
| 845 | depth_compare: Some(wgpu::CompareFunction::Less), |
| 846 | stencil: wgpu::StencilState::default(), |
| 847 | bias: wgpu::DepthBiasState::default(), |
| 848 | }), |
| 849 | multisample: wgpu::MultisampleState::default(), |
| 850 | multiview_mask: None, |
| 851 | cache: None, |
| 852 | }) |
| 853 | }; |
| 854 | let pipelines = [wgpu::PrimitiveTopology::TriangleList, wgpu::PrimitiveTopology::LineList] |
| 855 | .map(|topology| { |
| 856 | [ |
| 857 | make_pipeline( |
| 858 | topology, |
| 859 | true, |
| 860 | "fs_mesh", |
| 861 | wgpu::TextureFormat::Rgba8Unorm, |
| 862 | Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING), |
| 863 | ), |
| 864 | make_pipeline( |
| 865 | topology, |
| 866 | false, |
| 867 | "fs_mesh", |
| 868 | wgpu::TextureFormat::Rgba8Unorm, |
| 869 | Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING), |
| 870 | ), |
| 871 | ] |
| 872 | }); |
| 873 | let normal_pipelines = [wgpu::PrimitiveTopology::TriangleList, wgpu::PrimitiveTopology::LineList] |
| 874 | .map(|topology| { |
| 875 | [ |
| 876 | make_pipeline(topology, true, "fs_normal", wgpu::TextureFormat::Rgba16Float, None), |
| 877 | make_pipeline(topology, false, "fs_normal", wgpu::TextureFormat::Rgba16Float, None), |
| 878 | ] |
| 879 | }); |
| 880 | let depth_z_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { |
| 881 | label: Some("scene3d-depth-z-shader"), |
| 882 | source: wgpu::ShaderSource::Wgsl(DEPTH_TO_EYE_Z_SHADER.into()), |
| 883 | }); |
| 884 | let depth_z_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { |
| 885 | label: Some("scene3d-depth-z-bgl"), |
| 886 | entries: &[ |
| 887 | wgpu::BindGroupLayoutEntry { |
| 888 | binding: 0, |
| 889 | visibility: wgpu::ShaderStages::COMPUTE, |
| 890 | ty: wgpu::BindingType::Texture { |
| 891 | sample_type: wgpu::TextureSampleType::Depth, |
| 892 | view_dimension: wgpu::TextureViewDimension::D2, |
| 893 | multisampled: false, |
| 894 | }, |
| 895 | count: None, |
| 896 | }, |
| 897 | wgpu::BindGroupLayoutEntry { |
| 898 | binding: 1, |
| 899 | visibility: wgpu::ShaderStages::COMPUTE, |
| 900 | ty: wgpu::BindingType::StorageTexture { |
| 901 | access: wgpu::StorageTextureAccess::WriteOnly, |
| 902 | format: wgpu::TextureFormat::R32Float, |
| 903 | view_dimension: wgpu::TextureViewDimension::D2, |
| 904 | }, |
| 905 | count: None, |
| 906 | }, |
| 907 | wgpu::BindGroupLayoutEntry { |
| 908 | binding: 2, |
| 909 | visibility: wgpu::ShaderStages::COMPUTE, |
| 910 | ty: wgpu::BindingType::Buffer { |
| 911 | ty: wgpu::BufferBindingType::Uniform, |
| 912 | has_dynamic_offset: false, |
| 913 | min_binding_size: std::num::NonZeroU64::new( |
| 914 | std::mem::size_of::<DepthToEyeZUniform>() as u64, |
| 915 | ), |
| 916 | }, |
| 917 | count: None, |
| 918 | }, |
| 919 | ], |
| 920 | }); |
| 921 | let depth_z_pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { |
| 922 | label: Some("scene3d-depth-z-pl"), |
| 923 | bind_group_layouts: &[Some(&depth_z_bgl)], |
| 924 | immediate_size: 0, |
| 925 | }); |
| 926 | let depth_z_pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { |
| 927 | label: Some("scene3d-depth-to-eye-z"), |
| 928 | layout: Some(&depth_z_pl), |
| 929 | module: &depth_z_shader, |
| 930 | entry_point: Some("depth_to_eye_z"), |
| 931 | compilation_options: Default::default(), |
| 932 | cache: None, |
| 933 | }); |
| 934 | let sampler = device.create_sampler(&wgpu::SamplerDescriptor { |
| 935 | label: Some("scene3d-linear"), |
| 936 | address_mode_u: wgpu::AddressMode::ClampToEdge, |
| 937 | address_mode_v: wgpu::AddressMode::ClampToEdge, |
| 938 | mag_filter: wgpu::FilterMode::Linear, |
| 939 | min_filter: wgpu::FilterMode::Linear, |
| 940 | mipmap_filter: wgpu::MipmapFilterMode::Linear, |
| 941 | ..Default::default() |
| 942 | }); |
| 943 | let shadow_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { |
| 944 | label: Some("scene3d-shadow-shader"), |
| 945 | source: wgpu::ShaderSource::Wgsl(SHADOW_SHADER.into()), |
| 946 | }); |
| 947 | let dynamic_uniform = |binding| wgpu::BindGroupLayoutEntry { |
| 948 | binding, |
| 949 | visibility: wgpu::ShaderStages::VERTEX_FRAGMENT, |
| 950 | ty: wgpu::BindingType::Buffer { |
| 951 | ty: wgpu::BufferBindingType::Uniform, |
| 952 | has_dynamic_offset: true, |
| 953 | min_binding_size: None, |
| 954 | }, |
| 955 | count: None, |
| 956 | }; |
| 957 | let shadow_caster_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { |
| 958 | label: Some("scene3d-shadow-caster-bgl"), |
| 959 | entries: &[dynamic_uniform(0)], |
| 960 | }); |
| 961 | let shadow_face_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { |
| 962 | label: Some("scene3d-shadow-face-bgl"), |
| 963 | entries: &[dynamic_uniform(0)], |
| 964 | }); |
| 965 | let shadow_pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { |
| 966 | label: Some("scene3d-shadow-pl"), |
| 967 | bind_group_layouts: &[Some(&shadow_caster_bgl), Some(&shadow_face_bgl)], |
| 968 | immediate_size: 0, |
| 969 | }); |
| 970 | let shadow_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { |
| 971 | label: Some("scene3d-shadow"), |
| 972 | layout: Some(&shadow_pl), |
| 973 | vertex: wgpu::VertexState { |
| 974 | module: &shadow_shader, |
| 975 | entry_point: Some("vs_shadow"), |
| 976 | compilation_options: Default::default(), |
| 977 | buffers: &[Some(vbuf_layout)], |
| 978 | }, |
| 979 | fragment: Some(wgpu::FragmentState { |
| 980 | module: &shadow_shader, |
| 981 | entry_point: Some("fs_shadow"), |
| 982 | compilation_options: Default::default(), |
| 983 | targets: &[Some(wgpu::ColorTargetState { |
| 984 | format: wgpu::TextureFormat::R32Float, |
| 985 | blend: None, |
| 986 | write_mask: wgpu::ColorWrites::ALL, |
| 987 | })], |
| 988 | }), |
| 989 | primitive: wgpu::PrimitiveState::default(), |
| 990 | depth_stencil: Some(wgpu::DepthStencilState { |
| 991 | format: wgpu::TextureFormat::Depth32Float, |
| 992 | depth_write_enabled: Some(true), |
| 993 | depth_compare: Some(wgpu::CompareFunction::Less), |
| 994 | stencil: wgpu::StencilState::default(), |
| 995 | bias: wgpu::DepthBiasState::default(), |
| 996 | }), |
| 997 | multisample: wgpu::MultisampleState::default(), |
| 998 | multiview_mask: None, |
| 999 | cache: None, |
| 1000 | }); |
| 1001 | let shadow_dummy = device |
| 1002 | .create_texture(&wgpu::TextureDescriptor { |
| 1003 | label: Some("scene3d-shadow-dummy"), |
| 1004 | size: wgpu::Extent3d { width: 1, height: 1, depth_or_array_layers: 1 }, |
| 1005 | mip_level_count: 1, |
| 1006 | sample_count: 1, |
| 1007 | dimension: wgpu::TextureDimension::D2, |
| 1008 | format: wgpu::TextureFormat::R32Float, |
| 1009 | usage: wgpu::TextureUsages::TEXTURE_BINDING, |
| 1010 | view_formats: &[], |
| 1011 | }) |
| 1012 | .create_view(&wgpu::TextureViewDescriptor { |
| 1013 | dimension: Some(wgpu::TextureViewDimension::D2Array), |
| 1014 | ..Default::default() |
| 1015 | }); |
| 1016 | let shadow_dummy_uni = ShadowUniform { |
| 1017 | face_vp: [mat4_identity(); 6 * MAX_SHADOW_LIGHTS], |
| 1018 | point: [[-1.0, 0.0, 0.0, 0.0]; MAX_LIGHTS], |
| 1019 | }; |
| 1020 | let shadow_dummy_ubuf = device.create_buffer(&wgpu::BufferDescriptor { |
| 1021 | label: Some("scene3d-shadow-dummy-u"), |
| 1022 | size: std::mem::size_of::<ShadowUniform>() as u64, |
| 1023 | usage: wgpu::BufferUsages::UNIFORM, |
| 1024 | mapped_at_creation: true, |
| 1025 | }); |
| 1026 | shadow_dummy_ubuf |
| 1027 | .slice(..) |
| 1028 | .get_mapped_range_mut() |
| 1029 | .expect("mapped shadow dummy uniform buffer") |
| 1030 | .copy_from_slice(bytemuck::bytes_of(&shadow_dummy_uni)); |
| 1031 | shadow_dummy_ubuf.unmap(); |
| 1032 | Self { |
| 1033 | bgl, |
| 1034 | pipelines, |
| 1035 | normal_pipelines, |
| 1036 | depth_z_bgl, |
| 1037 | depth_z_pipeline, |
| 1038 | sampler, |
| 1039 | meshes: Mutex::new(Lru::with_byte_cap( |
| 1040 | MAX_CACHED_MESH_BUFFERS, |
| 1041 | MAX_CACHED_MESH_BYTES, |
| 1042 | |gm| gm.as_ref().map_or(0, |m| m.vbuf_bytes + m.ibuf_bytes), |
| 1043 | )), |
| 1044 | text3d_mesh_cache: Mutex::new(Lru::new(MAX_CACHED_MESH_BUFFERS)), |
| 1045 | shadow_pipeline, |
| 1046 | shadow_caster_bgl, |
| 1047 | shadow_face_bgl, |
| 1048 | shadow_dummy, |
| 1049 | shadow_dummy_ubuf, |
| 1050 | shadow_targets: Mutex::new(None), |
| 1051 | depth_targets: Mutex::new(Lru::new(DEPTH_CACHE_CAP)), |
| 1052 | uniform_cache: Mutex::new(Lru::with_byte_cap( |
| 1053 | UNIFORM_CACHE_CAP, |
| 1054 | MAX_CACHED_UNIFORM_BYTES, |
| 1055 | |b| b.size(), |
| 1056 | )), |
| 1057 | } |
| 1058 | } |
| 1059 | |
| 1060 | /// Returns a memoized `Text3D` vertex buffer for `key`, building it on miss. |
| 1061 | pub fn get_or_build_text3d_mesh( |
| 1062 | &self, |
| 1063 | key: u64, |
| 1064 | build: impl FnOnce() -> Vec<Vertex3D>, |
| 1065 | ) -> Arc<Vec<Vertex3D>> { |
| 1066 | if let Some(hit) = lock_or_recover(&self.text3d_mesh_cache).get(key) { |
| 1067 | return hit; |
| 1068 | } |
| 1069 | let built = Arc::new(build()); |
| 1070 | lock_or_recover(&self.text3d_mesh_cache) |
| 1071 | .get_or_insert_with(key, || Arc::clone(&built)) |
| 1072 | } |
| 1073 | |
| 1074 | /// Drops cached shadow cube-map targets, main-pass depth targets, memoized `Text3D` CPU meshes, |
| 1075 | /// cached GPU mesh vertex/index buffers, and pooled uniform buffers. |
| 1076 | pub fn clear_shadow_targets(&self) { |
| 1077 | *lock_or_recover(&self.shadow_targets) = None; |
| 1078 | lock_or_recover(&self.depth_targets).clear(); |
| 1079 | lock_or_recover(&self.text3d_mesh_cache).clear(); |
| 1080 | lock_or_recover(&self.meshes).clear(); |
| 1081 | lock_or_recover(&self.uniform_cache).clear(); |
| 1082 | } |
| 1083 | |
| 1084 | /// Drops all pooled 3D render targets (`shadow_targets` and `depth_targets`) and `Text3D` CPU meshes. |
| 1085 | pub fn clear_targets(&self) { |
| 1086 | self.clear_shadow_targets(); |
| 1087 | } |
| 1088 | |
| 1089 | /// Total GPU VRAM in bytes currently occupied by `shadow_targets` (R32Float layers + Depth32Float). |
| 1090 | pub fn shadow_vram_bytes(&self) -> u64 { |
| 1091 | lock_or_recover(&self.shadow_targets).as_ref().map_or(0, |t| { |
| 1092 | let layer_bytes = u64::from(SHADOW_MAP_SIZE) * u64::from(SHADOW_MAP_SIZE) * 4; |
| 1093 | layer_bytes * (u64::from(t.layers) + 1) |
| 1094 | }) |
| 1095 | } |
| 1096 | |
| 1097 | /// Total GPU VRAM in bytes currently occupied by pooled main-pass `Depth32Float` targets. |
| 1098 | pub fn depth_vram_bytes(&self) -> u64 { |
| 1099 | lock_or_recover(&self.depth_targets) |
| 1100 | .entries |
| 1101 | .values() |
| 1102 | .map(|(_, dt)| u64::from(dt.tex.width()) * u64::from(dt.tex.height()) * 4) |
| 1103 | .sum() |
| 1104 | } |
| 1105 | |
| 1106 | /// Total GPU VRAM in bytes currently occupied by cached vertex and index buffers. |
| 1107 | pub fn mesh_vram_bytes(&self) -> u64 { |
| 1108 | lock_or_recover(&self.meshes) |
| 1109 | .entries |
| 1110 | .values() |
| 1111 | .filter_map(|(_, gm)| gm.as_ref()) |
| 1112 | .map(|gm| gm.vbuf_bytes + gm.ibuf_bytes) |
| 1113 | .sum() |
| 1114 | } |
| 1115 | |
| 1116 | /// Total GPU VRAM in bytes currently occupied by cached uniform buffers. |
| 1117 | pub fn uniform_vram_bytes(&self) -> u64 { |
| 1118 | lock_or_recover(&self.uniform_cache).total_bytes |
| 1119 | } |
| 1120 | |
| 1121 | #[cfg(test)] |
| 1122 | pub(crate) fn gpu_mesh_count(&self) -> usize { |
| 1123 | lock_or_recover(&self.meshes).entries.len() |
| 1124 | } |
| 1125 | |
| 1126 | /// Attaches empty sky auxiliary channels (`EMPTY_Z_SENTINEL` for Z, `(0,0,0,0)` for Normal) |
| 1127 | /// when a `Renderer3D` exits early (e.g. disconnected `SceneInput` or invalid clip planes). |
| 1128 | pub fn attach_empty_aux( |
| 1129 | device: &wgpu::Device, |
| 1130 | queue: &wgpu::Queue, |
| 1131 | dst: &mut CachedTexture, |
| 1132 | want_z: bool, |
| 1133 | want_normal: bool, |
| 1134 | ) { |
| 1135 | if !want_z && !want_normal { |
| 1136 | return; |
| 1137 | } |
| 1138 | let size = [dst.size[0].max(1), dst.size[1].max(1)]; |
| 1139 | let mut aux = dst.aux_cloned(); |
| 1140 | if want_z { |
| 1141 | let z_tex = AuxChannelTex::new(device, size, wgpu::TextureFormat::R32Float, "scene3d-aux-z"); |
| 1142 | let data = vec![EMPTY_Z_SENTINEL; (z_tex.size[0] as usize) * (z_tex.size[1] as usize)]; |
| 1143 | queue.write_texture( |
| 1144 | z_tex.texture.as_image_copy(), |
| 1145 | bytemuck::cast_slice(&data), |
| 1146 | wgpu::TexelCopyBufferLayout { |
| 1147 | offset: 0, |
| 1148 | bytes_per_row: Some(z_tex.size[0] * 4), |
| 1149 | rows_per_image: Some(z_tex.size[1]), |
| 1150 | }, |
| 1151 | wgpu::Extent3d { |
| 1152 | width: z_tex.size[0], |
| 1153 | height: z_tex.size[1], |
| 1154 | depth_or_array_layers: 1, |
| 1155 | }, |
| 1156 | ); |
| 1157 | aux.z = Some(z_tex); |
| 1158 | } |
| 1159 | if want_normal { |
| 1160 | let normal_tex = AuxChannelTex::new(device, size, wgpu::TextureFormat::Rgba16Float, "scene3d-aux-normal"); |
| 1161 | let data = vec![0u16; (normal_tex.size[0] as usize) * (normal_tex.size[1] as usize) * 4]; |
| 1162 | queue.write_texture( |
| 1163 | normal_tex.texture.as_image_copy(), |
| 1164 | bytemuck::cast_slice(&data), |
| 1165 | wgpu::TexelCopyBufferLayout { |
| 1166 | offset: 0, |
| 1167 | bytes_per_row: Some(normal_tex.size[0] * 8), |
| 1168 | rows_per_image: Some(normal_tex.size[1]), |
| 1169 | }, |
| 1170 | wgpu::Extent3d { |
| 1171 | width: normal_tex.size[0], |
| 1172 | height: normal_tex.size[1], |
| 1173 | depth_or_array_layers: 1, |
| 1174 | }, |
| 1175 | ); |
| 1176 | aux.normal = Some(normal_tex); |
| 1177 | } |
| 1178 | dst.set_aux(Some(Arc::new(aux))); |
| 1179 | } |
| 1180 | |
| 1181 | #[allow(clippy::too_many_arguments)] |
| 1182 | pub fn render_meshes( |
| 1183 | &self, |
| 1184 | device: &wgpu::Device, |
| 1185 | queue: &wgpu::Queue, |
| 1186 | enc: &mut wgpu::CommandEncoder, |
| 1187 | dst: &CachedTexture, |
| 1188 | dummy: &CachedTexture, |
| 1189 | view_proj: Mat4, |
| 1190 | view: Mat4, |
| 1191 | cam_pos: [f32; 3], |
| 1192 | cam_far: f32, |
| 1193 | lights: SceneLights, |
| 1194 | lighting_enabled: bool, |
| 1195 | shadows_enabled: bool, |
| 1196 | meshes: &[DrawMesh], |
| 1197 | ) { |
| 1198 | let _ = self.render_meshes_inner( |
| 1199 | device, |
| 1200 | queue, |
| 1201 | enc, |
| 1202 | dst, |
| 1203 | dummy, |
| 1204 | view_proj, |
| 1205 | view, |
| 1206 | mat4_identity(), |
| 1207 | cam_pos, |
| 1208 | cam_far, |
| 1209 | lights, |
| 1210 | lighting_enabled, |
| 1211 | shadows_enabled, |
| 1212 | false, |
| 1213 | false, |
| 1214 | meshes, |
| 1215 | ); |
| 1216 | } |
| 1217 | |
| 1218 | #[allow(clippy::too_many_arguments)] |
| 1219 | pub fn render_meshes_with_aux( |
| 1220 | &self, |
| 1221 | device: &wgpu::Device, |
| 1222 | queue: &wgpu::Queue, |
| 1223 | enc: &mut wgpu::CommandEncoder, |
| 1224 | dst: &mut CachedTexture, |
| 1225 | dummy: &CachedTexture, |
| 1226 | view_proj: Mat4, |
| 1227 | view: Mat4, |
| 1228 | proj: Mat4, |
| 1229 | cam_pos: [f32; 3], |
| 1230 | cam_far: f32, |
| 1231 | lights: SceneLights, |
| 1232 | lighting_enabled: bool, |
| 1233 | shadows_enabled: bool, |
| 1234 | want_z: bool, |
| 1235 | want_normal: bool, |
| 1236 | meshes: &[DrawMesh], |
| 1237 | ) { |
| 1238 | if let Some(aux) = self.render_meshes_inner( |
| 1239 | device, |
| 1240 | queue, |
| 1241 | enc, |
| 1242 | dst, |
| 1243 | dummy, |
| 1244 | view_proj, |
| 1245 | view, |
| 1246 | proj, |
| 1247 | cam_pos, |
| 1248 | cam_far, |
| 1249 | lights, |
| 1250 | lighting_enabled, |
| 1251 | shadows_enabled, |
| 1252 | want_z, |
| 1253 | want_normal, |
| 1254 | meshes, |
| 1255 | ) { |
| 1256 | let mut merged = dst.aux_cloned(); |
| 1257 | if aux.z.is_some() { |
| 1258 | merged.z = aux.z; |
| 1259 | } |
| 1260 | if aux.normal.is_some() { |
| 1261 | merged.normal = aux.normal; |
| 1262 | } |
| 1263 | dst.set_aux(Some(Arc::new(merged))); |
| 1264 | } |
| 1265 | } |
| 1266 | |
| 1267 | #[allow(clippy::too_many_arguments)] |
| 1268 | fn render_meshes_inner( |
| 1269 | &self, |
| 1270 | device: &wgpu::Device, |
| 1271 | queue: &wgpu::Queue, |
| 1272 | enc: &mut wgpu::CommandEncoder, |
| 1273 | dst: &CachedTexture, |
| 1274 | dummy: &CachedTexture, |
| 1275 | view_proj: Mat4, |
| 1276 | view: Mat4, |
| 1277 | proj: Mat4, |
| 1278 | cam_pos: [f32; 3], |
| 1279 | cam_far: f32, |
| 1280 | lights: SceneLights, |
| 1281 | lighting_enabled: bool, |
| 1282 | shadows_enabled: bool, |
| 1283 | want_z: bool, |
| 1284 | want_normal: bool, |
| 1285 | meshes: &[DrawMesh], |
| 1286 | ) -> Option<AuxChannels> { |
| 1287 | let depth_size = [dst.size[0].max(1), dst.size[1].max(1)]; |
| 1288 | let depth_target = lock_or_recover(&self.depth_targets).get_or_insert_with(depth_size, || { |
| 1289 | let tex = device.create_texture(&wgpu::TextureDescriptor { |
| 1290 | label: Some("scene3d-depth"), |
| 1291 | size: wgpu::Extent3d { |
| 1292 | width: depth_size[0], |
| 1293 | height: depth_size[1], |
| 1294 | depth_or_array_layers: 1, |
| 1295 | }, |
| 1296 | mip_level_count: 1, |
| 1297 | sample_count: 1, |
| 1298 | dimension: wgpu::TextureDimension::D2, |
| 1299 | format: wgpu::TextureFormat::Depth32Float, |
| 1300 | usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING, |
| 1301 | view_formats: &[], |
| 1302 | }); |
| 1303 | let view = tex.create_view(&wgpu::TextureViewDescriptor::default()); |
| 1304 | DepthTarget { tex, view } |
| 1305 | }); |
| 1306 | let depth_view = &depth_target.view; |
| 1307 | |
| 1308 | // Point-light indices that get a cube shadow map, in slot order. |
| 1309 | let shadow_lights: Vec<usize> = if shadows_enabled { |
| 1310 | (0..lights.points.len().min(MAX_LIGHTS)) |
| 1311 | .filter(|&i| lights.points[i].shadow_density.is_some()) |
| 1312 | .take(MAX_SHADOW_LIGHTS) |
| 1313 | .collect() |
| 1314 | } else { |
| 1315 | Vec::new() |
| 1316 | }; |
| 1317 | let mut shadow_face_vps = [mat4_identity(); 6 * MAX_SHADOW_LIGHTS]; |
| 1318 | let shadow_ubuf_owned = (!shadow_lights.is_empty()).then(|| { |
| 1319 | let mut shadow_uni = ShadowUniform { |
| 1320 | face_vp: [mat4_identity(); 6 * MAX_SHADOW_LIGHTS], |
| 1321 | point: [[-1.0, 0.0, 0.0, 0.0]; MAX_LIGHTS], |
| 1322 | }; |
| 1323 | // Receivers visible to the camera are at most `cam_far` from it, so that bounds the light's reach. |
| 1324 | let distance_to_cam = |p: [f32; 3]| (0..3).map(|i| (p[i] - cam_pos[i]).powi(2)).sum::<f32>().sqrt(); |
| 1325 | for (slot, &li) in shadow_lights.iter().enumerate() { |
| 1326 | let pl = &lights.points[li]; |
| 1327 | let far = cam_far + distance_to_cam(pl.pos); |
| 1328 | let vps = cube_face_view_projections(pl.pos, far); |
| 1329 | shadow_uni.face_vp[slot * 6..slot * 6 + 6].copy_from_slice(&vps); |
| 1330 | shadow_face_vps[slot * 6..slot * 6 + 6].copy_from_slice(&vps); |
| 1331 | shadow_uni.point[li] = [slot as f32, pl.shadow_density.unwrap_or(0.0), 0.0, 0.0]; |
| 1332 | } |
| 1333 | cached_uniform_buffer( |
| 1334 | &self.uniform_cache, |
| 1335 | device, |
| 1336 | "scene3d-shadow-u", |
| 1337 | bytemuck::bytes_of(&shadow_uni), |
| 1338 | ) |
| 1339 | }); |
| 1340 | let shadow_ubuf = shadow_ubuf_owned.as_ref().unwrap_or(&self.shadow_dummy_ubuf); |
| 1341 | let shadow_targets = (!shadow_lights.is_empty()).then(|| { |
| 1342 | let layers = 6 * shadow_lights.len() as u32; |
| 1343 | let mut cache = lock_or_recover(&self.shadow_targets); |
| 1344 | match cache.as_ref() { |
| 1345 | Some(t) if t.layers >= layers => t.clone(), |
| 1346 | _ => { |
| 1347 | let target = |label, format, usage, depth_or_array_layers| { |
| 1348 | device.create_texture(&wgpu::TextureDescriptor { |
| 1349 | label: Some(label), |
| 1350 | size: wgpu::Extent3d { width: SHADOW_MAP_SIZE, height: SHADOW_MAP_SIZE, depth_or_array_layers }, |
| 1351 | mip_level_count: 1, |
| 1352 | sample_count: 1, |
| 1353 | dimension: wgpu::TextureDimension::D2, |
| 1354 | format, |
| 1355 | usage, |
| 1356 | view_formats: &[], |
| 1357 | }) |
| 1358 | }; |
| 1359 | let maps = target( |
| 1360 | "scene3d-shadow-maps", |
| 1361 | wgpu::TextureFormat::R32Float, |
| 1362 | wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING, |
| 1363 | layers, |
| 1364 | ); |
| 1365 | let array_view = maps.create_view(&wgpu::TextureViewDescriptor { |
| 1366 | dimension: Some(wgpu::TextureViewDimension::D2Array), |
| 1367 | ..Default::default() |
| 1368 | }); |
| 1369 | let layer_views = (0..layers) |
| 1370 | .map(|layer| { |
| 1371 | maps.create_view(&wgpu::TextureViewDescriptor { |
| 1372 | dimension: Some(wgpu::TextureViewDimension::D2), |
| 1373 | base_array_layer: layer, |
| 1374 | array_layer_count: Some(1), |
| 1375 | ..Default::default() |
| 1376 | }) |
| 1377 | }) |
| 1378 | .collect(); |
| 1379 | let fresh = ShadowTargets { |
| 1380 | layers, |
| 1381 | array_view, |
| 1382 | layer_views, |
| 1383 | depth: target( |
| 1384 | "scene3d-shadow-depth", |
| 1385 | wgpu::TextureFormat::Depth32Float, |
| 1386 | wgpu::TextureUsages::RENDER_ATTACHMENT, |
| 1387 | 1, |
| 1388 | ) |
| 1389 | .create_view(&wgpu::TextureViewDescriptor::default()), |
| 1390 | }; |
| 1391 | *cache = Some(fresh.clone()); |
| 1392 | fresh |
| 1393 | } |
| 1394 | } |
| 1395 | }); |
| 1396 | let shadow_view = shadow_targets.as_ref().map(|t| &t.array_view); |
| 1397 | // One buffer holds every caster and face uniform of this render at dynamic offsets: casters |
| 1398 | // first (at most one per mesh), then six faces per light. |
| 1399 | let align = device.limits().min_uniform_buffer_offset_alignment; |
| 1400 | let uniform_stride = (CASTER_BYTES.max(FACE_BYTES) as u32).next_multiple_of(align) as usize; |
| 1401 | let face_base = meshes.len() * uniform_stride; |
| 1402 | let mut shadow_uniform_bytes = vec![0u8; if shadow_lights.is_empty() { 0 } else { face_base + shadow_lights.len() * 6 * uniform_stride }]; |
| 1403 | let mut n_casters = 0; |
| 1404 | |
| 1405 | // One dynamic-offset uniform buffer holds every mesh's `MeshUniform` for this render call. |
| 1406 | let mesh_uni_size = std::mem::size_of::<MeshUniform>(); |
| 1407 | let mesh_uni_stride = (mesh_uni_size as u32).next_multiple_of(align) as usize; |
| 1408 | let mut mesh_uniform_bytes = vec![0u8; meshes.len() * mesh_uni_stride]; |
| 1409 | |
| 1410 | // Sort back-to-front by view-space centroid so semi-transparent planes and partial |
| 1411 | // Cube3D face groups blend cleanly while preserving scene-graph order on equal depths. |
| 1412 | let mut order: Vec<(usize, f32)> = meshes |
| 1413 | .iter() |
| 1414 | .enumerate() |
| 1415 | .map(|(i, m)| { |
| 1416 | let c = shape_local_center(&m.shape); |
| 1417 | let wx = m.world[0] * c[0] + m.world[4] * c[1] + m.world[8] * c[2] + m.world[12]; |
| 1418 | let wy = m.world[1] * c[0] + m.world[5] * c[1] + m.world[9] * c[2] + m.world[13]; |
| 1419 | let wz = m.world[2] * c[0] + m.world[6] * c[1] + m.world[10] * c[2] + m.world[14]; |
| 1420 | let vz = view[2] * wx + view[6] * wy + view[10] * wz + view[14]; |
| 1421 | (i, vz) |
| 1422 | }) |
| 1423 | .collect(); |
| 1424 | order.sort_by(|a, b| a.1.total_cmp(&b.1)); |
| 1425 | |
| 1426 | struct PreparedDraw<'a> { |
| 1427 | wireframe: bool, |
| 1428 | cull: [bool; 2], |
| 1429 | tex_view: &'a wgpu::TextureView, |
| 1430 | bump_view: &'a wgpu::TextureView, |
| 1431 | uni_offset: u32, |
| 1432 | caster_offset: Option<u32>, |
| 1433 | vbuf: wgpu::Buffer, |
| 1434 | ibuf: wgpu::Buffer, |
| 1435 | idx_count: u32, |
| 1436 | } |
| 1437 | struct GpuDraw { |
| 1438 | wireframe: bool, |
| 1439 | /// Skip the `[back-facing, front-facing]` pass. |
| 1440 | cull: [bool; 2], |
| 1441 | bg: wgpu::BindGroup, |
| 1442 | uni_offset: u32, |
| 1443 | /// Dynamic offset into `shadow_dyn_buf`; `None` for meshes that cast no shadow. |
| 1444 | caster_offset: Option<u32>, |
| 1445 | vbuf: wgpu::Buffer, |
| 1446 | ibuf: wgpu::Buffer, |
| 1447 | idx_count: u32, |
| 1448 | } |
| 1449 | let mut prepared = Vec::with_capacity(order.len()); |
| 1450 | for (idx, _) in order { |
| 1451 | let m = &meshes[idx]; |
| 1452 | let aspect = m |
| 1453 | .tex |
| 1454 | .as_ref() |
| 1455 | .map(|t| (t.canvas_size[0] as f32 / t.canvas_size[1].max(1) as f32).max(1e-4)) |
| 1456 | .unwrap_or(16.0 / 9.0); |
| 1457 | let (base_shape, fx) = m.shape.split_fx(); |
| 1458 | let upload = || { |
| 1459 | let (mut verts, mut indices) = build_shape_mesh(base_shape, aspect); |
| 1460 | if indices.is_empty() { |
| 1461 | return None; |
| 1462 | } |
| 1463 | if let Some(disp) = &m.displace { |
| 1464 | apply_heightmap_displace(&mut verts, &indices, disp); |
| 1465 | } |
| 1466 | if fx.wireframe { |
| 1467 | indices = triangle_edges(&indices); |
| 1468 | } |
| 1469 | let vbytes = bytemuck::cast_slice(&verts); |
| 1470 | let ibytes = bytemuck::cast_slice(&indices); |
| 1471 | let vbuf_bytes = vbytes.len() as u64; |
| 1472 | let ibuf_bytes = ibytes.len() as u64; |
| 1473 | let vbuf = device.create_buffer(&wgpu::BufferDescriptor { |
| 1474 | label: Some("scene3d-vb"), |
| 1475 | size: vbuf_bytes, |
| 1476 | usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST, |
| 1477 | mapped_at_creation: false, |
| 1478 | }); |
| 1479 | queue.write_buffer(&vbuf, 0, vbytes); |
| 1480 | let ibuf = device.create_buffer(&wgpu::BufferDescriptor { |
| 1481 | label: Some("scene3d-ib"), |
| 1482 | size: ibuf_bytes, |
| 1483 | usage: wgpu::BufferUsages::INDEX | wgpu::BufferUsages::COPY_DST, |
| 1484 | mapped_at_creation: false, |
| 1485 | }); |
| 1486 | queue.write_buffer(&ibuf, 0, ibytes); |
| 1487 | Some(GpuMesh { vbuf, ibuf, idx_count: indices.len() as u32, vbuf_bytes, ibuf_bytes }) |
| 1488 | }; |
| 1489 | // Heightmap contents are not part of the key, so displaced meshes are never cached. |
| 1490 | let gpu_mesh = if m.displace.is_some() { |
| 1491 | upload() |
| 1492 | } else { |
| 1493 | let key = mesh_key(base_shape, m.custom_mesh_key, aspect, fx.wireframe); |
| 1494 | lock_or_recover(&self.meshes).get_or_insert_with(key, upload) |
| 1495 | }; |
| 1496 | let Some(GpuMesh { vbuf, ibuf, idx_count, .. }) = gpu_mesh else { |
| 1497 | continue; |
| 1498 | }; |
| 1499 | |
| 1500 | let mvp = mat4_mul(view_proj, m.world); |
| 1501 | let tex_dod = |tex: Option<&CachedTexture>| -> [f32; 4] { |
| 1502 | tex.filter(|t| t.has_dod()) |
| 1503 | .map_or([0.0; 4], |t| [t.origin[0] as f32, t.origin[1] as f32, t.canvas_size[0] as f32, t.canvas_size[1] as f32]) |
| 1504 | }; |
| 1505 | let dod = tex_dod(m.tex.as_ref()); |
| 1506 | let bump_src = m.bump_tex.as_ref().or_else(|| if fx.bump_only { m.tex.as_ref() } else { None }); |
| 1507 | let bump_dod = tex_dod(bump_src); |
| 1508 | let mut point_pos = [[0.0_f32; 4]; MAX_LIGHTS]; |
| 1509 | let mut point_col = [[0.0_f32; 4]; MAX_LIGHTS]; |
| 1510 | let n_pt = lights.points.len().min(MAX_LIGHTS); |
| 1511 | for (pi, pl) in lights.points.iter().take(MAX_LIGHTS).enumerate() { |
| 1512 | point_pos[pi] = [pl.pos[0], pl.pos[1], pl.pos[2], pl.decay_type]; |
| 1513 | point_col[pi] = [pl.color[0], pl.color[1], pl.color[2], 0.0]; |
| 1514 | } |
| 1515 | let mut spot_pos = [[0.0_f32; 4]; MAX_LIGHTS]; |
| 1516 | let mut spot_dir = [[0.0_f32; 4]; MAX_LIGHTS]; |
| 1517 | let mut spot_col = [[0.0_f32; 4]; MAX_LIGHTS]; |
| 1518 | let n_sp = lights.spots.len().min(MAX_LIGHTS); |
| 1519 | for (si, sl) in lights.spots.iter().take(MAX_LIGHTS).enumerate() { |
| 1520 | spot_pos[si] = [sl.pos[0], sl.pos[1], sl.pos[2], sl.cos_inner]; |
| 1521 | spot_dir[si] = [sl.dir[0], sl.dir[1], sl.dir[2], sl.cos_outer]; |
| 1522 | spot_col[si] = [sl.color[0], sl.color[1], sl.color[2], sl.decay_type]; |
| 1523 | } |
| 1524 | let mut dir_to_light = [[0.0_f32; 4]; MAX_DIR_LIGHTS]; |
| 1525 | let mut dir_color = [[0.0_f32; 4]; MAX_DIR_LIGHTS]; |
| 1526 | let n_dir = lights.dirs.len().min(MAX_DIR_LIGHTS); |
| 1527 | for (di, dl) in lights.dirs.iter().take(MAX_DIR_LIGHTS).enumerate() { |
| 1528 | dir_to_light[di] = [dl.to_light[0], dl.to_light[1], dl.to_light[2], 0.0]; |
| 1529 | dir_color[di] = [dl.color[0], dl.color[1], dl.color[2], 0.0]; |
| 1530 | } |
| 1531 | let use_diffuse_tex = m.tex.is_some() && fx.env_tex_slot != 1; |
| 1532 | let has_bump_tex = bump_src.is_some() && fx.env_tex_slot != 2 && fx.cb_fg_tex_slot != 2; |
| 1533 | let env_span = ((fx.env_end_angle - fx.env_start_angle) / 360.0).abs().max(1e-4); |
| 1534 | let uni = MeshUniform { |
| 1535 | mvp, |
| 1536 | model: m.world, |
| 1537 | view, |
| 1538 | dod, |
| 1539 | flags: [ |
| 1540 | if use_diffuse_tex { 1.0 } else { 0.0 }, |
| 1541 | if lighting_enabled && m.affected_by_lights { 1.0 } else { 0.0 }, |
| 1542 | m.specular_intensity, |
| 1543 | if m.flip_normals { 1.0 } else { 0.0 }, |
| 1544 | ], |
| 1545 | diffuse_col: m.diffuse_col, |
| 1546 | specular_col: [ |
| 1547 | m.specular_col[0], |
| 1548 | m.specular_col[1], |
| 1549 | m.specular_col[2], |
| 1550 | m.specular_exponent, |
| 1551 | ], |
| 1552 | ambient: [lights.ambient[0], lights.ambient[1], lights.ambient[2], 0.0], |
| 1553 | dir_to_light, |
| 1554 | dir_color, |
| 1555 | cam_pos: [cam_pos[0], cam_pos[1], cam_pos[2], 0.0], |
| 1556 | light_counts: [n_pt as f32, n_sp as f32, n_dir as f32, if m.receives_shadows { 1.0 } else { 0.0 }], |
| 1557 | uv_xform: fx.uv.m, |
| 1558 | uv_off_wrap: [fx.uv.t[0], fx.uv.t[1], fx.uv_wrap as f32, if lighting_enabled && fx.per_light_unlit { lights.count.max(1) as f32 } else { 1.0 }], |
| 1559 | mat_fx: [fx.bump_scale, fx.bump_mode as f32, if fx.bump_only { 1.0 } else { 0.0 }, fx.spec_model as u32 as f32], |
| 1560 | bump_uv_xform: fx.bump_uv.m, |
| 1561 | bump_off_wrap: [fx.bump_uv.t[0], fx.bump_uv.t[1], fx.bump_wrap as f32, if has_bump_tex { 1.0 } else { 0.0 }], |
| 1562 | bump_dod, |
| 1563 | bump_params: [fx.bump_clamp_z, fx.bump_channel as f32, 0.0, 0.0], |
| 1564 | mtl_params: [ |
| 1565 | fx.diffuse_color_alpha, |
| 1566 | fx.refractive_index, |
| 1567 | if fx.do_fresnel { 1.0 } else { 0.0 }, |
| 1568 | fx.ward_spread_v, |
| 1569 | ], |
| 1570 | env_rot_0: [fx.env_rot[0], fx.env_rot[1], fx.env_rot[2], fx.env_mode as f32], |
| 1571 | env_rot_1: [fx.env_rot[3], fx.env_rot[4], fx.env_rot[5], fx.env_map_mode as f32], |
| 1572 | env_rot_2: [fx.env_rot[6], fx.env_rot[7], fx.env_rot[8], fx.env_tex_slot as f32], |
| 1573 | env_angles: [ |
| 1574 | fx.env_start_angle / 360.0, |
| 1575 | 1.0 / env_span, |
| 1576 | fx.refl_strength_var as f32, |
| 1577 | fx.refl_constant_strength, |
| 1578 | ], |
| 1579 | refl_params: [ |
| 1580 | fx.refl_glancing_strength, |
| 1581 | fx.refl_face_on_strength, |
| 1582 | fx.refl_falloff, |
| 1583 | fx.refract_ior, |
| 1584 | ], |
| 1585 | refl_tint: [ |
| 1586 | fx.refl_tint[0], |
| 1587 | fx.refl_tint[1], |
| 1588 | fx.refl_tint[2], |
| 1589 | if fx.refl_has_bg { 1.0 } else { 0.0 }, |
| 1590 | ], |
| 1591 | refract_tint: [fx.refract_tint[0], fx.refract_tint[1], fx.refract_tint[2], 0.0], |
| 1592 | cb_ops_a: fx.cb_ops_a.map(f32::from), |
| 1593 | cb_ops: fx.cb_ops.map(f32::from), |
| 1594 | cb_ops_b: fx.cb_ops_b.map(f32::from), |
| 1595 | cb_fg_col: fx.cb_fg_col, |
| 1596 | cb_flags: [ |
| 1597 | if fx.cb_enabled { 1.0 } else { 0.0 }, |
| 1598 | f32::from(fx.cb_coord_space), |
| 1599 | f32::from(fx.cb_fg_tex_slot), |
| 1600 | 0.0, |
| 1601 | ], |
| 1602 | point_pos, |
| 1603 | point_col, |
| 1604 | spot_pos, |
| 1605 | spot_dir, |
| 1606 | spot_col, |
| 1607 | }; |
| 1608 | let uni_offset = prepared.len() * mesh_uni_stride; |
| 1609 | mesh_uniform_bytes[uni_offset..uni_offset + mesh_uni_size].copy_from_slice(bytemuck::bytes_of(&uni)); |
| 1610 | let tex_view = m.tex.as_ref().map_or(&dummy.view, |t| &t.view); |
| 1611 | let bump_view = bump_src.map_or(&dummy.view, |t| &t.view); |
| 1612 | // Fusion's RendererOpenGL casts solid geometry shadows regardless of texture/material alpha. |
| 1613 | let caster_offset = (!shadow_lights.is_empty() && m.casts_shadow && !fx.wireframe).then(|| { |
| 1614 | let offset = n_casters * uniform_stride; |
| 1615 | shadow_uniform_bytes[offset..offset + CASTER_BYTES].copy_from_slice(bytemuck::cast_slice(&m.world)); |
| 1616 | n_casters += 1; |
| 1617 | offset as u32 |
| 1618 | }); |
| 1619 | prepared.push(PreparedDraw { |
| 1620 | wireframe: fx.wireframe, |
| 1621 | cull: [fx.cull_back, fx.cull_front], |
| 1622 | tex_view, |
| 1623 | bump_view, |
| 1624 | uni_offset: uni_offset as u32, |
| 1625 | caster_offset, |
| 1626 | vbuf, |
| 1627 | ibuf, |
| 1628 | idx_count, |
| 1629 | }); |
| 1630 | } |
| 1631 | let mesh_dyn_buf = (!prepared.is_empty()).then(|| { |
| 1632 | cached_uniform_buffer( |
| 1633 | &self.uniform_cache, |
| 1634 | device, |
| 1635 | "scene3d-mesh-dyn", |
| 1636 | &mesh_uniform_bytes[..prepared.len() * mesh_uni_stride], |
| 1637 | ) |
| 1638 | }); |
| 1639 | let draw_items: Vec<GpuDraw> = prepared |
| 1640 | .into_iter() |
| 1641 | .map(|p| { |
| 1642 | let mesh_buf = mesh_dyn_buf.as_ref().expect("mesh_dyn_buf allocated when prepared non-empty"); |
| 1643 | let bg = device.create_bind_group(&wgpu::BindGroupDescriptor { |
| 1644 | label: Some("scene3d-bg"), |
| 1645 | layout: &self.bgl, |
| 1646 | entries: &[ |
| 1647 | wgpu::BindGroupEntry { |
| 1648 | binding: 0, |
| 1649 | resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { |
| 1650 | buffer: mesh_buf, |
| 1651 | offset: 0, |
| 1652 | size: std::num::NonZeroU64::new(mesh_uni_size as u64), |
| 1653 | }), |
| 1654 | }, |
| 1655 | wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(p.tex_view) }, |
| 1656 | wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::Sampler(&self.sampler) }, |
| 1657 | wgpu::BindGroupEntry { binding: 3, resource: shadow_ubuf.as_entire_binding() }, |
| 1658 | wgpu::BindGroupEntry { |
| 1659 | binding: 4, |
| 1660 | resource: wgpu::BindingResource::TextureView(shadow_view.unwrap_or(&self.shadow_dummy)), |
| 1661 | }, |
| 1662 | wgpu::BindGroupEntry { binding: 5, resource: wgpu::BindingResource::TextureView(p.bump_view) }, |
| 1663 | ], |
| 1664 | }); |
| 1665 | GpuDraw { |
| 1666 | wireframe: p.wireframe, |
| 1667 | cull: p.cull, |
| 1668 | bg, |
| 1669 | uni_offset: p.uni_offset, |
| 1670 | caster_offset: p.caster_offset, |
| 1671 | vbuf: p.vbuf, |
| 1672 | ibuf: p.ibuf, |
| 1673 | idx_count: p.idx_count, |
| 1674 | } |
| 1675 | }) |
| 1676 | .collect(); |
| 1677 | |
| 1678 | if let Some(targets) = &shadow_targets { |
| 1679 | for (slot, &li) in shadow_lights.iter().enumerate() { |
| 1680 | let pos = lights.points[li].pos; |
| 1681 | for face in 0..6 { |
| 1682 | let layer = slot * 6 + face; |
| 1683 | let mut uniform = [0.0_f32; FACE_BYTES / 4]; |
| 1684 | uniform[..16].copy_from_slice(&shadow_face_vps[layer]); |
| 1685 | uniform[16..19].copy_from_slice(&pos); |
| 1686 | let face_offset = face_base + layer * uniform_stride; |
| 1687 | shadow_uniform_bytes[face_offset..face_offset + FACE_BYTES].copy_from_slice(bytemuck::cast_slice(&uniform)); |
| 1688 | } |
| 1689 | } |
| 1690 | let shadow_dyn_buf = cached_uniform_buffer( |
| 1691 | &self.uniform_cache, |
| 1692 | device, |
| 1693 | "scene3d-shadow-dyn", |
| 1694 | &shadow_uniform_bytes, |
| 1695 | ); |
| 1696 | let caster_bg = device.create_bind_group(&wgpu::BindGroupDescriptor { |
| 1697 | label: Some("scene3d-shadow-caster"), |
| 1698 | layout: &self.shadow_caster_bgl, |
| 1699 | entries: &[wgpu::BindGroupEntry { |
| 1700 | binding: 0, |
| 1701 | resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { |
| 1702 | buffer: &shadow_dyn_buf, |
| 1703 | offset: 0, |
| 1704 | size: std::num::NonZeroU64::new(CASTER_BYTES as u64), |
| 1705 | }), |
| 1706 | }], |
| 1707 | }); |
| 1708 | let face_bg = device.create_bind_group(&wgpu::BindGroupDescriptor { |
| 1709 | label: Some("scene3d-shadow-face"), |
| 1710 | layout: &self.shadow_face_bgl, |
| 1711 | entries: &[wgpu::BindGroupEntry { |
| 1712 | binding: 0, |
| 1713 | resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { |
| 1714 | buffer: &shadow_dyn_buf, |
| 1715 | offset: 0, |
| 1716 | size: std::num::NonZeroU64::new(FACE_BYTES as u64), |
| 1717 | }), |
| 1718 | }], |
| 1719 | }); |
| 1720 | for slot in 0..shadow_lights.len() { |
| 1721 | for face in 0..6 { |
| 1722 | let layer = slot * 6 + face; |
| 1723 | let face_offset = face_base + layer * uniform_stride; |
| 1724 | let layer_view = &targets.layer_views[layer]; |
| 1725 | let mut pass = enc.begin_render_pass(&wgpu::RenderPassDescriptor { |
| 1726 | label: Some("scene3d-shadow-pass"), |
| 1727 | color_attachments: &[Some(wgpu::RenderPassColorAttachment { |
| 1728 | view: layer_view, |
| 1729 | depth_slice: None, |
| 1730 | resolve_target: None, |
| 1731 | ops: wgpu::Operations { |
| 1732 | load: wgpu::LoadOp::Clear(wgpu::Color { r: 1e30, g: 0.0, b: 0.0, a: 0.0 }), |
| 1733 | store: wgpu::StoreOp::Store, |
| 1734 | }, |
| 1735 | })], |
| 1736 | depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { |
| 1737 | view: &targets.depth, |
| 1738 | depth_ops: Some(wgpu::Operations { |
| 1739 | load: wgpu::LoadOp::Clear(1.0), |
| 1740 | store: wgpu::StoreOp::Discard, |
| 1741 | }), |
| 1742 | stencil_ops: None, |
| 1743 | }), |
| 1744 | timestamp_writes: None, |
| 1745 | occlusion_query_set: None, |
| 1746 | multiview_mask: None, |
| 1747 | }); |
| 1748 | pass.set_pipeline(&self.shadow_pipeline); |
| 1749 | pass.set_bind_group(1, &face_bg, &[face_offset as u32]); |
| 1750 | for d in &draw_items { |
| 1751 | let Some(caster_offset) = d.caster_offset else { continue }; |
| 1752 | pass.set_bind_group(0, &caster_bg, &[caster_offset]); |
| 1753 | pass.set_vertex_buffer(0, d.vbuf.slice(..)); |
| 1754 | pass.set_index_buffer(d.ibuf.slice(..), wgpu::IndexFormat::Uint32); |
| 1755 | pass.draw_indexed(0..d.idx_count, 0, 0..1); |
| 1756 | } |
| 1757 | } |
| 1758 | } |
| 1759 | } |
| 1760 | |
| 1761 | let mut pass = enc.begin_render_pass(&wgpu::RenderPassDescriptor { |
| 1762 | label: Some("scene3d-pass"), |
| 1763 | color_attachments: &[Some(wgpu::RenderPassColorAttachment { |
| 1764 | view: &dst.view, |
| 1765 | depth_slice: None, |
| 1766 | resolve_target: None, |
| 1767 | ops: wgpu::Operations { |
| 1768 | load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT), |
| 1769 | store: wgpu::StoreOp::Store, |
| 1770 | }, |
| 1771 | })], |
| 1772 | depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { |
| 1773 | view: depth_view, |
| 1774 | depth_ops: Some(wgpu::Operations { |
| 1775 | load: wgpu::LoadOp::Clear(1.0), |
| 1776 | store: if want_z { wgpu::StoreOp::Store } else { wgpu::StoreOp::Discard }, |
| 1777 | }), |
| 1778 | stencil_ops: None, |
| 1779 | }), |
| 1780 | timestamp_writes: None, |
| 1781 | occlusion_query_set: None, |
| 1782 | multiview_mask: None, |
| 1783 | }); |
| 1784 | for d in &draw_items { |
| 1785 | pass.set_bind_group(0, &d.bg, &[d.uni_offset]); |
| 1786 | pass.set_vertex_buffer(0, d.vbuf.slice(..)); |
| 1787 | pass.set_index_buffer(d.ibuf.slice(..), wgpu::IndexFormat::Uint32); |
| 1788 | for (pipeline, culled) in self.pipelines[d.wireframe as usize].iter().zip(d.cull) { |
| 1789 | if !culled { |
| 1790 | pass.set_pipeline(pipeline); |
| 1791 | pass.draw_indexed(0..d.idx_count, 0, 0..1); |
| 1792 | } |
| 1793 | } |
| 1794 | } |
| 1795 | drop(pass); |
| 1796 | |
| 1797 | if !want_z && !want_normal { |
| 1798 | return None; |
| 1799 | } |
| 1800 | |
| 1801 | let mut aux = AuxChannels::default(); |
| 1802 | if want_z { |
| 1803 | let z_tex = AuxChannelTex::new(device, depth_size, wgpu::TextureFormat::R32Float, "scene3d-aux-z"); |
| 1804 | let depth_z_uni = DepthToEyeZUniform { |
| 1805 | proj_zw: [proj[10], proj[11], proj[14], proj[15]], |
| 1806 | params: [EMPTY_Z_SENTINEL, 0.0, 0.0, 0.0], |
| 1807 | }; |
| 1808 | let depth_z_ubuf = cached_uniform_buffer( |
| 1809 | &self.uniform_cache, |
| 1810 | device, |
| 1811 | "scene3d-depth-z-u", |
| 1812 | bytemuck::bytes_of(&depth_z_uni), |
| 1813 | ); |
| 1814 | let bg = device.create_bind_group(&wgpu::BindGroupDescriptor { |
| 1815 | label: Some("scene3d-depth-z-bg"), |
| 1816 | layout: &self.depth_z_bgl, |
| 1817 | entries: &[ |
| 1818 | wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(depth_view) }, |
| 1819 | wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(&z_tex.view) }, |
| 1820 | wgpu::BindGroupEntry { binding: 2, resource: depth_z_ubuf.as_entire_binding() }, |
| 1821 | ], |
| 1822 | }); |
| 1823 | let mut cpass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor { |
| 1824 | label: Some("scene3d-depth-to-eye-z"), |
| 1825 | timestamp_writes: None, |
| 1826 | }); |
| 1827 | cpass.set_pipeline(&self.depth_z_pipeline); |
| 1828 | cpass.set_bind_group(0, &bg, &[]); |
| 1829 | cpass.dispatch_workgroups(z_tex.size[0].div_ceil(8), z_tex.size[1].div_ceil(8), 1); |
| 1830 | aux.z = Some(z_tex); |
| 1831 | } |
| 1832 | |
| 1833 | if want_normal { |
| 1834 | let normal_raw = device.create_texture(&wgpu::TextureDescriptor { |
| 1835 | label: Some("scene3d-aux-normal"), |
| 1836 | size: wgpu::Extent3d { |
| 1837 | width: depth_size[0], |
| 1838 | height: depth_size[1], |
| 1839 | depth_or_array_layers: 1, |
| 1840 | }, |
| 1841 | mip_level_count: 1, |
| 1842 | sample_count: 1, |
| 1843 | dimension: wgpu::TextureDimension::D2, |
| 1844 | format: wgpu::TextureFormat::Rgba16Float, |
| 1845 | usage: wgpu::TextureUsages::RENDER_ATTACHMENT |
| 1846 | | wgpu::TextureUsages::TEXTURE_BINDING |
| 1847 | | wgpu::TextureUsages::COPY_SRC |
| 1848 | | wgpu::TextureUsages::COPY_DST, |
| 1849 | view_formats: &[], |
| 1850 | }); |
| 1851 | let normal_tex = AuxChannelTex::from_texture(normal_raw, depth_size); |
| 1852 | let mut npass = enc.begin_render_pass(&wgpu::RenderPassDescriptor { |
| 1853 | label: Some("scene3d-normal-pass"), |
| 1854 | color_attachments: &[Some(wgpu::RenderPassColorAttachment { |
| 1855 | view: &normal_tex.view, |
| 1856 | depth_slice: None, |
| 1857 | resolve_target: None, |
| 1858 | ops: wgpu::Operations { |
| 1859 | load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT), |
| 1860 | store: wgpu::StoreOp::Store, |
| 1861 | }, |
| 1862 | })], |
| 1863 | depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { |
| 1864 | view: depth_view, |
| 1865 | depth_ops: Some(wgpu::Operations { |
| 1866 | load: wgpu::LoadOp::Clear(1.0), |
| 1867 | store: wgpu::StoreOp::Discard, |
| 1868 | }), |
| 1869 | stencil_ops: None, |
| 1870 | }), |
| 1871 | timestamp_writes: None, |
| 1872 | occlusion_query_set: None, |
| 1873 | multiview_mask: None, |
| 1874 | }); |
| 1875 | for d in &draw_items { |
| 1876 | npass.set_bind_group(0, &d.bg, &[d.uni_offset]); |
| 1877 | npass.set_vertex_buffer(0, d.vbuf.slice(..)); |
| 1878 | npass.set_index_buffer(d.ibuf.slice(..), wgpu::IndexFormat::Uint32); |
| 1879 | for (pipeline, culled) in self.normal_pipelines[d.wireframe as usize].iter().zip(d.cull) { |
| 1880 | if !culled { |
| 1881 | npass.set_pipeline(pipeline); |
| 1882 | npass.draw_indexed(0..d.idx_count, 0, 0..1); |
| 1883 | } |
| 1884 | } |
| 1885 | } |
| 1886 | drop(npass); |
| 1887 | aux.normal = Some(normal_tex); |
| 1888 | } |
| 1889 | |
| 1890 | Some(aux) |
| 1891 | } |
| 1892 | } |
| 1893 | |
| 1894 | #[cfg(test)] |
| 1895 | mod tests { |
| 1896 | use super::*; |
| 1897 | use crate::Engine; |
| 1898 | use model::Comp; |
| 1899 | |
| 1900 | /// Renders `Renderer3D` node `R` of a 64x64 scene viewed by a camera at z=4.2 (35mm lens, 1" gate). |
| 1901 | fn render(lighting: bool, scene: &str) -> Option<Vec<u8>> { |
| 1902 | let src = format!( |
| 1903 | r#"Composition {{ CurrentTime = 0, RenderRange = {{ 0, 1 }}, GlobalRange = {{ 0, 1 }}, Tools = ordered() {{ |
| 1904 | Bg = Background {{ Inputs = {{ Width = Input {{ Value = 8, }}, Height = Input {{ Value = 8, }}, TopLeftRed = Input {{ Value = 1, }}, TopLeftGreen = Input {{ Value = 0.5, }}, TopLeftBlue = Input {{ Value = 0.25, }}, TopLeftAlpha = Input {{ Value = 1, }}, }}, }}, |
| 1905 | Tex = Texture2DOperator {{ Inputs = {{ Input = Input {{ SourceOp = "Bg", Source = "Output", }}, }}, }}, |
| 1906 | Flat = MtlBlinn {{ Inputs = {{ ["Specular.Intensity"] = Input {{ Value = 0, }}, }}, }}, |
| 1907 | Cam = Camera3D {{ Inputs = {{ ["Transform3DOp.Translate.Z"] = Input {{ Value = 4.2, }}, ApertureW = Input {{ Value = 1.0, }}, ApertureH = Input {{ Value = 1.0, }}, }}, }}, |
| 1908 | {scene} |
| 1909 | R = Renderer3D {{ Inputs = {{ Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }}, ["RendererSoftware.LightingEnabled"] = Input {{ Value = {}, }}, SceneInput = Input {{ SourceOp = "M", Source = "Output", }}, }}, }}, |
| 1910 | }} }}"#, |
| 1911 | lighting as u8 |
| 1912 | ); |
| 1913 | let comp = Comp::from_fusion_str(&src).expect("parse render comp"); |
| 1914 | let mut eng = Engine::new_headless().ok()?; |
| 1915 | let id = comp.find_node("R").expect("R"); |
| 1916 | let (tex, _) = eng.evaluate(&comp, id, 0.0); |
| 1917 | eng.readback_rgba(&tex).ok() |
| 1918 | } |
| 1919 | |
| 1920 | fn center(px: &[u8]) -> [u8; 4] { |
| 1921 | let i = (32 * 64 + 32) * 4; |
| 1922 | [px[i], px[i + 1], px[i + 2], px[i + 3]] |
| 1923 | } |
| 1924 | |
| 1925 | const PLANE: &str = r#"P = Shape3D { Inputs = { ["SurfacePlaneInputs.Width"] = Input { Value = 2, }, MaterialInput = Input { SourceOp = "Flat", Source = "MaterialOutput", }, }, },"#; |
| 1926 | |
| 1927 | #[test] |
| 1928 | fn point_light_decay_is_inverse_distance_and_inverse_square() { |
| 1929 | for (decay, expected) in [(0, 255.0), (1, 127.5), (2, 63.75)] { |
| 1930 | let scene = format!( |
| 1931 | r#"{PLANE} L = LightPoint {{ Inputs = {{ ["Transform3DOp.Translate.Z"] = Input {{ Value = 2, }}, DecayType = Input {{ Value = {decay}, }}, }}, }}, |
| 1932 | M = Merge3D {{ Inputs = {{ SceneInput1 = Input {{ SourceOp = "P", Source = "Output", }}, SceneInput2 = Input {{ SourceOp = "L", Source = "Output", }}, SceneInput3 = Input {{ SourceOp = "Cam", Source = "Output", }}, }}, }},"# |
| 1933 | ); |
| 1934 | let Some(px) = render(true, &scene) else { return }; |
| 1935 | let c = center(&px); |
| 1936 | assert!((c[0] as f32 - expected).abs() <= 3.0, "decay {decay}: {c:?}"); |
| 1937 | } |
| 1938 | } |
| 1939 | |
| 1940 | #[test] |
| 1941 | fn bare_texture_renders_unlit_but_blinn_diffuse_is_lit() { |
| 1942 | let scene = |mat: &str| { |
| 1943 | format!( |
| 1944 | r#"Shaded = MtlBlinn {{ Inputs = {{ ["Diffuse.Color.Material"] = Input {{ SourceOp = "Tex", Source = "MaterialOutput", }}, }}, }}, |
| 1945 | P = Shape3D {{ Inputs = {{ ["SurfacePlaneInputs.Width"] = Input {{ Value = 2, }}, MaterialInput = Input {{ SourceOp = "{mat}", Source = "MaterialOutput", }}, }}, }}, |
| 1946 | M = Merge3D {{ Inputs = {{ SceneInput1 = Input {{ SourceOp = "P", Source = "Output", }}, SceneInput2 = Input {{ SourceOp = "Cam", Source = "Output", }}, }}, }},"# |
| 1947 | ) |
| 1948 | }; |
| 1949 | let (Some(flat), Some(shaded)) = (render(true, &scene("Tex")), render(true, &scene("Shaded"))) else { return }; |
| 1950 | assert_eq!(center(&flat), [255, 128, 64, 255]); |
| 1951 | assert_eq!(center(&shaded)[..3], [0, 0, 0], "lighting on with no lights is black"); |
| 1952 | } |
| 1953 | |
| 1954 | #[test] |
| 1955 | fn wireframe_draws_edges_only() { |
| 1956 | let scene = |wire: u8| { |
| 1957 | format!( |
| 1958 | r#"P = Shape3D {{ Inputs = {{ ["SurfacePlaneInputs.Width"] = Input {{ Value = 2, }}, ["SurfacePlaneInputs.SubdivisionWidth"] = Input {{ Value = 2, }}, ["SurfacePlaneInputs.Wireframe"] = Input {{ Value = {wire}, }}, }}, }}, |
| 1959 | M = Merge3D {{ Inputs = {{ SceneInput1 = Input {{ SourceOp = "P", Source = "Output", }}, SceneInput2 = Input {{ SourceOp = "Cam", Source = "Output", }}, }}, }},"# |
| 1960 | ) |
| 1961 | }; |
| 1962 | let (Some(solid), Some(wire)) = (render(false, &scene(0)), render(false, &scene(1))) else { return }; |
| 1963 | let coverage = |px: &[u8]| px.chunks_exact(4).filter(|c| c[3] > 0).count(); |
| 1964 | assert_eq!(center(&solid)[3], 255); |
| 1965 | assert!(coverage(&wire) > 0 && coverage(&wire) < coverage(&solid) / 4, "{} vs {}", coverage(&wire), coverage(&solid)); |
| 1966 | } |
| 1967 | |
| 1968 | #[test] |
| 1969 | fn translucent_front_faces_show_the_inside_of_a_closed_mesh() { |
| 1970 | // Half-opaque cube: front and back faces both blend, so coverage accumulates to 0.75. |
| 1971 | let scene = r#"B = Shape3D { Inputs = { Shape = Input { Value = FuID { "SurfaceCubeInputs" }, }, ["MtlStdInputs.Diffuse.Opacity"] = Input { Value = 0.5, }, }, }, |
| 1972 | M = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = "B", Source = "Output", }, SceneInput2 = Input { SourceOp = "Cam", Source = "Output", }, }, },"#; |
| 1973 | let Some(px) = render(false, scene) else { return }; |
| 1974 | let alpha = center(&px)[3] as i32; |
| 1975 | assert!((alpha - 191).abs() <= 3, "alpha {alpha}"); |
| 1976 | } |
| 1977 | |
| 1978 | #[test] |
| 1979 | fn normals_stay_perpendicular_under_non_uniform_scale() { |
| 1980 | // Plane rotated 45 degrees about Y under a [4, 1, 1] scale: the true normal is |
| 1981 | // (1/4, 0, 1) normalized, so a +Z light gives cos = 0.970; `model * n` would give 0.243. |
| 1982 | let scene = r#"P = Shape3D { Inputs = { ["SurfacePlaneInputs.Width"] = Input { Value = 2, }, ["Transform3DOp.Rotate.Y"] = Input { Value = 45, }, MaterialInput = Input { SourceOp = "Flat", Source = "MaterialOutput", }, }, }, |
| 1983 | S = Transform3D { Inputs = { ["Transform3DOp.ScaleLock"] = Input { Value = 0, }, ["Transform3DOp.Scale.X"] = Input { Value = 4, }, SceneInput1 = Input { SourceOp = "P", Source = "Output", }, }, }, |
| 1984 | L = LightDirectional { }, |
| 1985 | M = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = "S", Source = "Output", }, SceneInput2 = Input { SourceOp = "L", Source = "Output", }, SceneInput3 = Input { SourceOp = "Cam", Source = "Output", }, }, },"#; |
| 1986 | let Some(px) = render(true, scene) else { return }; |
| 1987 | let expected = 255.0 / (1.0 + 1.0 / 16.0_f32).sqrt(); |
| 1988 | let c = center(&px); |
| 1989 | assert!((c[0] as f32 - expected).abs() <= 3.0, "{c:?} vs {expected}"); |
| 1990 | } |
| 1991 | |
| 1992 | #[test] |
| 1993 | fn up_to_four_directional_lights_accumulate() { |
| 1994 | // Five 0.1 lights facing the plane: the first four reach the shader, so 0.4 * 255. |
| 1995 | let lights: String = (1..=5) |
| 1996 | .map(|i| format!(r#"L{i} = LightDirectional {{ Inputs = {{ Intensity = Input {{ Value = 0.1, }}, }}, }},"#)) |
| 1997 | .collect(); |
| 1998 | let ports: String = (1..=5).map(|i| format!(r#"SceneInput{} = Input {{ SourceOp = "L{i}", Source = "Output", }},"#, i + 1)).collect(); |
| 1999 | let scene = format!( |
| 2000 | r#"{PLANE} {lights} |
| 2001 | M = Merge3D {{ Inputs = {{ SceneInput1 = Input {{ SourceOp = "P", Source = "Output", }}, {ports} SceneInput7 = Input {{ SourceOp = "Cam", Source = "Output", }}, }}, }},"# |
| 2002 | ); |
| 2003 | let Some(px) = render(true, &scene) else { return }; |
| 2004 | let c = center(&px); |
| 2005 | assert!((c[0] as f32 - 102.0).abs() <= 3.0, "{c:?}"); |
| 2006 | } |
| 2007 | |
| 2008 | #[test] |
| 2009 | fn gpu_meshes_are_reused_across_frames_and_split_by_wireframe() { |
| 2010 | let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle()); |
| 2011 | let Ok(adapter) = pollster::block_on(instance.request_adapter(&Default::default())) else { return }; |
| 2012 | let Ok((device, queue)) = pollster::block_on(adapter.request_device(&Default::default())) else { return }; |
| 2013 | let renderer = Scene3DRenderer::new(&device); |
| 2014 | let target = || { |
| 2015 | CachedTexture::from_texture( |
| 2016 | device.create_texture(&wgpu::TextureDescriptor { |
| 2017 | label: None, |
| 2018 | size: wgpu::Extent3d { width: 8, height: 8, depth_or_array_layers: 1 }, |
| 2019 | mip_level_count: 1, |
| 2020 | sample_count: 1, |
| 2021 | dimension: wgpu::TextureDimension::D2, |
| 2022 | format: wgpu::TextureFormat::Rgba8Unorm, |
| 2023 | usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::RENDER_ATTACHMENT, |
| 2024 | view_formats: &[], |
| 2025 | }), |
| 2026 | [8, 8], |
| 2027 | 0, |
| 2028 | ) |
| 2029 | }; |
| 2030 | let (dst, dummy) = (target(), target()); |
| 2031 | let sphere = |x: f32, wireframe: bool| DrawMesh { |
| 2032 | world: mat4_translate(x, 0.0, 0.0), |
| 2033 | shape: ShapeKind::WithMaterialFx { |
| 2034 | inner: Box::new(ShapeKind::Sphere { radius: 1.0, sub_base: 8, sub_height: 8 }), |
| 2035 | fx: MaterialFx { wireframe, ..Default::default() }, |
| 2036 | }, |
| 2037 | custom_mesh_key: None, |
| 2038 | tex: None, |
| 2039 | bump_tex: None, |
| 2040 | diffuse_col: [1.0; 4], |
| 2041 | specular_col: [1.0; 3], |
| 2042 | specular_intensity: 0.0, |
| 2043 | specular_exponent: 50.0, |
| 2044 | affected_by_lights: false, |
| 2045 | casts_shadow: true, |
| 2046 | receives_shadows: true, |
| 2047 | flip_normals: false, |
| 2048 | displace: None, |
| 2049 | }; |
| 2050 | let frame = |meshes: &[DrawMesh]| { |
| 2051 | let mut enc = device.create_command_encoder(&Default::default()); |
| 2052 | let (vp, cam) = (mat4_identity(), [0.0, 0.0, 5.0]); |
| 2053 | renderer.render_meshes(&device, &queue, &mut enc, &dst, &dummy, vp, vp, cam, 1000.0, SceneLights::default(), false, false, meshes); |
| 2054 | queue.submit(Some(enc.finish())); |
| 2055 | lock_or_recover(&renderer.meshes).entries.len() |
| 2056 | }; |
| 2057 | assert_eq!(frame(&[sphere(0.0, false)]), 1); |
| 2058 | assert_eq!(frame(&[sphere(0.5, false)]), 1, "a moved copy reuses the upload"); |
| 2059 | assert_eq!(frame(&[sphere(0.5, true)]), 2, "wireframe uses edge indices"); |
| 2060 | } |
| 2061 | |
| 2062 | #[test] |
| 2063 | fn lru_evicts_the_least_recently_used_entry_and_reuses_hits() { |
| 2064 | let mut lru = Lru::new(2); |
| 2065 | let builds = std::cell::Cell::new(0); |
| 2066 | let get = |lru: &mut Lru<u8, u8>, k: u8| lru.get_or_insert_with(k, || { builds.set(builds.get() + 1); k }); |
| 2067 | get(&mut lru, 1); |
| 2068 | get(&mut lru, 2); |
| 2069 | get(&mut lru, 1); |
| 2070 | get(&mut lru, 3); |
| 2071 | assert_eq!(builds.get(), 3, "second request for key 1 is a hit"); |
| 2072 | get(&mut lru, 1); |
| 2073 | assert_eq!(builds.get(), 3, "key 1 was refreshed, so key 2 was evicted"); |
| 2074 | get(&mut lru, 2); |
| 2075 | assert_eq!(builds.get(), 4); |
| 2076 | assert_eq!(lru.entries.len(), 2); |
| 2077 | } |
| 2078 | |
| 2079 | #[test] |
| 2080 | fn uv_affine_then_applies_self_first() { |
| 2081 | let shift = UvAffine { m: [1.0, 0.0, 0.0, 1.0], t: [0.5, 0.0] }; |
| 2082 | let double = UvAffine { m: [2.0, 0.0, 0.0, 2.0], t: [0.0, 0.0] }; |
| 2083 | assert_eq!(shift.then(&double).apply([0.0, 0.0]), [1.0, 0.0]); |
| 2084 | assert_eq!(double.then(&shift).apply([0.0, 0.0]), [0.5, 0.0]); |
| 2085 | } |
| 2086 | |
| 2087 | #[test] |
| 2088 | fn opengl_renderer_lighting_and_point_light_shadows() { |
| 2089 | let render_gl = |lighting: u8, shadows: u8| -> Option<Vec<u8>> { |
| 2090 | let src = format!( |
| 2091 | r#"Composition {{ CurrentTime = 0, RenderRange = {{ 0, 1 }}, GlobalRange = {{ 0, 1 }}, Tools = ordered() {{ |
| 2092 | Flat = MtlBlinn {{ Inputs = {{ ["Specular.Intensity"] = Input {{ Value = 0, }}, }}, }}, |
| 2093 | Recv = Shape3D {{ Inputs = {{ ["SurfacePlaneInputs.Width"] = Input {{ Value = 8, }}, ["Transform3DOp.Translate.Z"] = Input {{ Value = -2, }}, MaterialInput = Input {{ SourceOp = "Flat", Source = "MaterialOutput", }}, }}, }}, |
| 2094 | Blocker = Shape3D {{ Inputs = {{ ["SurfacePlaneInputs.Width"] = Input {{ Value = 0.8, }}, ["Transform3DOp.Translate.X"] = Input {{ Value = 0.4, }}, ["Transform3DOp.Translate.Z"] = Input {{ Value = 0, }}, MaterialInput = Input {{ SourceOp = "Flat", Source = "MaterialOutput", }}, }}, }}, |
| 2095 | Pt = LightPoint {{ Inputs = {{ ["Transform3DOp.Translate.X"] = Input {{ Value = 1.6, }}, ["Transform3DOp.Translate.Z"] = Input {{ Value = 2.0, }}, Intensity = Input {{ Value = 1, }}, ["ShadowLightInputs3D.ShadowsEnabled"] = Input {{ Value = 1, }}, ["ShadowLightInputs3D.ShadowDensity"] = Input {{ Value = 1.0, }}, }}, }}, |
| 2096 | Cam = Camera3D {{ Inputs = {{ ["Transform3DOp.Translate.Z"] = Input {{ Value = 4.5, }}, ApertureW = Input {{ Value = 1.0, }}, ApertureH = Input {{ Value = 1.0, }}, }}, }}, |
| 2097 | M = Merge3D {{ Inputs = {{ SceneInput1 = Input {{ SourceOp = "Recv", Source = "Output", }}, SceneInput2 = Input {{ SourceOp = "Blocker", Source = "Output", }}, SceneInput3 = Input {{ SourceOp = "Pt", Source = "Output", }}, SceneInput4 = Input {{ SourceOp = "Cam", Source = "Output", }}, }}, }}, |
| 2098 | R = Renderer3D {{ Inputs = {{ Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }}, RendererType = Input {{ Value = FuID {{ "RendererOpenGL" }}, }}, ["RendererOpenGL.LightingEnabled"] = Input {{ Value = {lighting}, }}, ["RendererOpenGL.ShadowsEnabled"] = Input {{ Value = {shadows}, }}, SceneInput = Input {{ SourceOp = "M", Source = "Output", }}, }}, }}, |
| 2099 | }} }}"# |
| 2100 | ); |
| 2101 | let comp = Comp::from_fusion_str(&src).expect("parse shadow comp"); |
| 2102 | let mut eng = Engine::new_headless().ok()?; |
| 2103 | let id = comp.find_node("R").expect("R"); |
| 2104 | let (tex, _) = eng.evaluate(&comp, id, 0.0); |
| 2105 | eng.readback_rgba(&tex).ok() |
| 2106 | }; |
| 2107 | let (Some(unlit), Some(no_shad), Some(with_shad)) = (render_gl(0, 0), render_gl(1, 0), render_gl(1, 1)) else { |
| 2108 | return; |
| 2109 | }; |
| 2110 | // With LightingEnabled=0 under RendererOpenGL, receiver is pure flat white. |
| 2111 | let px = |buf: &[u8], x: usize, y: usize| buf[(y * 64 + x) * 4]; |
| 2112 | assert_eq!(px(&unlit, 8, 32), 255); |
| 2113 | // Blocker at (0,0,0) casts a shadow onto Recv (Z=-2) to the left of center when viewed from X=1.8. |
| 2114 | let dark_pixels = |buf: &[u8]| (0..64 * 64).filter(|&i| buf[i * 4 + 3] > 200 && buf[i * 4] < 40).count(); |
| 2115 | assert!(dark_pixels(&with_shad) > dark_pixels(&no_shad) + 15, "shadows should darken receiver: with={} vs without={}", dark_pixels(&with_shad), dark_pixels(&no_shad)); |
| 2116 | } |
| 2117 | |
| 2118 | #[test] |
| 2119 | fn transparent_textured_casters_cast_geometry_shadow() { |
| 2120 | let dark_receiver_pixels = |card_alpha: u8, shadows: u8| -> Option<usize> { |
| 2121 | let src = format!( |
| 2122 | r#"Composition {{ CurrentTime = 0, RenderRange = {{ 0, 1 }}, GlobalRange = {{ 0, 1 }}, Tools = ordered() {{ |
| 2123 | Flat = MtlBlinn {{ Inputs = {{ ["Specular.Intensity"] = Input {{ Value = 0, }}, }}, }}, |
| 2124 | Bg = Background {{ Inputs = {{ Width = Input {{ Value = 8, }}, Height = Input {{ Value = 8, }}, TopLeftRed = Input {{ Value = 1, }}, TopLeftAlpha = Input {{ Value = {card_alpha}, }}, }}, }}, |
| 2125 | Tex = Texture2DOperator {{ Inputs = {{ Input = Input {{ SourceOp = "Bg", Source = "Output", }}, }}, }}, |
| 2126 | Recv = Shape3D {{ Inputs = {{ ["SurfacePlaneInputs.Width"] = Input {{ Value = 8, }}, ["Transform3DOp.Translate.Z"] = Input {{ Value = -2, }}, MaterialInput = Input {{ SourceOp = "Flat", Source = "MaterialOutput", }}, }}, }}, |
| 2127 | Card = ImagePlane3D {{ Inputs = {{ ["Transform3DOp.Translate.X"] = Input {{ Value = 0.4, }}, MaterialInput = Input {{ SourceOp = "Tex", Source = "MaterialOutput", }}, }}, }}, |
| 2128 | Pt = LightPoint {{ Inputs = {{ ["Transform3DOp.Translate.X"] = Input {{ Value = 1.6, }}, ["Transform3DOp.Translate.Z"] = Input {{ Value = 2.0, }}, ["ShadowLightInputs3D.ShadowsEnabled"] = Input {{ Value = 1, }}, ["ShadowLightInputs3D.ShadowDensity"] = Input {{ Value = 1.0, }}, }}, }}, |
| 2129 | Cam = Camera3D {{ Inputs = {{ ["Transform3DOp.Translate.Z"] = Input {{ Value = 4.5, }}, ApertureW = Input {{ Value = 1.0, }}, ApertureH = Input {{ Value = 1.0, }}, }}, }}, |
| 2130 | M = Merge3D {{ Inputs = {{ SceneInput1 = Input {{ SourceOp = "Recv", Source = "Output", }}, SceneInput2 = Input {{ SourceOp = "Card", Source = "Output", }}, SceneInput3 = Input {{ SourceOp = "Pt", Source = "Output", }}, SceneInput4 = Input {{ SourceOp = "Cam", Source = "Output", }}, }}, }}, |
| 2131 | R = Renderer3D {{ Inputs = {{ Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }}, RendererType = Input {{ Value = FuID {{ "RendererOpenGL" }}, }}, ["RendererOpenGL.LightingEnabled"] = Input {{ Value = 1, }}, ["RendererOpenGL.ShadowsEnabled"] = Input {{ Value = {shadows}, }}, SceneInput = Input {{ SourceOp = "M", Source = "Output", }}, }}, }}, |
| 2132 | }} }}"# |
| 2133 | ); |
| 2134 | let comp = Comp::from_fusion_str(&src).expect("parse shadow comp"); |
| 2135 | let mut eng = Engine::new_headless().ok()?; |
| 2136 | let (tex, _) = eng.evaluate(&comp, comp.find_node("R").expect("R"), 0.0); |
| 2137 | let buf = eng.readback_rgba(&tex).ok()?; |
| 2138 | Some((0..64 * 64).filter(|&i| buf[i * 4 + 3] > 200 && buf[i * 4] < 40).count()) |
| 2139 | }; |
| 2140 | let (Some(opaque), Some(clear), Some(off)) = (dark_receiver_pixels(255, 1), dark_receiver_pixels(0, 1), dark_receiver_pixels(0, 0)) else { |
| 2141 | return; |
| 2142 | }; |
| 2143 | assert!(opaque > off + 15, "opaque card must shadow: {opaque} vs {off}"); |
| 2144 | assert!(clear > off + 15, "RendererOpenGL casts geometry shadows regardless of texture alpha: {clear} vs {off}"); |
| 2145 | } |
| 2146 | |
| 2147 | #[test] |
| 2148 | fn multi_light_point_shadows_both_cast() { |
| 2149 | let render_multi = |shadows: u8| -> Option<Vec<u8>> { |
| 2150 | let src = format!( |
| 2151 | r#"Composition {{ CurrentTime = 0, RenderRange = {{ 0, 1 }}, GlobalRange = {{ 0, 1 }}, Tools = ordered() {{ |
| 2152 | Flat = MtlBlinn {{ Inputs = {{ ["Specular.Intensity"] = Input {{ Value = 0, }}, }}, }}, |
| 2153 | Recv = Shape3D {{ Inputs = {{ ["SurfacePlaneInputs.Width"] = Input {{ Value = 8, }}, ["Transform3DOp.Translate.Z"] = Input {{ Value = -2, }}, MaterialInput = Input {{ SourceOp = "Flat", Source = "MaterialOutput", }}, }}, }}, |
| 2154 | Card = ImagePlane3D {{ Inputs = {{ ["Transform3DOp.Translate.X"] = Input {{ Value = 0.0, }}, MaterialInput = Input {{ SourceOp = "Flat", Source = "MaterialOutput", }}, }}, }}, |
| 2155 | PtL = LightPoint {{ Inputs = {{ ["Transform3DOp.Translate.X"] = Input {{ Value = -1.4, }}, ["Transform3DOp.Translate.Z"] = Input {{ Value = 2.0, }}, Intensity = Input {{ Value = 0.45, }}, ["ShadowLightInputs3D.ShadowsEnabled"] = Input {{ Value = 1, }}, ["ShadowLightInputs3D.ShadowDensity"] = Input {{ Value = 1.0, }}, }}, }}, |
| 2156 | PtR = LightPoint {{ Inputs = {{ ["Transform3DOp.Translate.X"] = Input {{ Value = 1.4, }}, ["Transform3DOp.Translate.Z"] = Input {{ Value = 2.0, }}, Intensity = Input {{ Value = 0.45, }}, ["ShadowLightInputs3D.ShadowsEnabled"] = Input {{ Value = 1, }}, ["ShadowLightInputs3D.ShadowDensity"] = Input {{ Value = 1.0, }}, }}, }}, |
| 2157 | Cam = Camera3D {{ Inputs = {{ ["Transform3DOp.Translate.Z"] = Input {{ Value = 4.5, }}, ApertureW = Input {{ Value = 1.0, }}, ApertureH = Input {{ Value = 1.0, }}, }}, }}, |
| 2158 | M = Merge3D {{ Inputs = {{ SceneInput1 = Input {{ SourceOp = "Recv", Source = "Output", }}, SceneInput2 = Input {{ SourceOp = "Card", Source = "Output", }}, SceneInput3 = Input {{ SourceOp = "PtL", Source = "Output", }}, SceneInput4 = Input {{ SourceOp = "PtR", Source = "Output", }}, SceneInput5 = Input {{ SourceOp = "Cam", Source = "Output", }}, }}, }}, |
| 2159 | R = Renderer3D {{ Inputs = {{ Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }}, RendererType = Input {{ Value = FuID {{ "RendererOpenGL" }}, }}, ["RendererOpenGL.LightingEnabled"] = Input {{ Value = 1, }}, ["RendererOpenGL.ShadowsEnabled"] = Input {{ Value = {shadows}, }}, SceneInput = Input {{ SourceOp = "M", Source = "Output", }}, }}, }}, |
| 2160 | }} }}"# |
| 2161 | ); |
| 2162 | let comp = Comp::from_fusion_str(&src).expect("parse multi-light shadow comp"); |
| 2163 | let mut eng = Engine::new_headless().ok()?; |
| 2164 | let (tex, _) = eng.evaluate(&comp, comp.find_node("R").expect("R"), 0.0); |
| 2165 | eng.readback_rgba(&tex).ok() |
| 2166 | }; |
| 2167 | let (Some(no_s), Some(with_s)) = (render_multi(0), render_multi(1)) else { |
| 2168 | return; |
| 2169 | }; |
| 2170 | // PtL casts shadow to the right (x=46, y=32), PtR casts shadow to the left (x=18, y=32). |
| 2171 | let px = |buf: &[u8], x: usize| u16::from(buf[(32 * 64 + x) * 4]); |
| 2172 | assert!(px(&with_s, 18) + 40 < px(&no_s, 18), "right light shadow missing on left: {} vs {}", px(&with_s, 18), px(&no_s, 18)); |
| 2173 | assert!(px(&with_s, 46) + 40 < px(&no_s, 46), "left light shadow missing on right: {} vs {}", px(&with_s, 46), px(&no_s, 46)); |
| 2174 | } |
| 2175 | |
| 2176 | #[test] |
| 2177 | fn shadow_caster_and_receiver_flags_are_honored() { |
| 2178 | let dark_receiver_pixels = |blocker_extra: &str, receiver_extra: &str, flat_extra: &str| -> Option<usize> { |
| 2179 | let src = format!( |
| 2180 | r#"Composition {{ CurrentTime = 0, RenderRange = {{ 0, 1 }}, GlobalRange = {{ 0, 1 }}, Tools = ordered() {{ |
| 2181 | Flat = MtlBlinn {{ Inputs = {{ ["Specular.Intensity"] = Input {{ Value = 0, }}, {flat_extra} }}, }}, |
| 2182 | Recv = Shape3D {{ Inputs = {{ ["SurfacePlaneInputs.Width"] = Input {{ Value = 8, }}, ["Transform3DOp.Translate.Z"] = Input {{ Value = -2, }}, {receiver_extra} }}, }}, |
| 2183 | Blocker = Shape3D {{ Inputs = {{ ["SurfacePlaneInputs.Width"] = Input {{ Value = 0.8, }}, ["Transform3DOp.Translate.X"] = Input {{ Value = 0.4, }}, MaterialInput = Input {{ SourceOp = "Flat", Source = "MaterialOutput", }}, {blocker_extra} }}, }}, |
| 2184 | Pt = LightPoint {{ Inputs = {{ ["Transform3DOp.Translate.X"] = Input {{ Value = 1.6, }}, ["Transform3DOp.Translate.Z"] = Input {{ Value = 2.0, }}, ["ShadowLightInputs3D.ShadowsEnabled"] = Input {{ Value = 1, }}, ["ShadowLightInputs3D.ShadowDensity"] = Input {{ Value = 1.0, }}, }}, }}, |
| 2185 | Cam = Camera3D {{ Inputs = {{ ["Transform3DOp.Translate.Z"] = Input {{ Value = 4.5, }}, ApertureW = Input {{ Value = 1.0, }}, ApertureH = Input {{ Value = 1.0, }}, }}, }}, |
| 2186 | M = Merge3D {{ Inputs = {{ SceneInput1 = Input {{ SourceOp = "Recv", Source = "Output", }}, SceneInput2 = Input {{ SourceOp = "Blocker", Source = "Output", }}, SceneInput3 = Input {{ SourceOp = "Pt", Source = "Output", }}, SceneInput4 = Input {{ SourceOp = "Cam", Source = "Output", }}, }}, }}, |
| 2187 | R = Renderer3D {{ Inputs = {{ Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }}, RendererType = Input {{ Value = FuID {{ "RendererOpenGL" }}, }}, ["RendererOpenGL.LightingEnabled"] = Input {{ Value = 1, }}, ["RendererOpenGL.ShadowsEnabled"] = Input {{ Value = 1, }}, SceneInput = Input {{ SourceOp = "M", Source = "Output", }}, }}, }}, |
| 2188 | }} }}"# |
| 2189 | ); |
| 2190 | let comp = Comp::from_fusion_str(&src).expect("parse shadow comp"); |
| 2191 | let mut eng = Engine::new_headless().ok()?; |
| 2192 | let (tex, _) = eng.evaluate(&comp, comp.find_node("R").expect("R"), 0.0); |
| 2193 | let buf = eng.readback_rgba(&tex).ok()?; |
| 2194 | Some((0..64 * 64).filter(|&i| buf[i * 4 + 3] > 200 && buf[i * 4] < 40).count()) |
| 2195 | }; |
| 2196 | let no_caster = r#"["SurfacePlaneInputs.Lighting.IsShadowCaster"] = Input { Value = 0, },"#; |
| 2197 | let no_receive = r#"["MtlStdInputs.ReceivesShadows"] = Input { Value = 0, },"#; |
| 2198 | let flat_receiver = r#"MaterialInput = Input { SourceOp = "Flat", Source = "MaterialOutput", },"#; |
| 2199 | let (Some(shadowed), Some(uncast), Some(unreceived), Some(unreceived_by_material)) = ( |
| 2200 | dark_receiver_pixels("", "", ""), |
| 2201 | dark_receiver_pixels(no_caster, "", ""), |
| 2202 | dark_receiver_pixels("", no_receive, ""), |
| 2203 | dark_receiver_pixels("", flat_receiver, "ReceivesShadows = Input { Value = 0, },"), |
| 2204 | ) else { |
| 2205 | return; |
| 2206 | }; |
| 2207 | assert!(shadowed > uncast + 15, "baseline must shadow: {shadowed} vs {uncast}"); |
| 2208 | assert!(shadowed > unreceived + 15, "receiver opt-out must remove the shadow: {shadowed} vs {unreceived}"); |
| 2209 | assert_eq!(uncast, unreceived, "either flag alone removes the shadow entirely"); |
| 2210 | assert_eq!(uncast, unreceived_by_material, "a material shader owns the receiver flag"); |
| 2211 | } |
| 2212 | |
| 2213 | #[test] |
| 2214 | fn shadow_vram_bytes_tracks_pool_and_clear_resets_both_caches() { |
| 2215 | let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle()); |
| 2216 | let Ok(adapter) = pollster::block_on(instance.request_adapter(&Default::default())) else { return }; |
| 2217 | let Ok((device, queue)) = pollster::block_on(adapter.request_device(&Default::default())) else { return }; |
| 2218 | let renderer = Scene3DRenderer::new(&device); |
| 2219 | assert_eq!(renderer.shadow_vram_bytes(), 0); |
| 2220 | |
| 2221 | let _ = renderer.get_or_build_text3d_mesh(42, || vec![Vertex3D { pos: [0.0; 3], normal: [0.0, 0.0, 1.0], uv: [0.0; 2] }]); |
| 2222 | assert_eq!(lock_or_recover(&renderer.text3d_mesh_cache).entries.len(), 1); |
| 2223 | |
| 2224 | let tex = device.create_texture(&wgpu::TextureDescriptor { |
| 2225 | label: None, |
| 2226 | size: wgpu::Extent3d { width: 8, height: 8, depth_or_array_layers: 1 }, |
| 2227 | mip_level_count: 1, |
| 2228 | sample_count: 1, |
| 2229 | dimension: wgpu::TextureDimension::D2, |
| 2230 | format: wgpu::TextureFormat::Rgba8Unorm, |
| 2231 | usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::RENDER_ATTACHMENT, |
| 2232 | view_formats: &[], |
| 2233 | }); |
| 2234 | let dst = CachedTexture::from_texture(tex, [8, 8], 0); |
| 2235 | let dummy = dst.clone(); |
| 2236 | let mut lights = SceneLights::default(); |
| 2237 | lights.points.push(PointLight { |
| 2238 | pos: [0.0, 0.0, 2.0], |
| 2239 | color: [1.0, 1.0, 1.0], |
| 2240 | decay_type: 0.0, |
| 2241 | decay_rate: 0.0, |
| 2242 | shadow_density: Some(1.0), |
| 2243 | }); |
| 2244 | let mut enc = device.create_command_encoder(&Default::default()); |
| 2245 | renderer.render_meshes( |
| 2246 | &device, |
| 2247 | &queue, |
| 2248 | &mut enc, |
| 2249 | &dst, |
| 2250 | &dummy, |
| 2251 | mat4_identity(), |
| 2252 | mat4_identity(), |
| 2253 | [0.0, 0.0, 5.0], |
| 2254 | 100.0, |
| 2255 | lights, |
| 2256 | true, |
| 2257 | true, |
| 2258 | &[], |
| 2259 | ); |
| 2260 | queue.submit(Some(enc.finish())); |
| 2261 | |
| 2262 | // 1 shadow light = 6 R32Float layers + 1 Depth32Float texture = 7 * 1024 * 1024 * 4 bytes. |
| 2263 | let expected = u64::from(SHADOW_MAP_SIZE) * u64::from(SHADOW_MAP_SIZE) * 4 * 7; |
| 2264 | assert_eq!(renderer.shadow_vram_bytes(), expected); |
| 2265 | |
| 2266 | renderer.clear_shadow_targets(); |
| 2267 | assert_eq!(renderer.shadow_vram_bytes(), 0); |
| 2268 | assert_eq!(renderer.depth_vram_bytes(), 0); |
| 2269 | assert_eq!(lock_or_recover(&renderer.text3d_mesh_cache).entries.len(), 0); |
| 2270 | } |
| 2271 | |
| 2272 | #[test] |
| 2273 | fn depth_targets_are_reused_by_size_and_cleared_on_clear_targets() { |
| 2274 | let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle()); |
| 2275 | let Ok(adapter) = pollster::block_on(instance.request_adapter(&Default::default())) else { return }; |
| 2276 | let Ok((device, queue)) = pollster::block_on(adapter.request_device(&Default::default())) else { return }; |
| 2277 | let renderer = Scene3DRenderer::new(&device); |
| 2278 | let make_tex = |w, h| { |
| 2279 | CachedTexture::from_texture( |
| 2280 | device.create_texture(&wgpu::TextureDescriptor { |
| 2281 | label: None, |
| 2282 | size: wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 }, |
| 2283 | mip_level_count: 1, |
| 2284 | sample_count: 1, |
| 2285 | dimension: wgpu::TextureDimension::D2, |
| 2286 | format: wgpu::TextureFormat::Rgba8Unorm, |
| 2287 | usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::RENDER_ATTACHMENT, |
| 2288 | view_formats: &[], |
| 2289 | }), |
| 2290 | [w, h], |
| 2291 | 0, |
| 2292 | ) |
| 2293 | }; |
| 2294 | let dst_a = make_tex(16, 16); |
| 2295 | let dst_b = make_tex(32, 16); |
| 2296 | let dummy = make_tex(8, 8); |
| 2297 | let render_empty = |dst: &CachedTexture| { |
| 2298 | let mut enc = device.create_command_encoder(&Default::default()); |
| 2299 | renderer.render_meshes( |
| 2300 | &device, |
| 2301 | &queue, |
| 2302 | &mut enc, |
| 2303 | dst, |
| 2304 | &dummy, |
| 2305 | mat4_identity(), |
| 2306 | mat4_identity(), |
| 2307 | [0.0, 0.0, 5.0], |
| 2308 | 100.0, |
| 2309 | SceneLights::default(), |
| 2310 | false, |
| 2311 | false, |
| 2312 | &[], |
| 2313 | ); |
| 2314 | queue.submit(Some(enc.finish())); |
| 2315 | }; |
| 2316 | |
| 2317 | render_empty(&dst_a); |
| 2318 | assert_eq!(lock_or_recover(&renderer.depth_targets).entries.len(), 1); |
| 2319 | assert_eq!(renderer.depth_vram_bytes(), 16 * 16 * 4); |
| 2320 | |
| 2321 | render_empty(&dst_a); |
| 2322 | assert_eq!(lock_or_recover(&renderer.depth_targets).entries.len(), 1); |
| 2323 | assert_eq!(renderer.depth_vram_bytes(), 16 * 16 * 4); |
| 2324 | |
| 2325 | render_empty(&dst_b); |
| 2326 | assert_eq!(lock_or_recover(&renderer.depth_targets).entries.len(), 2); |
| 2327 | assert_eq!(renderer.depth_vram_bytes(), (16 * 16 + 32 * 16) * 4); |
| 2328 | |
| 2329 | renderer.clear_targets(); |
| 2330 | assert_eq!(lock_or_recover(&renderer.depth_targets).entries.len(), 0); |
| 2331 | assert_eq!(renderer.depth_vram_bytes(), 0); |
| 2332 | } |
| 2333 | |
| 2334 | #[test] |
| 2335 | fn gpu_mesh_buffer_cache_hits_bounds_lru_and_clears_on_bust() { |
| 2336 | let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle()); |
| 2337 | let Ok(adapter) = pollster::block_on(instance.request_adapter(&Default::default())) else { return }; |
| 2338 | let Ok((device, queue)) = pollster::block_on(adapter.request_device(&Default::default())) else { return }; |
| 2339 | let renderer = Scene3DRenderer::new(&device); |
| 2340 | let make_tex = |w, h| { |
| 2341 | CachedTexture::from_texture( |
| 2342 | device.create_texture(&wgpu::TextureDescriptor { |
| 2343 | label: None, |
| 2344 | size: wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 }, |
| 2345 | mip_level_count: 1, |
| 2346 | sample_count: 1, |
| 2347 | dimension: wgpu::TextureDimension::D2, |
| 2348 | format: wgpu::TextureFormat::Rgba8Unorm, |
| 2349 | usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::RENDER_ATTACHMENT, |
| 2350 | view_formats: &[], |
| 2351 | }), |
| 2352 | [w, h], |
| 2353 | 0, |
| 2354 | ) |
| 2355 | }; |
| 2356 | let (dst, dummy) = (make_tex(16, 16), make_tex(8, 8)); |
| 2357 | let make_custom = |z_offset: f32| -> DrawMesh { |
| 2358 | let tri = vec![ |
| 2359 | Vertex3D { pos: [-0.5, -0.5, z_offset], normal: [0.0, 0.0, 1.0], uv: [0.0, 1.0] }, |
| 2360 | Vertex3D { pos: [0.5, -0.5, z_offset], normal: [0.0, 0.0, 1.0], uv: [1.0, 1.0] }, |
| 2361 | Vertex3D { pos: [0.0, 0.5, z_offset], normal: [0.0, 0.0, 1.0], uv: [0.5, 0.0] }, |
| 2362 | ]; |
| 2363 | DrawMesh { |
| 2364 | world: mat4_identity(), |
| 2365 | shape: ShapeKind::CustomMesh(Arc::new(tri)), |
| 2366 | custom_mesh_key: None, |
| 2367 | tex: None, |
| 2368 | bump_tex: None, |
| 2369 | diffuse_col: [1.0; 4], |
| 2370 | specular_col: [1.0; 3], |
| 2371 | specular_intensity: 0.0, |
| 2372 | specular_exponent: 50.0, |
| 2373 | affected_by_lights: false, |
| 2374 | casts_shadow: false, |
| 2375 | receives_shadows: false, |
| 2376 | flip_normals: false, |
| 2377 | displace: None, |
| 2378 | } |
| 2379 | }; |
| 2380 | let render_one = |m: DrawMesh| { |
| 2381 | let mut enc = device.create_command_encoder(&Default::default()); |
| 2382 | renderer.render_meshes( |
| 2383 | &device, |
| 2384 | &queue, |
| 2385 | &mut enc, |
| 2386 | &dst, |
| 2387 | &dummy, |
| 2388 | mat4_identity(), |
| 2389 | mat4_identity(), |
| 2390 | [0.0, 0.0, 5.0], |
| 2391 | 100.0, |
| 2392 | SceneLights::default(), |
| 2393 | false, |
| 2394 | false, |
| 2395 | &[m], |
| 2396 | ); |
| 2397 | queue.submit(Some(enc.finish())); |
| 2398 | }; |
| 2399 | |
| 2400 | // 1. Repeated identical frames hit both GPU mesh cache and uniform cache, even across Arc drop/reallocation. |
| 2401 | render_one(make_custom(0.0)); |
| 2402 | let vram_1 = renderer.mesh_vram_bytes(); |
| 2403 | assert_eq!(renderer.gpu_mesh_count(), 1); |
| 2404 | assert!(vram_1 > 0); |
| 2405 | assert_eq!(lock_or_recover(&renderer.uniform_cache).entries.len(), 1); |
| 2406 | |
| 2407 | render_one(make_custom(0.0)); |
| 2408 | assert_eq!(renderer.gpu_mesh_count(), 1, "rebuilt identical Arc must hit content-keyed mesh cache"); |
| 2409 | assert_eq!(renderer.mesh_vram_bytes(), vram_1); |
| 2410 | assert_eq!(lock_or_recover(&renderer.uniform_cache).entries.len(), 1, "identical uniform bytes reuse cached buffer"); |
| 2411 | |
| 2412 | // 2. Eviction stays strictly bounded by MAX_CACHED_MESH_BUFFERS (128). |
| 2413 | for i in 1..=(MAX_CACHED_MESH_BUFFERS + 20) { |
| 2414 | render_one(make_custom(i as f32 * 0.01)); |
| 2415 | } |
| 2416 | assert_eq!(renderer.gpu_mesh_count(), MAX_CACHED_MESH_BUFFERS); |
| 2417 | assert!(lock_or_recover(&renderer.uniform_cache).entries.len() <= UNIFORM_CACHE_CAP); |
| 2418 | |
| 2419 | // 3. clear_shadow_targets() (called by bust_gpu_cache) releases all cached GPU mesh and uniform buffers. |
| 2420 | renderer.clear_shadow_targets(); |
| 2421 | assert_eq!(renderer.gpu_mesh_count(), 0); |
| 2422 | assert_eq!(renderer.mesh_vram_bytes(), 0); |
| 2423 | assert_eq!(lock_or_recover(&renderer.uniform_cache).entries.len(), 0); |
| 2424 | } |
| 2425 | |
| 2426 | #[test] |
| 2427 | fn cube3d_semi_transparent_front_face_reveals_opaque_interior_faces() { |
| 2428 | let src = r#"Composition { CurrentTime = 0, RenderRange = { 0, 1 }, GlobalRange = { 0, 1 }, Tools = ordered() { |
| 2429 | Bg = Background { Inputs = { Width = Input { Value = 8, }, Height = Input { Value = 8, }, TopLeftRed = Input { Value = 0, }, TopLeftGreen = Input { Value = 0, }, TopLeftBlue = Input { Value = 0, }, TopLeftAlpha = Input { Value = 0, }, }, }, |
| 2430 | Tex = Texture2DOperator { Inputs = { Input = Input { SourceOp = "Bg", Source = "Output", }, }, }, |
| 2431 | Cube = Cube3D { Inputs = { FrontMaterialInput = Input { SourceOp = "Tex", Source = "MaterialOutput", }, }, }, |
| 2432 | Cam = Camera3D { Inputs = { ["Transform3DOp.Translate.Z"] = Input { Value = 3.0, }, }, }, |
| 2433 | Amb = LightAmbient { Inputs = { Intensity = Input { Value = 0.25, }, }, }, |
| 2434 | M = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = "Cube", Source = "Output", }, SceneInput2 = Input { SourceOp = "Amb", Source = "Output", }, SceneInput3 = Input { SourceOp = "Cam", Source = "Output", }, }, }, |
| 2435 | R = Renderer3D { Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 64, }, ["RendererSoftware.LightingEnabled"] = Input { Value = 1, }, SceneInput = Input { SourceOp = "M", Source = "Output", }, }, }, |
| 2436 | } }"#; |
| 2437 | let comp = Comp::from_fusion_str(src).expect("parse Cube3D comp"); |
| 2438 | let Ok(mut eng) = Engine::new_headless() else { return }; |
| 2439 | let (tex, _) = eng.evaluate(&comp, comp.find_node("R").expect("R"), 0.0); |
| 2440 | let px = eng.readback_rgba(&tex).expect("readback Cube3D"); |
| 2441 | let c = center(&px); |
| 2442 | assert_eq!(c[3], 255, "transparent front face must reveal opaque back face inside cube: {c:?}"); |
| 2443 | assert!((c[0] as i32 - 64).abs() <= 2, "back face should show 0.25 ambient gray: {c:?}"); |
| 2444 | } |
| 2445 | |
| 2446 | #[test] |
| 2447 | fn diffuse_color_alpha_modulates_alpha_without_scaling_rgb() { |
| 2448 | let render_mat = |extra: &str| -> Option<[u8; 4]> { |
| 2449 | let scene = format!( |
| 2450 | r#"Mtl = MtlBlinn {{ Inputs = {{ ["Diffuse.Color.Red"] = Input {{ Value = 0.8, }}, ["Diffuse.Color.Green"] = Input {{ Value = 0.4, }}, ["Diffuse.Color.Blue"] = Input {{ Value = 0.2, }}, ["Specular.Intensity"] = Input {{ Value = 0, }}, {extra} }}, }}, |
| 2451 | P = Shape3D {{ Inputs = {{ ["SurfacePlaneInputs.Width"] = Input {{ Value = 4, }}, MaterialInput = Input {{ SourceOp = "Mtl", Source = "MaterialOutput", }}, }}, }}, |
| 2452 | L = LightDirectional {{ }}, |
| 2453 | M = Merge3D {{ Inputs = {{ SceneInput1 = Input {{ SourceOp = "P", Source = "Output", }}, SceneInput2 = Input {{ SourceOp = "L", Source = "Output", }}, SceneInput3 = Input {{ SourceOp = "Cam", Source = "Output", }}, }}, }},"# |
| 2454 | ); |
| 2455 | render(true, &scene).map(|px| center(&px)) |
| 2456 | }; |
| 2457 | let Some(ca) = render_mat(r#"["Diffuse.Color.Alpha"] = Input { Value = 0.5, },"#) else { return }; |
| 2458 | let Some(op) = render_mat(r#"["Diffuse.Opacity"] = Input { Value = 0.5, },"#) else { return }; |
| 2459 | assert!((ca[0] as i32 - 204).abs() <= 2 && (ca[1] as i32 - 102).abs() <= 2 && (ca[2] as i32 - 51).abs() <= 2, "Diffuse.Color.Alpha must not attenuate RGB: {ca:?}"); |
| 2460 | assert!((ca[3] as i32 - 128).abs() <= 2, "Diffuse.Color.Alpha must set output alpha: {ca:?}"); |
| 2461 | assert!((op[0] as i32 - 102).abs() <= 2 && (op[1] as i32 - 51).abs() <= 2 && (op[2] as i32 - 25).abs() <= 2, "Diffuse.Opacity scales premultiplied RGB: {op:?}"); |
| 2462 | assert!((op[3] as i32 - 128).abs() <= 2, "Diffuse.Opacity sets output alpha: {op:?}"); |
| 2463 | } |
| 2464 | |
| 2465 | #[test] |
| 2466 | fn cook_torrance_refractive_index_drives_fresnel_specular() { |
| 2467 | let render_ct = |ri: f32, do_fresnel: u8| -> Option<u8> { |
| 2468 | let scene = format!( |
| 2469 | r#"Mtl = MtlCookTorrance {{ Inputs = {{ ["Diffuse.Color.Red"] = Input {{ Value = 0, }}, ["Diffuse.Color.Green"] = Input {{ Value = 0, }}, ["Diffuse.Color.Blue"] = Input {{ Value = 0, }}, ["Specular.Roughness"] = Input {{ Value = 0.6, }}, ["Specular.RefractiveIndex"] = Input {{ Value = {ri}, }}, ["Specular.DoFresnel"] = Input {{ Value = {do_fresnel}, }}, }}, }}, |
| 2470 | P = Shape3D {{ Inputs = {{ ["SurfacePlaneInputs.Width"] = Input {{ Value = 4, }}, MaterialInput = Input {{ SourceOp = "Mtl", Source = "MaterialOutput", }}, }}, }}, |
| 2471 | L = LightDirectional {{ }}, |
| 2472 | M = Merge3D {{ Inputs = {{ SceneInput1 = Input {{ SourceOp = "P", Source = "Output", }}, SceneInput2 = Input {{ SourceOp = "L", Source = "Output", }}, SceneInput3 = Input {{ SourceOp = "Cam", Source = "Output", }}, }}, }},"# |
| 2473 | ); |
| 2474 | render(true, &scene).map(|px| center(&px)[0]) |
| 2475 | }; |
| 2476 | let (Some(n1), Some(n2), Some(n3), Some(no_f)) = ( |
| 2477 | render_ct(1.0, 1), |
| 2478 | render_ct(2.0, 1), |
| 2479 | render_ct(2.9, 1), |
| 2480 | render_ct(2.0, 0), |
| 2481 | ) else { |
| 2482 | return; |
| 2483 | }; |
| 2484 | assert_eq!(n1, 0, "RI=1.0 has zero Fresnel reflectance"); |
| 2485 | assert!(n2 > n1 && n3 > n2, "higher RI must strengthen specular: n1={n1} n2={n2} n3={n3}"); |
| 2486 | assert!(no_f > n3, "DoFresnel=0 disables Fresnel attenuation: no_f={no_f} vs n3={n3}"); |
| 2487 | } |
| 2488 | |
| 2489 | #[test] |
| 2490 | fn unlit_premultiplied_emissive_texture_preserves_rgb() { |
| 2491 | let scene = r#"EmissiveBg = Background { Inputs = { Width = Input { Value = 8, }, Height = Input { Value = 8, }, TopLeftRed = Input { Value = 0.8, }, TopLeftGreen = Input { Value = 0.4, }, TopLeftBlue = Input { Value = 0.2, }, TopLeftAlpha = Input { Value = 0.5, }, }, }, |
| 2492 | EmissiveTex = Texture2DOperator { Inputs = { Input = Input { SourceOp = "EmissiveBg", Source = "Output", }, }, }, |
| 2493 | Card = ImagePlane3D { Inputs = { ["Transform3DOp.Scale.X"] = Input { Value = 4, }, MaterialInput = Input { SourceOp = "EmissiveTex", Source = "MaterialOutput", }, }, }, |
| 2494 | M = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = "Card", Source = "Output", }, SceneInput2 = Input { SourceOp = "Cam", Source = "Output", }, }, },"#; |
| 2495 | let Some(px) = render(true, scene) else { return }; |
| 2496 | let c = center(&px); |
| 2497 | assert!((c[0] as i32 - 204).abs() <= 2 && (c[1] as i32 - 102).abs() <= 2 && (c[2] as i32 - 51).abs() <= 2, "premultiplied emissive RGB must not be attenuated by alpha: {c:?}"); |
| 2498 | assert!((c[3] as i32 - 128).abs() <= 2, "alpha must remain 0.5: {c:?}"); |
| 2499 | } |
| 2500 | |
| 2501 | #[test] |
| 2502 | fn lru_byte_cap_evicts_least_recently_used_entries() { |
| 2503 | let mut lru: Lru<u8, (u8, u64)> = Lru::with_byte_cap(16, 100, |v| v.1); |
| 2504 | lru.get_or_insert_with(1, || (1, 40)); |
| 2505 | lru.get_or_insert_with(2, || (2, 40)); |
| 2506 | assert_eq!(lru.total_bytes, 80); |
| 2507 | // Touch key 1 so key 2 becomes LRU before inserting key 3 (80 + 40 > 100). |
| 2508 | assert_eq!(lru.get(1), Some((1, 40))); |
| 2509 | lru.get_or_insert_with(3, || (3, 40)); |
| 2510 | assert_eq!(lru.total_bytes, 80); |
| 2511 | assert_eq!(lru.get(2), None, "LRU key 2 must be evicted to satisfy byte cap"); |
| 2512 | assert_eq!(lru.get(1), Some((1, 40))); |
| 2513 | assert_eq!(lru.get(3), Some((3, 40))); |
| 2514 | // Entries larger than max_bytes are returned without busting the cache or exceeding max_bytes. |
| 2515 | let oversized = lru.get_or_insert_with(4, || (4, 150)); |
| 2516 | assert_eq!(oversized, (4, 150)); |
| 2517 | assert_eq!(lru.total_bytes, 80); |
| 2518 | assert_eq!(lru.entries.len(), 2); |
| 2519 | } |
| 2520 | |
| 2521 | #[test] |
| 2522 | fn mesh_and_uniform_byte_caps_evict_lru_and_track_uniform_vram_bytes() { |
| 2523 | let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle()); |
| 2524 | let Ok(adapter) = pollster::block_on(instance.request_adapter(&Default::default())) else { return }; |
| 2525 | let Ok((device, queue)) = pollster::block_on(adapter.request_device(&Default::default())) else { return }; |
| 2526 | let renderer = Scene3DRenderer::new(&device); |
| 2527 | let make_tex = |w, h| { |
| 2528 | CachedTexture::from_texture( |
| 2529 | device.create_texture(&wgpu::TextureDescriptor { |
| 2530 | label: None, |
| 2531 | size: wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 }, |
| 2532 | mip_level_count: 1, |
| 2533 | sample_count: 1, |
| 2534 | dimension: wgpu::TextureDimension::D2, |
| 2535 | format: wgpu::TextureFormat::Rgba8Unorm, |
| 2536 | usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::RENDER_ATTACHMENT, |
| 2537 | view_formats: &[], |
| 2538 | }), |
| 2539 | [w, h], |
| 2540 | 0, |
| 2541 | ) |
| 2542 | }; |
| 2543 | let (dst, dummy) = (make_tex(16, 16), make_tex(8, 8)); |
| 2544 | let make_mesh = |n_tris: usize, z: f32| -> DrawMesh { |
| 2545 | let mut verts = Vec::with_capacity(n_tris * 3); |
| 2546 | for i in 0..n_tris { |
| 2547 | let off = i as f32 * 0.001 + z; |
| 2548 | verts.push(Vertex3D { pos: [-0.5, -0.5, off], normal: [0.0, 0.0, 1.0], uv: [0.0, 1.0] }); |
| 2549 | verts.push(Vertex3D { pos: [0.5, -0.5, off], normal: [0.0, 0.0, 1.0], uv: [1.0, 1.0] }); |
| 2550 | verts.push(Vertex3D { pos: [0.0, 0.5, off], normal: [0.0, 0.0, 1.0], uv: [0.5, 0.0] }); |
| 2551 | } |
| 2552 | DrawMesh { |
| 2553 | world: mat4_identity(), |
| 2554 | shape: ShapeKind::CustomMesh(Arc::new(verts)), |
| 2555 | custom_mesh_key: None, |
| 2556 | tex: None, |
| 2557 | bump_tex: None, |
| 2558 | diffuse_col: [1.0; 4], |
| 2559 | specular_col: [1.0; 3], |
| 2560 | specular_intensity: 0.0, |
| 2561 | specular_exponent: 50.0, |
| 2562 | affected_by_lights: false, |
| 2563 | casts_shadow: false, |
| 2564 | receives_shadows: false, |
| 2565 | flip_normals: false, |
| 2566 | displace: None, |
| 2567 | } |
| 2568 | }; |
| 2569 | let render_one = |m: DrawMesh| { |
| 2570 | let mut enc = device.create_command_encoder(&Default::default()); |
| 2571 | renderer.render_meshes( |
| 2572 | &device, |
| 2573 | &queue, |
| 2574 | &mut enc, |
| 2575 | &dst, |
| 2576 | &dummy, |
| 2577 | mat4_identity(), |
| 2578 | mat4_identity(), |
| 2579 | [0.0, 0.0, 5.0], |
| 2580 | 100.0, |
| 2581 | SceneLights::default(), |
| 2582 | false, |
| 2583 | false, |
| 2584 | &[m], |
| 2585 | ); |
| 2586 | queue.submit(Some(enc.finish())); |
| 2587 | }; |
| 2588 | |
| 2589 | // Render one mesh and verify default caps and uniform_vram_bytes tracking. |
| 2590 | render_one(make_mesh(20, 0.0)); |
| 2591 | let single_mesh_bytes = renderer.mesh_vram_bytes(); |
| 2592 | let single_uni_bytes = renderer.uniform_vram_bytes(); |
| 2593 | assert!(single_mesh_bytes > 0 && single_mesh_bytes <= MAX_CACHED_MESH_BYTES); |
| 2594 | assert!(single_uni_bytes > 0 && single_uni_bytes <= MAX_CACHED_UNIFORM_BYTES); |
| 2595 | |
| 2596 | // Enforce tight byte caps (< 2 entries) and confirm LRU eviction caps both pools. |
| 2597 | lock_or_recover(&renderer.meshes).max_bytes = single_mesh_bytes + single_mesh_bytes / 2; |
| 2598 | lock_or_recover(&renderer.uniform_cache).max_bytes = single_uni_bytes + single_uni_bytes / 2; |
| 2599 | |
| 2600 | render_one(make_mesh(20, 1.0)); |
| 2601 | assert_eq!(renderer.gpu_mesh_count(), 1, "mesh byte cap must evict LRU mesh"); |
| 2602 | assert_eq!(renderer.mesh_vram_bytes(), single_mesh_bytes); |
| 2603 | assert_eq!(lock_or_recover(&renderer.uniform_cache).entries.len(), 1, "uniform byte cap must evict LRU uniform"); |
| 2604 | assert_eq!(renderer.uniform_vram_bytes(), single_uni_bytes); |
| 2605 | |
| 2606 | renderer.clear_shadow_targets(); |
| 2607 | assert_eq!(renderer.uniform_vram_bytes(), 0); |
| 2608 | assert_eq!(renderer.mesh_vram_bytes(), 0); |
| 2609 | } |
| 2610 | |
| 2611 | fn readback_aux_tex(eng: &Engine, aux: &AuxChannelTex, bpp: u32) -> Vec<u8> { |
| 2612 | let [w, h] = aux.size; |
| 2613 | let unpadded_bpr = w * bpp; |
| 2614 | let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT; |
| 2615 | let padded_bpr = unpadded_bpr.div_ceil(align) * align; |
| 2616 | let buf = eng.device().create_buffer(&wgpu::BufferDescriptor { |
| 2617 | label: Some("readback-aux"), |
| 2618 | size: u64::from(padded_bpr) * u64::from(h), |
| 2619 | usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, |
| 2620 | mapped_at_creation: false, |
| 2621 | }); |
| 2622 | let mut enc = eng.device().create_command_encoder(&Default::default()); |
| 2623 | enc.copy_texture_to_buffer( |
| 2624 | aux.texture.as_image_copy(), |
| 2625 | wgpu::TexelCopyBufferInfo { |
| 2626 | buffer: &buf, |
| 2627 | layout: wgpu::TexelCopyBufferLayout { |
| 2628 | offset: 0, |
| 2629 | bytes_per_row: Some(padded_bpr), |
| 2630 | rows_per_image: Some(h), |
| 2631 | }, |
| 2632 | }, |
| 2633 | wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 }, |
| 2634 | ); |
| 2635 | eng.queue().submit(Some(enc.finish())); |
| 2636 | let slice = buf.slice(..); |
| 2637 | let (tx, rx) = std::sync::mpsc::channel(); |
| 2638 | slice.map_async(wgpu::MapMode::Read, move |res| { |
| 2639 | let _ = tx.send(res); |
| 2640 | }); |
| 2641 | eng.device() |
| 2642 | .poll(wgpu::PollType::Wait { |
| 2643 | submission_index: None, |
| 2644 | timeout: Some(std::time::Duration::from_secs(10)), |
| 2645 | }) |
| 2646 | .unwrap(); |
| 2647 | rx.recv().unwrap().unwrap(); |
| 2648 | let data = slice.get_mapped_range().unwrap(); |
| 2649 | let mut out = Vec::with_capacity((unpadded_bpr * h) as usize); |
| 2650 | for y in 0..h as usize { |
| 2651 | let start = y * padded_bpr as usize; |
| 2652 | out.extend_from_slice(&data[start..start + unpadded_bpr as usize]); |
| 2653 | } |
| 2654 | drop(data); |
| 2655 | buf.unmap(); |
| 2656 | out |
| 2657 | } |
| 2658 | |
| 2659 | #[test] |
| 2660 | fn renderer3d_z_and_normal_aux_channels_match_fusion_convention() { |
| 2661 | let make_comp = |proj_type: &str, ch_z: u8, ch_n: u8| -> Comp { |
| 2662 | let src = format!( |
| 2663 | r#"Composition {{ CurrentTime = 0, RenderRange = {{ 0, 1 }}, GlobalRange = {{ 0, 1 }}, Tools = ordered() {{ |
| 2664 | Flat = MtlBlinn {{ Inputs = {{ ["Specular.Intensity"] = Input {{ Value = 0, }}, }}, }}, |
| 2665 | P = Shape3D {{ Inputs = {{ |
| 2666 | ["SurfacePlaneInputs.Width"] = Input {{ Value = 0.5, }}, |
| 2667 | ["SurfacePlaneInputs.Height"] = Input {{ Value = 0.5, }}, |
| 2668 | ["Transform3DOp.Translate.Z"] = Input {{ Value = -1.0, }}, |
| 2669 | MaterialInput = Input {{ SourceOp = "Flat", Source = "MaterialOutput", }}, |
| 2670 | }}, }}, |
| 2671 | Cam = Camera3D {{ Inputs = {{ |
| 2672 | ProjectionType = Input {{ Value = FuID {{ "{proj_type}" }}, }}, |
| 2673 | ["Transform3DOp.Translate.Z"] = Input {{ Value = 2.0, }}, |
| 2674 | ApertureW = Input {{ Value = 1.0, }}, |
| 2675 | ApertureH = Input {{ Value = 1.0, }}, |
| 2676 | }}, }}, |
| 2677 | M = Merge3D {{ Inputs = {{ |
| 2678 | SceneInput1 = Input {{ SourceOp = "P", Source = "Output", }}, |
| 2679 | SceneInput2 = Input {{ SourceOp = "Cam", Source = "Output", }}, |
| 2680 | }}, }}, |
| 2681 | R = Renderer3D {{ Inputs = {{ |
| 2682 | Width = Input {{ Value = 64, }}, |
| 2683 | Height = Input {{ Value = 64, }}, |
| 2684 | ["RendererSoftware.Channels.Z"] = Input {{ Value = {ch_z}, }}, |
| 2685 | ["RendererSoftware.Channels.Normal"] = Input {{ Value = {ch_n}, }}, |
| 2686 | SceneInput = Input {{ SourceOp = "M", Source = "Output", }}, |
| 2687 | }}, }}, |
| 2688 | }} }}"# |
| 2689 | ); |
| 2690 | Comp::from_fusion_str(&src).expect("parse Z/Normal comp") |
| 2691 | }; |
| 2692 | |
| 2693 | let Ok(mut eng) = Engine::new_headless() else { return }; |
| 2694 | |
| 2695 | // 1. Both channels disabled -> zero aux allocation (`aux == None`). |
| 2696 | let comp_off = make_comp("Perspective", 0, 0); |
| 2697 | let (tex_off, _) = eng.evaluate(&comp_off, comp_off.find_node("R").unwrap(), 0.0); |
| 2698 | assert!(tex_off.aux.is_none(), "aux must stay None when Z and Normal are disabled"); |
| 2699 | |
| 2700 | // 2. Perspective & Orthographic cameras both yield Z = -3.0 at center and EMPTY_Z_SENTINEL at corner. |
| 2701 | for proj_type in ["Perspective", "Orthographic"] { |
| 2702 | let comp = make_comp(proj_type, 1, 1); |
| 2703 | let r_id = comp.find_node("R").unwrap(); |
| 2704 | let (tex, _) = eng.evaluate(&comp, r_id, 0.0); |
| 2705 | let aux = tex.aux.as_ref().expect("aux channels must be attached"); |
| 2706 | let z_tex = aux.z.as_ref().expect("aux.z must be present"); |
| 2707 | let n_tex = aux.normal.as_ref().expect("aux.normal must be present"); |
| 2708 | assert_eq!(z_tex.format, wgpu::TextureFormat::R32Float); |
| 2709 | assert_eq!(n_tex.format, wgpu::TextureFormat::Rgba16Float); |
| 2710 | |
| 2711 | let z_bytes = readback_aux_tex(&eng, z_tex, 4); |
| 2712 | let z_vals: &[f32] = bytemuck::cast_slice(&z_bytes); |
| 2713 | let center_z = z_vals[32 * 64 + 32]; |
| 2714 | let corner_z = z_vals[0]; |
| 2715 | assert!( |
| 2716 | (center_z - (-3.0)).abs() <= 1e-3, |
| 2717 | "{proj_type} center Z should be -3.0, got {center_z}" |
| 2718 | ); |
| 2719 | assert_eq!( |
| 2720 | corner_z, EMPTY_Z_SENTINEL, |
| 2721 | "{proj_type} empty corner Z should be EMPTY_Z_SENTINEL, got {corner_z}" |
| 2722 | ); |
| 2723 | |
| 2724 | let n_bytes = readback_aux_tex(&eng, n_tex, 8); |
| 2725 | let read_n = |x: usize, y: usize| -> [f32; 4] { |
| 2726 | let off = (y * 64 + x) * 8; |
| 2727 | [ |
| 2728 | ::exr::prelude::f16::from_bits(u16::from_le_bytes([n_bytes[off], n_bytes[off + 1]])).to_f32(), |
| 2729 | ::exr::prelude::f16::from_bits(u16::from_le_bytes([n_bytes[off + 2], n_bytes[off + 3]])).to_f32(), |
| 2730 | ::exr::prelude::f16::from_bits(u16::from_le_bytes([n_bytes[off + 4], n_bytes[off + 5]])).to_f32(), |
| 2731 | ::exr::prelude::f16::from_bits(u16::from_le_bytes([n_bytes[off + 6], n_bytes[off + 7]])).to_f32(), |
| 2732 | ] |
| 2733 | }; |
| 2734 | let cn = read_n(32, 32); |
| 2735 | let kn = read_n(0, 0); |
| 2736 | assert!( |
| 2737 | cn[0].abs() <= 1e-3 && cn[1].abs() <= 1e-3 && (cn[2] - 1.0).abs() <= 1e-3 && cn[3].abs() <= 1e-3, |
| 2738 | "{proj_type} center normal should be (0,0,1,0), got {cn:?}" |
| 2739 | ); |
| 2740 | assert_eq!(kn, [0.0, 0.0, 0.0, 0.0], "{proj_type} corner normal should be zero"); |
| 2741 | } |
| 2742 | |
| 2743 | // 3. Toggling Channels.Z on an existing comp updates cache key cleanly. |
| 2744 | let (tex_cached_off, _) = eng.evaluate(&make_comp("Perspective", 0, 0), comp_off.find_node("R").unwrap(), 0.0); |
| 2745 | assert!(tex_cached_off.aux.is_none()); |
| 2746 | } |
| 2747 | |
| 2748 | #[test] |
| 2749 | fn mtl_ward_anisotropic_spread_u_vs_v_stretches_specular_highlight() { |
| 2750 | let Ok(mut eng) = Engine::new_headless() else { return }; |
| 2751 | let mut render = |su: f32, sv: f32| -> Vec<u8> { |
| 2752 | let src = format!( |
| 2753 | r#"Composition {{ CurrentTime = 0, RenderRange = {{ 0, 1 }}, GlobalRange = {{ 0, 1 }}, Tools = ordered() {{ |
| 2754 | Ward = MtlWard {{ Inputs = {{ |
| 2755 | ["Diffuse.Color.Red"] = Input {{ Value = 0.0, }}, |
| 2756 | ["Diffuse.Color.Green"] = Input {{ Value = 0.0, }}, |
| 2757 | ["Diffuse.Color.Blue"] = Input {{ Value = 0.0, }}, |
| 2758 | ["Specular.Intensity"] = Input {{ Value = 1.0, }}, |
| 2759 | ["Specular.SpreadU"] = Input {{ Value = {su}, }}, |
| 2760 | ["Specular.SpreadV"] = Input {{ Value = {sv}, }}, |
| 2761 | }}, }}, |
| 2762 | S = Shape3D {{ Inputs = {{ |
| 2763 | Shape = Input {{ Value = FuID {{ "SurfaceSphereInputs" }}, }}, |
| 2764 | ["SurfaceSphereInputs.Radius"] = Input {{ Value = 1.0, }}, |
| 2765 | MaterialInput = Input {{ SourceOp = "Ward", Source = "MaterialOutput", }}, |
| 2766 | }}, }}, |
| 2767 | L = LightDirectional {{ Inputs = {{ Intensity = Input {{ Value = 2.0, }}, }}, }}, |
| 2768 | Cam = Camera3D {{ Inputs = {{ ["Transform3DOp.Translate.Z"] = Input {{ Value = 5.5, }}, }}, }}, |
| 2769 | M = Merge3D {{ Inputs = {{ |
| 2770 | SceneInput1 = Input {{ SourceOp = "S", Source = "Output", }}, |
| 2771 | SceneInput2 = Input {{ SourceOp = "L", Source = "Output", }}, |
| 2772 | SceneInput3 = Input {{ SourceOp = "Cam", Source = "Output", }}, |
| 2773 | }}, }}, |
| 2774 | R = Renderer3D {{ Inputs = {{ |
| 2775 | Width = Input {{ Value = 64, }}, |
| 2776 | Height = Input {{ Value = 64, }}, |
| 2777 | ["RendererSoftware.LightingEnabled"] = Input {{ Value = 1, }}, |
| 2778 | SceneInput = Input {{ SourceOp = "M", Source = "Output", }}, |
| 2779 | }}, }}, |
| 2780 | }} }}"# |
| 2781 | ); |
| 2782 | let comp = Comp::from_fusion_str(&src).unwrap(); |
| 2783 | let (tex, _) = eng.evaluate(&comp, comp.find_node("R").unwrap(), 0.0); |
| 2784 | eng.readback_rgba(&tex).unwrap() |
| 2785 | }; |
| 2786 | let horiz = render(0.45, 0.05); |
| 2787 | let vert = render(0.05, 0.45); |
| 2788 | let px_r = |buf: &[u8], x: usize, y: usize| buf[(y * 64 + x) * 4] as f32; |
| 2789 | // Sample off-center along horizontal vs vertical axes from sphere center (32, 32). |
| 2790 | let h_horiz = px_r(&horiz, 40, 32) + px_r(&horiz, 24, 32); |
| 2791 | let h_vert = px_r(&horiz, 32, 40) + px_r(&horiz, 32, 24); |
| 2792 | let v_horiz = px_r(&vert, 40, 32) + px_r(&vert, 24, 32); |
| 2793 | let v_vert = px_r(&vert, 32, 40) + px_r(&vert, 32, 24); |
| 2794 | assert!(h_horiz > h_vert + 5.0, "wide SpreadU should stretch highlight horizontally: h={h_horiz} v={h_vert}"); |
| 2795 | assert!(v_vert > v_horiz + 5.0, "wide SpreadV should stretch highlight vertically: h={v_horiz} v={v_vert}"); |
| 2796 | } |
| 2797 | |
| 2798 | #[test] |
| 2799 | fn spheremap_and_mtl_reflect_fresnel_and_constant_strength() { |
| 2800 | let Ok(mut eng) = Engine::new_headless() else { return }; |
| 2801 | let mut render_reflect = |strength_var: u8, face_on: f32, glancing: f32, rot_y: f32| -> Vec<u8> { |
| 2802 | let src = format!( |
| 2803 | r#"Composition {{ CurrentTime = 0, RenderRange = {{ 0, 1 }}, GlobalRange = {{ 0, 1 }}, Tools = ordered() {{ |
| 2804 | Env = Background {{ Inputs = {{ |
| 2805 | Width = Input {{ Value = 64, }}, |
| 2806 | Height = Input {{ Value = 32, }}, |
| 2807 | Type = Input {{ Value = FuID {{ "Horizontal" }}, }}, |
| 2808 | TopLeftRed = Input {{ Value = 1.0, }}, TopLeftGreen = Input {{ Value = 0.0, }}, TopLeftBlue = Input {{ Value = 0.0, }}, |
| 2809 | TopRightRed = Input {{ Value = 0.0, }}, TopRightGreen = Input {{ Value = 0.0, }}, TopRightBlue = Input {{ Value = 1.0, }}, |
| 2810 | }}, }}, |
| 2811 | SMap = SphereMap {{ Inputs = {{ |
| 2812 | Image = Input {{ SourceOp = "Env", Source = "Output", }}, |
| 2813 | ["Rotate.Y"] = Input {{ Value = {rot_y}, }}, |
| 2814 | }}, }}, |
| 2815 | Dark = MtlBlinn {{ Inputs = {{ |
| 2816 | ["Diffuse.Color.Red"] = Input {{ Value = 0.0, }}, |
| 2817 | ["Diffuse.Color.Green"] = Input {{ Value = 0.0, }}, |
| 2818 | ["Diffuse.Color.Blue"] = Input {{ Value = 0.0, }}, |
| 2819 | ["Specular.Intensity"] = Input {{ Value = 0.0, }}, |
| 2820 | }}, }}, |
| 2821 | Refl = MtlReflect {{ Inputs = {{ |
| 2822 | BackgroundMaterial = Input {{ SourceOp = "Dark", Source = "MaterialOutput", }}, |
| 2823 | ["Reflection.Color.Material"] = Input {{ SourceOp = "SMap", Source = "MaterialOutput", }}, |
| 2824 | ["Reflection.StrengthVariability"] = Input {{ Value = {strength_var}, }}, |
| 2825 | ["Reflection.ConstantStrength"] = Input {{ Value = 1.0, }}, |
| 2826 | ["Reflection.FaceOnStrength"] = Input {{ Value = {face_on}, }}, |
| 2827 | ["Reflection.GlancingStrength"] = Input {{ Value = {glancing}, }}, |
| 2828 | ["Reflection.Falloff"] = Input {{ Value = 2.0, }}, |
| 2829 | }}, }}, |
| 2830 | S = Shape3D {{ Inputs = {{ |
| 2831 | Shape = Input {{ Value = FuID {{ "SurfaceSphereInputs" }}, }}, |
| 2832 | ["SurfaceSphereInputs.Radius"] = Input {{ Value = 1.0, }}, |
| 2833 | MaterialInput = Input {{ SourceOp = "Refl", Source = "MaterialOutput", }}, |
| 2834 | }}, }}, |
| 2835 | Cam = Camera3D {{ Inputs = {{ ["Transform3DOp.Translate.Z"] = Input {{ Value = 6.0, }}, }}, }}, |
| 2836 | M = Merge3D {{ Inputs = {{ |
| 2837 | SceneInput1 = Input {{ SourceOp = "S", Source = "Output", }}, |
| 2838 | SceneInput2 = Input {{ SourceOp = "Cam", Source = "Output", }}, |
| 2839 | }}, }}, |
| 2840 | R = Renderer3D {{ Inputs = {{ |
| 2841 | Width = Input {{ Value = 64, }}, |
| 2842 | Height = Input {{ Value = 64, }}, |
| 2843 | SceneInput = Input {{ SourceOp = "M", Source = "Output", }}, |
| 2844 | }}, }}, |
| 2845 | }} }}"# |
| 2846 | ); |
| 2847 | let comp = Comp::from_fusion_str(&src).unwrap(); |
| 2848 | let (tex, _) = eng.evaluate(&comp, comp.find_node("R").unwrap(), 0.0); |
| 2849 | eng.readback_rgba(&tex).unwrap() |
| 2850 | }; |
| 2851 | let luma = |buf: &[u8], x: usize, y: usize| { |
| 2852 | let o = (y * 64 + x) * 4; |
| 2853 | buf[o] as f32 + buf[o + 1] as f32 + buf[o + 2] as f32 |
| 2854 | }; |
| 2855 | // Fresnel By-Angle: face-on center is dark (0), grazing rim is bright! |
| 2856 | let fresnel = render_reflect(1, 0.0, 1.0, 0.0); |
| 2857 | let center_l = luma(&fresnel, 32, 32); |
| 2858 | let rim_l = (46..=56).map(|x| luma(&fresnel, x, 32)).fold(0.0_f32, f32::max); |
| 2859 | assert!(center_l < 15.0 && rim_l > 80.0, "Fresnel center={center_l} rim={rim_l}"); |
| 2860 | |
| 2861 | // Constant full reflection reflects at center too, and rotating SphereMap by 180° shifts colors. |
| 2862 | let c0 = render_reflect(0, 0.0, 1.0, 0.0); |
| 2863 | let c180 = render_reflect(0, 0.0, 1.0, 180.0); |
| 2864 | assert!(luma(&c0, 32, 32) > 80.0, "constant reflection should brighten center"); |
| 2865 | let diff: f32 = (0..64 * 64 * 4).map(|i| (c0[i] as f32 - c180[i] as f32).abs()).sum::<f32>() / (64.0 * 64.0 * 4.0); |
| 2866 | assert!(diff > 5.0, "rotating SphereMap by 180 deg must change reflected image, diff={diff}"); |
| 2867 | } |
| 2868 | |
| 2869 | #[test] |
| 2870 | fn mtl_chan_bool_inverts_swaps_and_combines_channels() { |
| 2871 | let Ok(mut eng) = Engine::new_headless() else { return }; |
| 2872 | let src = r#"Composition { CurrentTime = 0, RenderRange = { 0, 1 }, GlobalRange = { 0, 1 }, Tools = ordered() { |
| 2873 | Bg = MtlBlinn { Inputs = { |
| 2874 | ["Diffuse.Color.Red"] = Input { Value = 0.0, }, |
| 2875 | ["Diffuse.Color.Green"] = Input { Value = 1.0, }, |
| 2876 | ["Diffuse.Color.Blue"] = Input { Value = 0.0, }, |
| 2877 | ReceivesLighting = Input { Value = 0, }, |
| 2878 | }, }, |
| 2879 | Fg = MtlBlinn { Inputs = { |
| 2880 | ["Diffuse.Color.Red"] = Input { Value = 0.0, }, |
| 2881 | ["Diffuse.Color.Green"] = Input { Value = 0.0, }, |
| 2882 | ["Diffuse.Color.Blue"] = Input { Value = 0.5, }, |
| 2883 | ReceivesLighting = Input { Value = 0, }, |
| 2884 | }, }, |
| 2885 | CB = MtlChanBool { Inputs = { |
| 2886 | BackgroundMaterial = Input { SourceOp = "Bg", Source = "MaterialOutput", }, |
| 2887 | ForegroundMaterial = Input { SourceOp = "Fg", Source = "MaterialOutput", }, |
| 2888 | -- R = BG.G (5 -> 1.0), G = 1 - BG.G (op 2 -> 0.0), B = BG.B + FG.B (op 4 -> 0.5), A = White (9 -> 1.0) |
| 2889 | OperandAR = Input { Value = 5, }, OperationR = Input { Value = 0, }, |
| 2890 | OperandAG = Input { Value = 5, }, OperationG = Input { Value = 2, }, |
| 2891 | OperandAB = Input { Value = 6, }, OperationB = Input { Value = 4, }, OperandBB = Input { Value = 2, }, |
| 2892 | OperandAA = Input { Value = 9, }, OperationA = Input { Value = 0, }, |
| 2893 | }, }, |
| 2894 | P = Shape3D { Inputs = { |
| 2895 | ["SurfacePlaneInputs.Width"] = Input { Value = 2.0, }, |
| 2896 | MaterialInput = Input { SourceOp = "CB", Source = "MaterialOutput", }, |
| 2897 | }, }, |
| 2898 | Cam = Camera3D { Inputs = { ["Transform3DOp.Translate.Z"] = Input { Value = 2.0, }, }, }, |
| 2899 | M = Merge3D { Inputs = { |
| 2900 | SceneInput1 = Input { SourceOp = "P", Source = "Output", }, |
| 2901 | SceneInput2 = Input { SourceOp = "Cam", Source = "Output", }, |
| 2902 | }, }, |
| 2903 | R = Renderer3D { Inputs = { |
| 2904 | Width = Input { Value = 32, }, |
| 2905 | Height = Input { Value = 32, }, |
| 2906 | SceneInput = Input { SourceOp = "M", Source = "Output", }, |
| 2907 | }, }, |
| 2908 | } }"#; |
| 2909 | let comp = Comp::from_fusion_str(src).unwrap(); |
| 2910 | let (tex, _) = eng.evaluate(&comp, comp.find_node("R").unwrap(), 0.0); |
| 2911 | let px = eng.readback_rgba(&tex).unwrap(); |
| 2912 | let o = (16 * 32 + 16) * 4; |
| 2913 | let rgba = [px[o], px[o + 1], px[o + 2], px[o + 3]]; |
| 2914 | assert!(rgba[0] >= 250 && rgba[1] <= 5 && (rgba[2] as i32 - 128).abs() <= 4 && rgba[3] >= 250, "unexpected MtlChanBool pixel {rgba:?}"); |
| 2915 | } |
| 2916 | |
| 2917 | #[test] |
| 2918 | fn bender3d_and_replicate3d_render_end_to_end() { |
| 2919 | let Ok(mut eng) = Engine::new_headless() else { return }; |
| 2920 | let src = r#"Composition { CurrentTime = 0, RenderRange = { 0, 1 }, GlobalRange = { 0, 1 }, Tools = ordered() { |
| 2921 | Dest = Shape3D { Inputs = { |
| 2922 | ["SurfacePlaneInputs.Width"] = Input { Value = 1.6, }, |
| 2923 | ["SurfacePlaneInputs.SubdivisionWidth"] = Input { Value = 1, }, |
| 2924 | }, }, |
| 2925 | Dot = Shape3D { Inputs = { |
| 2926 | ["SurfacePlaneInputs.Width"] = Input { Value = 0.3, }, |
| 2927 | ["MtlStdInputs.Diffuse.Color.Red"] = Input { Value = 1.0, }, |
| 2928 | ["MtlStdInputs.Diffuse.Color.Green"] = Input { Value = 0.2, }, |
| 2929 | ["MtlStdInputs.Diffuse.Color.Blue"] = Input { Value = 0.0, }, |
| 2930 | ["MtlStdInputs.ReceivesLighting"] = Input { Value = 0, }, |
| 2931 | }, }, |
| 2932 | BentDot = Bender3D { Inputs = { |
| 2933 | SceneInput = Input { SourceOp = "Dot", Source = "Output", }, |
| 2934 | Bender = Input { Value = FuID { "Twist" }, }, |
| 2935 | Amount = Input { Value = 0.25, }, |
| 2936 | }, }, |
| 2937 | Rep = Replicate3D { Inputs = { |
| 2938 | Destination = Input { SourceOp = "Dest", Source = "Output", }, |
| 2939 | Input1 = Input { SourceOp = "BentDot", Source = "Output", }, |
| 2940 | }, }, |
| 2941 | Cam = Camera3D { Inputs = { ["Transform3DOp.Translate.Z"] = Input { Value = 4.5, }, }, }, |
| 2942 | M = Merge3D { Inputs = { |
| 2943 | SceneInput1 = Input { SourceOp = "Rep", Source = "Output", }, |
| 2944 | SceneInput2 = Input { SourceOp = "Cam", Source = "Output", }, |
| 2945 | }, }, |
| 2946 | R = Renderer3D { Inputs = { |
| 2947 | Width = Input { Value = 64, }, |
| 2948 | Height = Input { Value = 64, }, |
| 2949 | SceneInput = Input { SourceOp = "M", Source = "Output", }, |
| 2950 | }, }, |
| 2951 | } }"#; |
| 2952 | let comp = Comp::from_fusion_str(src).unwrap(); |
| 2953 | let (tex, _) = eng.evaluate(&comp, comp.find_node("R").unwrap(), 0.0); |
| 2954 | let px = eng.readback_rgba(&tex).unwrap(); |
| 2955 | // 4 corners of the destination plane should produce non-empty orange pixels, while center (32, 32) is empty! |
| 2956 | let center_a = px[(32 * 64 + 32) * 4 + 3]; |
| 2957 | let lit_pixels = px.chunks_exact(4).filter(|p| p[0] > 200 && p[3] > 200).count(); |
| 2958 | assert_eq!(center_a, 0, "center between 4 replicated corners should be transparent"); |
| 2959 | assert!(lit_pixels >= 40, "expected 4 replicated corner quads to render, got {lit_pixels} pixels"); |
| 2960 | } |
| 2961 | } |