authoravatarclover caruso<git@paperclover.net>2026-11-30 20:44:22-08:00
committeravatarclover caruso<git@paperclover.net>2026-11-30 20:54:09-08:00
log9c00057b07397a81c13f866dbc14fb0ae0d1399a
tree960700962a46e3c21a9775b778aa6faad9b5e9c6
parent9f6cd5fe8fd066b899ef73513343ff2e092bd205
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

Fix 3D normal matrix, scaled cameras, multi-dir lights, GPU mesh/FBX/optflow caching

- shader: transform normals by the cofactor of the model 3x3 (non-uniform scale) - collect: general mat4_inverse for camera views, numeric SceneInput order, every LightDirectional collected (4 shader slots) - scene3d: bounded LRU of GPU vertex/index buffers keyed by base shape - fbx: cache keyed by (path, mtime, obj, scale); the missing-file placeholder is never cached - optflow: LRU of 4 half-res flow fields keyed by frame pair so extra alphas only run the warp - eval/text_3d: use mat4_inverse and hash all directional lights Assisted-by: claude-sonnet-5.5

6 files changed, 489 insertions(+), 121 deletions(-)

crates/engine/src/eval/text_3d.rs+5-3
...@@ -534,7 +534,7 @@ impl Engine {...@@ -534,7 +534,7 @@ impl Engine {
534 );534 );
535535
536 let (view, proj, cam_pos) = if let Some(cam) = cameras.first() {536 let (view, proj, cam_pos) = if let Some(cam) = cameras.first() {
537 let v = crate::scene3d::mat4_inverse_rigid(cam.world);537 let v = crate::scene3d::mat4_inverse(cam.world);
538 let p = crate::scene3d::mat4_perspective_wgpu(cam.vfov_rad, aspect, cam.near, cam.far);538 let p = crate::scene3d::mat4_perspective_wgpu(cam.vfov_rad, aspect, cam.near, cam.far);
539 (v, p, [cam.world[12], cam.world[13], cam.world[14]])539 (v, p, [cam.world[12], cam.world[13], cam.world[14]])
540 } else {540 } else {
...@@ -550,8 +550,10 @@ impl Engine {...@@ -550,8 +550,10 @@ impl Engine {
550 hash_floats.extend_from_slice(&view_proj);550 hash_floats.extend_from_slice(&view_proj);
551 hash_floats.push(if lighting_enabled { 1.0 } else { 0.0 });551 hash_floats.push(if lighting_enabled { 1.0 } else { 0.0 });
552 hash_floats.extend_from_slice(&lights.ambient);552 hash_floats.extend_from_slice(&lights.ambient);
553 hash_floats.extend_from_slice(&lights.dir_to_light);553 for dl in &lights.dirs {
554 hash_floats.extend_from_slice(&lights.dir_color);554 hash_floats.extend_from_slice(&dl.to_light);
555 hash_floats.extend_from_slice(&dl.color);
556 }
555 for pl in &lights.points {557 for pl in &lights.points {
556 hash_floats.extend_from_slice(&pl.pos);558 hash_floats.extend_from_slice(&pl.pos);
557 hash_floats.extend_from_slice(&pl.color);559 hash_floats.extend_from_slice(&pl.color);
crates/engine/src/optflow.rs+102-31
...@@ -7,7 +7,7 @@ use model::BitDepth;...@@ -7,7 +7,7 @@ use model::BitDepth;
7use std::collections::HashMap;7use std::collections::HashMap;
8use std::collections::hash_map::DefaultHasher;8use std::collections::hash_map::DefaultHasher;
9use std::hash::{Hash, Hasher};9use std::hash::{Hash, Hasher};
10use std::sync::RwLock;10use std::sync::{Mutex, RwLock};
1111
12#[repr(C)]12#[repr(C)]
13#[derive(Clone, Copy, Pod, Zeroable)]13#[derive(Clone, Copy, Pod, Zeroable)]
...@@ -449,6 +449,12 @@ fn fs_warp_flow(in: VsOut) -> @location(0) vec4<f32> {...@@ -449,6 +449,12 @@ fn fs_warp_flow(in: VsOut) -> @location(0) vec4<f32> {
449}449}
450"#;450"#;
451451
452/// Cached flow fields kept per `OpticalFlowPipelines`; one entry is a single frame pair.
453const FLOW_CACHE_CAP: usize = 4;
454
455/// `(content_hash_a, content_hash_b, full-res size)`.
456type FlowKey = (u64, u64, [u32; 2]);
457
452/// Self-contained `wgpu` pipelines for GPU optical flow and motion-compensated frame interpolation.458/// Self-contained `wgpu` pipelines for GPU optical flow and motion-compensated frame interpolation.
453pub struct OpticalFlowPipelines {459pub struct OpticalFlowPipelines {
454 shader: wgpu::ShaderModule,460 shader: wgpu::ShaderModule,
...@@ -462,6 +468,8 @@ pub struct OpticalFlowPipelines {...@@ -462,6 +468,8 @@ pub struct OpticalFlowPipelines {
462 flow_smooth: wgpu::RenderPipeline,468 flow_smooth: wgpu::RenderPipeline,
463 blend_pipelines: RwLock<HashMap<wgpu::TextureFormat, wgpu::RenderPipeline>>,469 blend_pipelines: RwLock<HashMap<wgpu::TextureFormat, wgpu::RenderPipeline>>,
464 warp_pipelines: RwLock<HashMap<wgpu::TextureFormat, wgpu::RenderPipeline>>,470 warp_pipelines: RwLock<HashMap<wgpu::TextureFormat, wgpu::RenderPipeline>>,
471 /// Half-resolution flow fields, least recently used first.
472 flow_cache: Mutex<Vec<(FlowKey, wgpu::TextureView)>>,
465}473}
466474
467impl OpticalFlowPipelines {475impl OpticalFlowPipelines {
...@@ -547,6 +555,7 @@ impl OpticalFlowPipelines {...@@ -547,6 +555,7 @@ impl OpticalFlowPipelines {
547 flow_smooth,555 flow_smooth,
548 blend_pipelines: RwLock::new(HashMap::new()),556 blend_pipelines: RwLock::new(HashMap::new()),
549 warp_pipelines: RwLock::new(HashMap::new()),557 warp_pipelines: RwLock::new(HashMap::new()),
558 flow_cache: Mutex::new(Vec::new()),
550 }559 }
551 }560 }
552561
...@@ -694,11 +703,58 @@ impl OpticalFlowPipelines {...@@ -694,11 +703,58 @@ impl OpticalFlowPipelines {
694 let key = hash_interp(frame_a.content_hash, frame_b.content_hash, alpha, 2, target_format);703 let key = hash_interp(frame_a.content_hash, frame_b.content_hash, alpha, 2, target_format);
695 let dst = alloc_output_texture(device, frame_a, target_format, key);704 let dst = alloc_output_texture(device, frame_a, target_format, key);
696705
697 // Compute 4-level pyramid dimensions: full, 1/2, 1/4, 1/8
698 let s0 = [frame_a.size[0].max(1), frame_a.size[1].max(1)];706 let s0 = [frame_a.size[0].max(1), frame_a.size[1].max(1)];
699 let s1 = [s0[0].div_ceil(2).max(1), s0[1].div_ceil(2).max(1)];707 let s1 = half_size(s0);
700 let s2 = [s1[0].div_ceil(2).max(1), s1[1].div_ceil(2).max(1)];708 let flow_key = (frame_a.content_hash, frame_b.content_hash, s0);
701 let s3 = [s2[0].div_ceil(2).max(1), s2[1].div_ceil(2).max(1)];709 let cached = {
710 let mut cache = self.flow_cache.lock().unwrap();
711 cache.iter().position(|(k, _)| *k == flow_key).map(|i| {
712 let entry = cache.remove(i);
713 let view = entry.1.clone();
714 cache.push(entry);
715 view
716 })
717 };
718 let flow1_view = cached.unwrap_or_else(|| {
719 let view = self.compute_flow_field(device, queue, enc, frame_a, frame_b);
720 let mut cache = self.flow_cache.lock().unwrap();
721 if cache.len() >= FLOW_CACHE_CAP {
722 cache.remove(0);
723 }
724 cache.push((flow_key, view.clone()));
725 view
726 });
727
728 // Full-resolution bidirectional occlusion-aware warp & blend
729 let scale_1_to_0 = [
730 s0[0] as f32 / s1[0] as f32,
731 s0[1] as f32 / s1[1] as f32,
732 alpha.clamp(0.0, 1.0),
733 0.0,
734 ];
735 let guard = self.warp_pipelines.read().unwrap();
736 let pipe = guard.get(&target_format).unwrap();
737 self.run_pass(
738 device, queue, enc, pipe, "optflow-warp",
739 &frame_a.view, &frame_b.view, &flow1_view, &dst.view, s0, scale_1_to_0,
740 );
741 dst
742 }
743
744 /// Encodes the 4-level (full, 1/2, 1/4, 1/8) coarse-to-fine flow estimate and returns the
745 /// half-resolution flow field.
746 fn compute_flow_field(
747 &self,
748 device: &wgpu::Device,
749 queue: &wgpu::Queue,
750 enc: &mut wgpu::CommandEncoder,
751 frame_a: &CachedTexture,
752 frame_b: &CachedTexture,
753 ) -> wgpu::TextureView {
754 let s0 = [frame_a.size[0].max(1), frame_a.size[1].max(1)];
755 let s1 = half_size(s0);
756 let s2 = half_size(s1);
757 let s3 = half_size(s2);
702758
703 // 1. Build (luma, R-G, B-Y, alpha) feature pyramids for A and B759 // 1. Build (luma, R-G, B-Y, alpha) feature pyramids for A and B
704 let (fa0_tex, fa0_view) = alloc_f16_tex(device, s0, "optflow-fa0");760 let (fa0_tex, fa0_view) = alloc_f16_tex(device, s0, "optflow-fa0");
...@@ -784,41 +840,20 @@ impl OpticalFlowPipelines {...@@ -784,41 +840,20 @@ impl OpticalFlowPipelines {
784 &fa1_view, &fb1_view, &flow1_raw_view, &flow1_view, s1, [0.0; 4],840 &fa1_view, &fb1_view, &flow1_raw_view, &flow1_view, s1, [0.0; 4],
785 );841 );
786842
787 // 3. Full-resolution bidirectional occlusion-aware warp & blend
788 let scale_1_to_0 = [
789 s0[0] as f32 / s1[0] as f32,
790 s0[1] as f32 / s1[1] as f32,
791 alpha.clamp(0.0, 1.0),
792 0.0,
793 ];
794 {
795 let guard = self.warp_pipelines.read().unwrap();
796 let pipe = guard.get(&target_format).unwrap();
797 self.run_pass(
798 device,
799 queue,
800 enc,
801 pipe,
802 "optflow-warp",
803 &frame_a.view,
804 &frame_b.view,
805 &flow1_view,
806 &dst.view,
807 s0,
808 scale_1_to_0,
809 );
810 }
811
812 // Keep temporary textures alive until all passes are encoded into `enc`.843 // Keep temporary textures alive until all passes are encoded into `enc`.
813 drop((844 drop((
814 fa0_tex, fb0_tex, fa1_tex, fb1_tex, fa2_tex, fb2_tex, fa3_tex, fb3_tex,845 fa0_tex, fb0_tex, fa1_tex, fb1_tex, fa2_tex, fb2_tex, fa3_tex, fb3_tex,
815 flow3_raw_tex, flow3_tex, flow2_raw_tex, flow2_tex, flow1_raw_tex, flow1_tex,846 flow3_raw_tex, flow3_tex, flow2_raw_tex, flow2_tex, flow1_raw_tex, flow1_tex,
816 ));847 ));
817848
818 dst849 flow1_view
819 }850 }
820}851}
821852
853fn half_size(s: [u32; 2]) -> [u32; 2] {
854 [s[0].div_ceil(2).max(1), s[1].div_ceil(2).max(1)]
855}
856
822fn create_fullscreen_pipeline(857fn create_fullscreen_pipeline(
823 device: &wgpu::Device,858 device: &wgpu::Device,
824 shader: &wgpu::ShaderModule,859 shader: &wgpu::ShaderModule,
...@@ -1209,6 +1244,42 @@ mod tests {...@@ -1209,6 +1244,42 @@ mod tests {
1209 );1244 );
1210 }1245 }
12111246
1247 #[test]
1248 fn test_flow_field_is_cached_per_frame_pair_and_bounded() {
1249 let (device, queue) = create_headless_device();
1250 let cached = OpticalFlowPipelines::new(&device);
1251 let fresh = OpticalFlowPipelines::new(&device);
1252
1253 let (w, h) = (128u32, 72u32);
1254 let frame = |i: i32, hash: u64| {
1255 upload_rgba8(&device, &queue, w, h, &render_box_scene(w, h, 20 + 8 * i, 20), hash)
1256 };
1257 let (tex_a, tex_b) = (frame(0, 1), frame(1, 2));
1258 let fmt = wgpu::TextureFormat::Rgba8Unorm;
1259 let interp = |p: &OpticalFlowPipelines, a: &CachedTexture, b: &CachedTexture, alpha: f32| {
1260 let mut enc = device.create_command_encoder(&Default::default());
1261 let out = p.interpolate_flow(&device, &queue, &mut enc, a, b, alpha, fmt);
1262 queue.submit(Some(enc.finish()));
1263 readback_bytes(&device, &queue, &out, 4)
1264 };
1265
1266 let first = interp(&cached, &tex_a, &tex_b, 0.25);
1267 let field = cached.flow_cache.lock().unwrap()[0].1.clone();
1268 let second = interp(&cached, &tex_a, &tex_b, 0.75);
1269 {
1270 let cache = cached.flow_cache.lock().unwrap();
1271 assert_eq!(cache.len(), 1, "second alpha reuses the pair's flow field");
1272 assert!(cache[0].1 == field, "second alpha must hit the cached field texture");
1273 }
1274 assert_ne!(first, second, "alpha still drives the warp pass");
1275 assert_eq!(second, interp(&fresh, &tex_a, &tex_b, 0.75), "cached field matches a fresh computation");
1276
1277 for i in 2..8 {
1278 interp(&cached, &frame(i, 10 + i as u64), &frame(i + 1, 20 + i as u64), 0.5);
1279 }
1280 assert_eq!(cached.flow_cache.lock().unwrap().len(), FLOW_CACHE_CAP);
1281 }
1282
1212 #[test]1283 #[test]
1213 fn test_optflow_mismatched_sizes_and_rgba32float() {1284 fn test_optflow_mismatched_sizes_and_rgba32float() {
1214 let (device, queue) = create_headless_device();1285 let (device, queue) = create_headless_device();
crates/engine/src/scene3d/collect.rs+91-6
...@@ -2,10 +2,10 @@...@@ -2,10 +2,10 @@
22
3use super::fbx::load_mesh_cached;3use super::fbx::load_mesh_cached;
4use super::math::{4use super::math::{
5 mat4_identity, mat4_mul, mat4_rot_x, mat4_rot_y, mat4_rot_z, mat4_scale, mat4_translate,5 mat4_identity, mat4_inverse_rigid, mat4_mul, mat4_rot_x, mat4_rot_y, mat4_rot_z, mat4_scale, mat4_translate,
6};6};
7use super::{7use super::{
8 CameraInstance, Displace3DSpec, Mat4, MaterialFx, MeshInstance, PointLight, SceneLights,8 CameraInstance, DirLight, Displace3DSpec, Mat4, MaterialFx, MeshInstance, PointLight, SceneLights,
9 ShapeKind, SpecModel, SpotLight, Text3DSpec, UvAffine, CUBE_FACES,9 ShapeKind, SpecModel, SpotLight, Text3DSpec, UvAffine, CUBE_FACES,
10};10};
11use model::{Comp, ExprEngine, Node, NodeId};11use model::{Comp, ExprEngine, Node, NodeId};
...@@ -126,7 +126,8 @@ fn collect_scene_inner(...@@ -126,7 +126,8 @@ fn collect_scene_inner(
126 .keys()126 .keys()
127 .filter(|k| k.starts_with("SceneInput"))127 .filter(|k| k.starts_with("SceneInput"))
128 .collect();128 .collect();
129 input_names.sort();129 // `SceneInput2` precedes `SceneInput10`.
130 input_names.sort_by_cached_key(|k| (k["SceneInput".len()..].parse::<u32>().unwrap_or(0), k.to_string()));
130 for in_name in input_names {131 for in_name in input_names {
131 if let Some(src_id) = node.connected_node(in_name).and_then(|s| comp.find_node(s)) {132 if let Some(src_id) = node.connected_node(in_name).and_then(|s| comp.find_node(s)) {
132 collect_scene_inner(comp, src_id, time, expr, world, render_aspect, ovr, cameras, meshes, lights, visited, depth + 1);133 collect_scene_inner(comp, src_id, time, expr, world, render_aspect, ovr, cameras, meshes, lights, visited, depth + 1);
...@@ -270,9 +271,7 @@ fn collect_scene_inner(...@@ -270,9 +271,7 @@ fn collect_scene_inner(
270 let dy = world[9];271 let dy = world[9];
271 let dz = world[10];272 let dz = world[10];
272 let len = (dx * dx + dy * dy + dz * dz).sqrt().max(1e-5);273 let len = (dx * dx + dy * dy + dz * dz).sqrt().max(1e-5);
273 lights.dir_to_light = [dx / len, dy / len, dz / len];274 lights.dirs.push(DirLight { to_light: [dx / len, dy / len, dz / len], color });
274 lights.dir_color = color;
275 lights.has_dir = true;
276 }275 }
277 "LightPoint" => {276 "LightPoint" => {
278 let Some(color) = light_color(comp, node, time, expr) else { return };277 let Some(color) = light_color(comp, node, time, expr) else { return };
...@@ -729,6 +728,42 @@ fn eval_duplicate3d_step(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine)...@@ -729,6 +728,42 @@ fn eval_duplicate3d_step(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine)
729 mat4_mul(mat4_translate(tx, ty, tz), mat4_mul(rot, mat4_scale(sx, sy, sz)))728 mat4_mul(mat4_translate(tx, ty, tz), mat4_mul(rot, mat4_scale(sx, sy, sz)))
730}729}
731730
731/// General 4x4 inverse (Gauss-Jordan, partial pivoting); a singular `m` falls back to
732/// `mat4_inverse_rigid` so a degenerate camera scale never yields NaNs.
733pub fn mat4_inverse(m: Mat4) -> Mat4 {
734 let mut a = [[0.0_f64; 8]; 4];
735 for (r, row) in a.iter_mut().enumerate() {
736 for c in 0..4 {
737 row[c] = f64::from(m[c * 4 + r]);
738 }
739 row[4 + r] = 1.0;
740 }
741 for col in 0..4 {
742 let pivot = (col..4).max_by(|&i, &j| a[i][col].abs().total_cmp(&a[j][col].abs())).unwrap_or(col);
743 let invertible = a[pivot][col].abs() > 1e-12;
744 if !invertible {
745 return mat4_inverse_rigid(m);
746 }
747 a.swap(col, pivot);
748 let p = a[col][col];
749 a[col].iter_mut().for_each(|x| *x /= p);
750 let pivot_row = a[col];
751 for (r, row) in a.iter_mut().enumerate() {
752 if r != col {
753 let f = row[col];
754 row.iter_mut().zip(pivot_row).for_each(|(x, pv)| *x -= f * pv);
755 }
756 }
757 }
758 let mut out = [0.0_f32; 16];
759 for (r, row) in a.iter().enumerate() {
760 for c in 0..4 {
761 out[c * 4 + r] = row[4 + c] as f32;
762 }
763 }
764 out
765}
766
732pub fn eval_transform3d(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> Mat4 {767pub fn eval_transform3d(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> Mat4 {
733 let tx = comp.eval_number(node, "Transform3DOp.Translate.X", time, 0.0, expr) as f32;768 let tx = comp.eval_number(node, "Transform3DOp.Translate.X", time, 0.0, expr) as f32;
734 let ty = comp.eval_number(node, "Transform3DOp.Translate.Y", time, 0.0, expr) as f32;769 let ty = comp.eval_number(node, "Transform3DOp.Translate.Y", time, 0.0, expr) as f32;
...@@ -1183,4 +1218,54 @@ mod tests {...@@ -1183,4 +1218,54 @@ mod tests {
1183 assert_eq!(meshes.len(), 1);1218 assert_eq!(meshes.len(), 1);
1184 assert!(matches!(meshes[0].shape.base_shape(), ShapeKind::Plane { .. }));1219 assert!(matches!(meshes[0].shape.base_shape(), ShapeKind::Plane { .. }));
1185 }1220 }
1221
1222 #[test]
1223 fn scene_inputs_are_visited_in_numeric_order() {
1224 let plane = |name: &str, x: u32| format!(r#"{name} = Shape3D {{ Inputs = {{ ["Transform3DOp.Translate.X"] = Input {{ Value = {x}, }}, }}, }},"#);
1225 let src = comp_src(&format!(
1226 r#"{} {} {}
1227 M = Merge3D {{ Inputs = {{ SceneInput10 = Input {{ SourceOp = "C", Source = "Output", }}, SceneInput2 = Input {{ SourceOp = "B", Source = "Output", }}, SceneInput1 = Input {{ SourceOp = "A", Source = "Output", }}, }}, }},"#,
1228 plane("A", 1),
1229 plane("B", 2),
1230 plane("C", 10),
1231 ));
1232 let (_, meshes, _) = collect(&src, "M");
1233 let xs: Vec<f32> = meshes.iter().map(|m| m.world[12]).collect();
1234 assert_eq!(xs, [1.0, 2.0, 10.0]);
1235 }
1236
1237 #[test]
1238 fn every_directional_light_is_collected_with_its_own_direction_and_color() {
1239 let src = comp_src(
1240 r#"Front = LightDirectional { Inputs = { Intensity = Input { Value = 0.5, }, }, },
1241 Side = LightDirectional { Inputs = { ["Transform3DOp.Rotate.Y"] = Input { Value = 90, }, Red = Input { Value = 0, }, }, },
1242 M = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = "Front", Source = "Output", }, SceneInput2 = Input { SourceOp = "Side", Source = "Output", }, }, },"#,
1243 );
1244 let (_, _, lights) = collect(&src, "M");
1245 assert_eq!(lights.dirs.len(), 2);
1246 assert_eq!(lights.dirs[0].color, [0.5, 0.5, 0.5]);
1247 assert!((lights.dirs[0].to_light[2] - 1.0).abs() < 1e-5);
1248 assert_eq!(lights.dirs[1].color, [0.0, 1.0, 1.0]);
1249 assert!((lights.dirs[1].to_light[0] - 1.0).abs() < 1e-5, "{:?}", lights.dirs[1].to_light);
1250 }
1251
1252 #[test]
1253 fn mat4_inverse_handles_scaled_camera_parents() {
1254 let src = comp_src(
1255 r#"Cam = Camera3D { Inputs = { ["Transform3DOp.Translate.Z"] = Input { Value = 4, }, ["Transform3DOp.Rotate.Y"] = Input { Value = 30, }, }, },
1256 Rig = Transform3D { Inputs = { ["Transform3DOp.ScaleLock"] = Input { Value = 0, }, ["Transform3DOp.Scale.X"] = Input { Value = 2, }, ["Transform3DOp.Scale.Y"] = Input { Value = 0.5, }, ["Transform3DOp.Translate.X"] = Input { Value = 3, }, SceneInput1 = Input { SourceOp = "Cam", Source = "Output", }, }, },"#,
1257 );
1258 let (cams, ..) = collect(&src, "Rig");
1259 let world = cams[0].world;
1260 let near_identity = |m: Mat4| m.iter().zip(mat4_identity()).all(|(a, b)| (a - b).abs() < 1e-5);
1261 assert!(near_identity(mat4_mul(mat4_inverse(world), world)));
1262 assert!(!near_identity(mat4_mul(mat4_inverse_rigid(world), world)), "rigid inverse is wrong under scale");
1263 }
1264
1265 #[test]
1266 fn mat4_inverse_of_singular_matrix_is_finite() {
1267 let inv = mat4_inverse(mat4_scale(0.0, 1.0, 1.0));
1268 assert!(inv.iter().all(|v| v.is_finite()));
1269 assert_eq!(mat4_inverse(mat4_translate(1.0, 2.0, 3.0)), mat4_translate(-1.0, -2.0, -3.0));
1270 }
1186}1271}
crates/engine/src/scene3d/fbx.rs+44-13
...@@ -6,12 +6,13 @@...@@ -6,12 +6,13 @@
6//! - Binary FBX (`Kaydara FBX Binary \0`, v7100–v7700+, raw & zlib-compressed arrays)6//! - Binary FBX (`Kaydara FBX Binary \0`, v7100–v7700+, raw & zlib-compressed arrays)
7//!7//!
8//! Recomputes smooth vertex normals when absent, applies `ScaleFileUnitsBy`,8//! Recomputes smooth vertex normals when absent, applies `ScaleFileUnitsBy`,
9//! caches loaded meshes by `(path, obj_name, scale)`, and falls back gracefully9//! caches loaded meshes by `(path, mtime, obj_name, scale)`, and falls back gracefully
10//! to a unit bounding-box placeholder mesh if the file is missing or unreadable.10//! to a unit bounding-box placeholder mesh (never cached) if the file is missing or unreadable.
1111
12use std::collections::HashMap;12use std::collections::HashMap;
13use std::path::{Path, PathBuf};13use std::path::{Path, PathBuf};
14use std::sync::{Arc, Mutex, OnceLock};14use std::sync::{Arc, Mutex, OnceLock};
15use std::time::SystemTime;
1516
16use super::shader::Vertex3D;17use super::shader::Vertex3D;
1718
...@@ -21,11 +22,12 @@ const MAX_FBX_DEPTH: usize = 32;...@@ -21,11 +22,12 @@ const MAX_FBX_DEPTH: usize = 32;
21const MAX_DECOMPRESS_BYTES: usize = 64 * 1024 * 1024;22const MAX_DECOMPRESS_BYTES: usize = 64 * 1024 * 1024;
22const MAX_TRIANGLES: usize = 500_000;23const MAX_TRIANGLES: usize = 500_000;
2324
24type MeshCacheKey = (String, String, u32);25type MeshCacheKey = (PathBuf, Option<SystemTime>, String, u32);
25static MESH_CACHE: OnceLock<Mutex<HashMap<MeshCacheKey, Arc<Vec<Vertex3D>>>>> = OnceLock::new();26static MESH_CACHE: OnceLock<Mutex<HashMap<MeshCacheKey, Arc<Vec<Vertex3D>>>>> = OnceLock::new();
2627
27/// Loads a `.fbx` or `.obj` mesh (cached), applying `scale_units` (`ScaleFileUnitsBy`).28/// Loads a `.fbx` or `.obj` mesh (cached), applying `scale_units` (`ScaleFileUnitsBy`).
28/// Falls back to a unit bounding-box placeholder mesh if the file is missing or invalid.29/// Editing the file on disk invalidates its entry. A unit bounding-box placeholder is returned,
30/// but not cached, if the file is missing or invalid.
29pub(super) fn load_mesh_cached(31pub(super) fn load_mesh_cached(
30 raw_path: &str,32 raw_path: &str,
31 comp_path: Option<&Path>,33 comp_path: Option<&Path>,
...@@ -38,12 +40,10 @@ pub(super) fn load_mesh_cached(...@@ -38,12 +40,10 @@ pub(super) fn load_mesh_cached(
38 1.040 1.0
39 };41 };
40 let resolved = resolve_import_path(raw_path, comp_path);42 let resolved = resolve_import_path(raw_path, comp_path);
41 let cache_path = resolved43 let mtime = resolved.as_ref().and_then(|p| std::fs::metadata(p).and_then(|m| m.modified()).ok());
42 .as_ref()
43 .map(|p| p.to_string_lossy().into_owned())
44 .unwrap_or_else(|| raw_path.to_string());
45 let key = (44 let key = (
46 cache_path,45 resolved.clone().unwrap_or_else(|| PathBuf::from(raw_path)),
46 mtime,
47 obj_name.unwrap_or("").to_string(),47 obj_name.unwrap_or("").to_string(),
48 scale.to_bits(),48 scale.to_bits(),
49 );49 );
...@@ -61,8 +61,12 @@ pub(super) fn load_mesh_cached(...@@ -61,8 +61,12 @@ pub(super) fn load_mesh_cached(
61 let bytes = std::fs::read(&p).ok()?;61 let bytes = std::fs::read(&p).ok()?;
62 parse_mesh_bytes(&bytes, ext.as_deref(), obj_name, scale)62 parse_mesh_bytes(&bytes, ext.as_deref(), obj_name, scale)
63 })63 })
64 .filter(|v| !v.is_empty())64 .filter(|v| !v.is_empty());
65 .unwrap_or_else(unit_box_placeholder);65 let Some(loaded) = loaded else {
66 // Shared so a missing file keeps a stable identity for downstream cache keys.
67 static PLACEHOLDER: OnceLock<Arc<Vec<Vertex3D>>> = OnceLock::new();
68 return Arc::clone(PLACEHOLDER.get_or_init(|| Arc::new(unit_box_placeholder())));
69 };
6670
67 let arc = Arc::new(loaded);71 let arc = Arc::new(loaded);
68 if let Ok(mut guard) = cache.lock() {72 if let Ok(mut guard) = cache.lock() {
...@@ -1508,8 +1512,35 @@ Objects: {...@@ -1508,8 +1512,35 @@ Objects: {
1508 }1512 }
15091513
1510 #[test]1514 #[test]
1511 fn test_missing_file_fallback_unit_box() {1515 fn test_missing_file_fallback_unit_box_is_not_cached() {
1512 let mesh = load_mesh_cached("/nonexistent/path/to/missing_model.fbx", None, None, 1.0);1516 let path = "/nonexistent/path/to/missing_model.fbx";
1517 let mesh = load_mesh_cached(path, None, None, 1.0);
1513 assert_eq!(mesh.len(), 36, "fallback placeholder should be a 12-triangle unit box");1518 assert_eq!(mesh.len(), 36, "fallback placeholder should be a 12-triangle unit box");
1519 let cache = MESH_CACHE.get().unwrap().lock().unwrap();
1520 assert!(!cache.keys().any(|k| k.0 == Path::new(path)));
1521 }
1522
1523 #[test]
1524 fn test_editing_file_on_disk_invalidates_cache() {
1525 let dir = std::env::temp_dir().join(format!("fission-fbx-mtime-{}", std::process::id()));
1526 std::fs::create_dir_all(&dir).unwrap();
1527 let file = dir.join("tri.obj");
1528 let path = file.to_str().unwrap();
1529 let write = |body: &str, mtime_secs: u64| {
1530 std::fs::write(&file, body).unwrap();
1531 let t = SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(mtime_secs);
1532 std::fs::File::options().write(true).open(&file).unwrap().set_modified(t).unwrap();
1533 };
1534 let tri = "v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n";
1535 let quad = "v 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\nf 1 2 3 4\n";
1536
1537 write(tri, 1_000_000);
1538 let first = load_mesh_cached(path, None, None, 1.0);
1539 assert_eq!(first.len(), 3);
1540 assert!(Arc::ptr_eq(&first, &load_mesh_cached(path, None, None, 1.0)), "unchanged file hits the cache");
1541
1542 write(quad, 2_000_000);
1543 assert_eq!(load_mesh_cached(path, None, None, 1.0).len(), 6, "edited file reloads");
1544 std::fs::remove_dir_all(&dir).unwrap();
1514 }1545 }
1515}1546}
crates/engine/src/scene3d/mod.rs+220-56
...@@ -12,19 +12,20 @@ mod math;...@@ -12,19 +12,20 @@ mod math;
12mod mesh;12mod mesh;
13mod shader;13mod shader;
1414
15pub use collect::{collect_scene, collect_scene_with_nodes, eval_transform3d};15pub use collect::{collect_scene, collect_scene_with_nodes, eval_transform3d, mat4_inverse};
16pub use math::{16pub use math::{
17 mat4_identity, mat4_inverse_rigid, mat4_mul, mat4_perspective_wgpu, mat4_rot_x, mat4_rot_y,17 mat4_identity, mat4_inverse_rigid, mat4_mul, mat4_perspective_wgpu, mat4_rot_x, mat4_rot_y,
18 mat4_rot_z, mat4_scale, mat4_translate,18 mat4_rot_z, mat4_scale, mat4_translate,
19};19};
20pub use shader::Vertex3D;20pub use shader::Vertex3D;
2121
22use std::sync::Arc;22use std::collections::HashMap;
23use std::sync::{Arc, Mutex};
2324
24use crate::cache::CachedTexture;25use crate::cache::CachedTexture;
25use mesh::{apply_heightmap_displace, build_shape_mesh, triangle_edges};26use mesh::{apply_heightmap_displace, build_shape_mesh, triangle_edges};
26use model::NodeId;27use model::NodeId;
27use shader::{MeshUniform, MAX_LIGHTS, SHADER_3D};28use shader::{MeshUniform, MAX_DIR_LIGHTS, MAX_LIGHTS, SHADER_3D};
2829
29pub type Mat4 = [f32; 16]; // Column-major 4x430pub type Mat4 = [f32; 16]; // Column-major 4x4
3031
...@@ -34,6 +35,52 @@ pub struct Scene3DRenderer {...@@ -34,6 +35,52 @@ pub struct Scene3DRenderer {
34 /// faces show the inside of closed meshes.35 /// faces show the inside of closed meshes.
35 pipelines: [[wgpu::RenderPipeline; 2]; 2],36 pipelines: [[wgpu::RenderPipeline; 2]; 2],
36 sampler: wgpu::Sampler,37 sampler: wgpu::Sampler,
38 meshes: Mutex<Lru<MeshKey, Option<GpuMesh>>>,
39}
40
41/// Most meshes kept resident on the GPU across frames.
42const MESH_CACHE_CAP: usize = 64;
43
44/// `(base shape hash, image-plane aspect bits, wireframe)`; everything `build_shape_mesh` and the
45/// edge conversion read, so animated transforms and materials reuse one upload.
46type MeshKey = (u64, u32, bool);
47
48#[derive(Clone)]
49struct GpuMesh {
50 vbuf: wgpu::Buffer,
51 ibuf: wgpu::Buffer,
52 idx_count: u32,
53 /// Keeps a `CustomMesh` allocation alive: `ShapeKind::hash_into` hashes its address.
54 _shape: ShapeKind,
55}
56
57/// Bounded map evicting the least recently used entry.
58struct Lru<K, V> {
59 cap: usize,
60 tick: u64,
61 entries: HashMap<K, (u64, V)>,
62}
63
64impl<K: std::hash::Hash + Eq + Copy, V: Clone> Lru<K, V> {
65 fn new(cap: usize) -> Self {
66 Self { cap, tick: 0, entries: HashMap::new() }
67 }
68
69 fn get_or_insert_with(&mut self, key: K, make: impl FnOnce() -> V) -> V {
70 self.tick += 1;
71 if let Some((used, v)) = self.entries.get_mut(&key) {
72 *used = self.tick;
73 return v.clone();
74 }
75 if self.entries.len() >= self.cap {
76 if let Some(oldest) = self.entries.iter().min_by_key(|(_, (used, _))| *used).map(|(k, _)| *k) {
77 self.entries.remove(&oldest);
78 }
79 }
80 let v = make();
81 self.entries.insert(key, (self.tick, v.clone()));
82 v
83 }
37}84}
3885
39#[derive(Clone)]86#[derive(Clone)]
...@@ -287,29 +334,21 @@ pub struct SpotLight {...@@ -287,29 +334,21 @@ pub struct SpotLight {
287 pub decay_type: f32,334 pub decay_type: f32,
288}335}
289336
290#[derive(Clone, Debug)]337#[derive(Clone, Copy, Debug)]
338pub struct DirLight {
339 pub to_light: [f32; 3],
340 pub color: [f32; 3],
341}
342
343#[derive(Clone, Debug, Default)]
291pub struct SceneLights {344pub struct SceneLights {
292 pub ambient: [f32; 3],345 pub ambient: [f32; 3],
293 pub dir_to_light: [f32; 3],346 /// Only the first `MAX_DIR_LIGHTS` reach the shader.
294 pub dir_color: [f32; 3],347 pub dirs: Vec<DirLight>,
295 pub has_dir: bool,
296 pub points: Vec<PointLight>,348 pub points: Vec<PointLight>,
297 pub spots: Vec<SpotLight>,349 pub spots: Vec<SpotLight>,
298}350}
299351
300impl Default for SceneLights {
301 fn default() -> Self {
302 Self {
303 ambient: [0.0, 0.0, 0.0],
304 dir_to_light: [0.0, 0.0, 1.0],
305 dir_color: [0.0, 0.0, 0.0],
306 has_dir: false,
307 points: Vec::new(),
308 spots: Vec::new(),
309 }
310 }
311}
312
313pub struct DrawMesh {352pub struct DrawMesh {
314 pub world: Mat4,353 pub world: Mat4,
315 pub shape: ShapeKind,354 pub shape: ShapeKind,
...@@ -323,11 +362,24 @@ pub struct DrawMesh {...@@ -323,11 +362,24 @@ pub struct DrawMesh {
323 pub displace: Option<DisplaceHeightmap>,362 pub displace: Option<DisplaceHeightmap>,
324}363}
325364
365fn mesh_key(base_shape: &ShapeKind, aspect: f32, wireframe: bool) -> MeshKey {
366 use std::hash::{DefaultHasher, Hasher};
367 let mut h = DefaultHasher::new();
368 base_shape.hash_into(&mut h);
369 let aspect_bits = if matches!(base_shape, ShapeKind::ImagePlane) { aspect.to_bits() } else { 0 };
370 (h.finish(), aspect_bits, wireframe)
371}
372
326impl Scene3DRenderer {373impl Scene3DRenderer {
327 pub fn new(device: &wgpu::Device) -> Self {374 pub fn new(device: &wgpu::Device) -> Self {
328 let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {375 let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
329 label: Some("scene3d-shader"),376 label: Some("scene3d-shader"),
330 source: wgpu::ShaderSource::Wgsl(SHADER_3D.replace("MAX_LIGHTS", &MAX_LIGHTS.to_string()).into()),377 source: wgpu::ShaderSource::Wgsl(
378 SHADER_3D
379 .replace("MAX_DIR_LIGHTS", &MAX_DIR_LIGHTS.to_string())
380 .replace("MAX_LIGHTS", &MAX_LIGHTS.to_string())
381 .into(),
382 ),
331 });383 });
332 let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {384 let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
333 label: Some("scene3d-bgl"),385 label: Some("scene3d-bgl"),
...@@ -423,7 +475,7 @@ impl Scene3DRenderer {...@@ -423,7 +475,7 @@ impl Scene3DRenderer {
423 mipmap_filter: wgpu::MipmapFilterMode::Linear,475 mipmap_filter: wgpu::MipmapFilterMode::Linear,
424 ..Default::default()476 ..Default::default()
425 });477 });
426 Self { bgl, pipelines, sampler }478 Self { bgl, pipelines, sampler, meshes: Mutex::new(Lru::new(MESH_CACHE_CAP)) }
427 }479 }
428480
429 #[allow(clippy::too_many_arguments)]481 #[allow(clippy::too_many_arguments)]
...@@ -489,32 +541,45 @@ impl Scene3DRenderer {...@@ -489,32 +541,45 @@ impl Scene3DRenderer {
489 .map(|t| (t.canvas_size[0] as f32 / t.canvas_size[1].max(1) as f32).max(1e-4))541 .map(|t| (t.canvas_size[0] as f32 / t.canvas_size[1].max(1) as f32).max(1e-4))
490 .unwrap_or(16.0 / 9.0);542 .unwrap_or(16.0 / 9.0);
491 let (base_shape, fx) = m.shape.split_fx();543 let (base_shape, fx) = m.shape.split_fx();
492 let (mut verts, mut indices) = build_shape_mesh(base_shape, aspect);544 let upload = || {
493 if indices.is_empty() {545 let (mut verts, mut indices) = build_shape_mesh(base_shape, aspect);
546 if indices.is_empty() {
547 return None;
548 }
549 if let Some(disp) = &m.displace {
550 apply_heightmap_displace(&mut verts, &indices, disp);
551 }
552 if fx.wireframe {
553 indices = triangle_edges(&indices);
554 }
555 let vbytes = bytemuck::cast_slice(&verts);
556 let ibytes = bytemuck::cast_slice(&indices);
557 let vbuf = device.create_buffer(&wgpu::BufferDescriptor {
558 label: Some("scene3d-vb"),
559 size: vbytes.len() as u64,
560 usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
561 mapped_at_creation: false,
562 });
563 queue.write_buffer(&vbuf, 0, vbytes);
564 let ibuf = device.create_buffer(&wgpu::BufferDescriptor {
565 label: Some("scene3d-ib"),
566 size: ibytes.len() as u64,
567 usage: wgpu::BufferUsages::INDEX | wgpu::BufferUsages::COPY_DST,
568 mapped_at_creation: false,
569 });
570 queue.write_buffer(&ibuf, 0, ibytes);
571 Some(GpuMesh { vbuf, ibuf, idx_count: indices.len() as u32, _shape: base_shape.clone() })
572 };
573 // Heightmap contents are not part of the key, so displaced meshes are never cached.
574 let gpu_mesh = if m.displace.is_some() {
575 upload()
576 } else {
577 let key = mesh_key(base_shape, aspect, fx.wireframe);
578 self.meshes.lock().unwrap().get_or_insert_with(key, upload)
579 };
580 let Some(GpuMesh { vbuf, ibuf, idx_count, .. }) = gpu_mesh else {
494 continue;581 continue;
495 }582 };
496 if let Some(disp) = &m.displace {
497 apply_heightmap_displace(&mut verts, &indices, disp);
498 }
499 if fx.wireframe {
500 indices = triangle_edges(&indices);
501 }
502 let vbytes = bytemuck::cast_slice(&verts);
503 let ibytes = bytemuck::cast_slice(&indices);
504 let vbuf = device.create_buffer(&wgpu::BufferDescriptor {
505 label: Some("scene3d-vb"),
506 size: vbytes.len() as u64,
507 usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
508 mapped_at_creation: false,
509 });
510 queue.write_buffer(&vbuf, 0, vbytes);
511 let ibuf = device.create_buffer(&wgpu::BufferDescriptor {
512 label: Some("scene3d-ib"),
513 size: ibytes.len() as u64,
514 usage: wgpu::BufferUsages::INDEX | wgpu::BufferUsages::COPY_DST,
515 mapped_at_creation: false,
516 });
517 queue.write_buffer(&ibuf, 0, ibytes);
518583
519 let mvp = mat4_mul(view_proj, m.world);584 let mvp = mat4_mul(view_proj, m.world);
520 let dod = if let Some(t) = &m.tex {585 let dod = if let Some(t) = &m.tex {
...@@ -542,6 +607,13 @@ impl Scene3DRenderer {...@@ -542,6 +607,13 @@ impl Scene3DRenderer {
542 spot_dir[si] = [sl.dir[0], sl.dir[1], sl.dir[2], sl.cos_outer];607 spot_dir[si] = [sl.dir[0], sl.dir[1], sl.dir[2], sl.cos_outer];
543 spot_col[si] = [sl.color[0], sl.color[1], sl.color[2], sl.decay_type];608 spot_col[si] = [sl.color[0], sl.color[1], sl.color[2], sl.decay_type];
544 }609 }
610 let mut dir_to_light = [[0.0_f32; 4]; MAX_DIR_LIGHTS];
611 let mut dir_color = [[0.0_f32; 4]; MAX_DIR_LIGHTS];
612 let n_dir = lights.dirs.len().min(MAX_DIR_LIGHTS);
613 for (di, dl) in lights.dirs.iter().take(MAX_DIR_LIGHTS).enumerate() {
614 dir_to_light[di] = [dl.to_light[0], dl.to_light[1], dl.to_light[2], 0.0];
615 dir_color[di] = [dl.color[0], dl.color[1], dl.color[2], 0.0];
616 }
545 let uni = MeshUniform {617 let uni = MeshUniform {
546 mvp,618 mvp,
547 model: m.world,619 model: m.world,
...@@ -560,15 +632,10 @@ impl Scene3DRenderer {...@@ -560,15 +632,10 @@ impl Scene3DRenderer {
560 m.specular_exponent,632 m.specular_exponent,
561 ],633 ],
562 ambient: [lights.ambient[0], lights.ambient[1], lights.ambient[2], 0.0],634 ambient: [lights.ambient[0], lights.ambient[1], lights.ambient[2], 0.0],
563 dir_to_light: [635 dir_to_light,
564 lights.dir_to_light[0],636 dir_color,
565 lights.dir_to_light[1],
566 lights.dir_to_light[2],
567 if lights.has_dir { 1.0 } else { 0.0 },
568 ],
569 dir_color: [lights.dir_color[0], lights.dir_color[1], lights.dir_color[2], 0.0],
570 cam_pos: [cam_pos[0], cam_pos[1], cam_pos[2], 0.0],637 cam_pos: [cam_pos[0], cam_pos[1], cam_pos[2], 0.0],
571 light_counts: [n_pt as f32, n_sp as f32, 0.0, 0.0],638 light_counts: [n_pt as f32, n_sp as f32, n_dir as f32, 0.0],
572 uv_xform: fx.uv.m,639 uv_xform: fx.uv.m,
573 uv_off_wrap: [fx.uv.t[0], fx.uv.t[1], fx.uv_wrap as f32, 0.0],640 uv_off_wrap: [fx.uv.t[0], fx.uv.t[1], fx.uv_wrap as f32, 0.0],
574 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],641 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],
...@@ -601,7 +668,7 @@ impl Scene3DRenderer {...@@ -601,7 +668,7 @@ impl Scene3DRenderer {
601 bg,668 bg,
602 vbuf,669 vbuf,
603 ibuf,670 ibuf,
604 idx_count: indices.len() as u32,671 idx_count,
605 });672 });
606 }673 }
607674
...@@ -726,6 +793,103 @@ mod tests {...@@ -726,6 +793,103 @@ mod tests {
726 assert!((alpha - 191).abs() <= 3, "alpha {alpha}");793 assert!((alpha - 191).abs() <= 3, "alpha {alpha}");
727 }794 }
728795
796 #[test]
797 fn normals_stay_perpendicular_under_non_uniform_scale() {
798 // Plane rotated 45 degrees about Y under a [4, 1, 1] scale: the true normal is
799 // (1/4, 0, 1) normalized, so a +Z light gives cos = 0.970; `model * n` would give 0.243.
800 let scene = r#"P = Shape3D { Inputs = { ["SurfacePlaneInputs.Width"] = Input { Value = 2, }, ["Transform3DOp.Rotate.Y"] = Input { Value = 45, }, MaterialInput = Input { SourceOp = "Flat", Source = "MaterialOutput", }, }, },
801 S = Transform3D { Inputs = { ["Transform3DOp.ScaleLock"] = Input { Value = 0, }, ["Transform3DOp.Scale.X"] = Input { Value = 4, }, SceneInput1 = Input { SourceOp = "P", Source = "Output", }, }, },
802 L = LightDirectional { },
803 M = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = "S", Source = "Output", }, SceneInput2 = Input { SourceOp = "L", Source = "Output", }, SceneInput3 = Input { SourceOp = "Cam", Source = "Output", }, }, },"#;
804 let Some(px) = render(true, scene) else { return };
805 let expected = 255.0 / (1.0 + 1.0 / 16.0_f32).sqrt();
806 let c = center(&px);
807 assert!((c[0] as f32 - expected).abs() <= 3.0, "{c:?} vs {expected}");
808 }
809
810 #[test]
811 fn up_to_four_directional_lights_accumulate() {
812 // Five 0.1 lights facing the plane: the first four reach the shader, so 0.4 * 255.
813 let lights: String = (1..=5)
814 .map(|i| format!(r#"L{i} = LightDirectional {{ Inputs = {{ Intensity = Input {{ Value = 0.1, }}, }}, }},"#))
815 .collect();
816 let ports: String = (1..=5).map(|i| format!(r#"SceneInput{} = Input {{ SourceOp = "L{i}", Source = "Output", }},"#, i + 1)).collect();
817 let scene = format!(
818 r#"{PLANE} {lights}
819 M = Merge3D {{ Inputs = {{ SceneInput1 = Input {{ SourceOp = "P", Source = "Output", }}, {ports} SceneInput7 = Input {{ SourceOp = "Cam", Source = "Output", }}, }}, }},"#
820 );
821 let Some(px) = render(true, &scene) else { return };
822 let c = center(&px);
823 assert!((c[0] as f32 - 102.0).abs() <= 3.0, "{c:?}");
824 }
825
826 #[test]
827 fn gpu_meshes_are_reused_across_frames_and_split_by_wireframe() {
828 let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle());
829 let Ok(adapter) = pollster::block_on(instance.request_adapter(&Default::default())) else { return };
830 let Ok((device, queue)) = pollster::block_on(adapter.request_device(&Default::default())) else { return };
831 let renderer = Scene3DRenderer::new(&device);
832 let target = || {
833 CachedTexture::from_texture(
834 device.create_texture(&wgpu::TextureDescriptor {
835 label: None,
836 size: wgpu::Extent3d { width: 8, height: 8, depth_or_array_layers: 1 },
837 mip_level_count: 1,
838 sample_count: 1,
839 dimension: wgpu::TextureDimension::D2,
840 format: wgpu::TextureFormat::Rgba8Unorm,
841 usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::RENDER_ATTACHMENT,
842 view_formats: &[],
843 }),
844 [8, 8],
845 0,
846 )
847 };
848 let (dst, dummy) = (target(), target());
849 let sphere = |x: f32, wireframe: bool| DrawMesh {
850 world: mat4_translate(x, 0.0, 0.0),
851 shape: ShapeKind::WithMaterialFx {
852 inner: Box::new(ShapeKind::Sphere { radius: 1.0, sub_base: 8, sub_height: 8 }),
853 fx: MaterialFx { wireframe, ..Default::default() },
854 },
855 tex: None,
856 diffuse_col: [1.0; 4],
857 specular_col: [1.0; 3],
858 specular_intensity: 0.0,
859 specular_exponent: 50.0,
860 affected_by_lights: false,
861 flip_normals: false,
862 displace: None,
863 };
864 let frame = |meshes: &[DrawMesh]| {
865 let mut enc = device.create_command_encoder(&Default::default());
866 let (vp, cam) = (mat4_identity(), [0.0, 0.0, 5.0]);
867 renderer.render_meshes(&device, &queue, &mut enc, &dst, &dummy, vp, vp, cam, SceneLights::default(), false, meshes);
868 queue.submit(Some(enc.finish()));
869 renderer.meshes.lock().unwrap().entries.len()
870 };
871 assert_eq!(frame(&[sphere(0.0, false)]), 1);
872 assert_eq!(frame(&[sphere(0.5, false)]), 1, "a moved copy reuses the upload");
873 assert_eq!(frame(&[sphere(0.5, true)]), 2, "wireframe uses edge indices");
874 }
875
876 #[test]
877 fn lru_evicts_the_least_recently_used_entry_and_reuses_hits() {
878 let mut lru = Lru::new(2);
879 let builds = std::cell::Cell::new(0);
880 let get = |lru: &mut Lru<u8, u8>, k: u8| lru.get_or_insert_with(k, || { builds.set(builds.get() + 1); k });
881 get(&mut lru, 1);
882 get(&mut lru, 2);
883 get(&mut lru, 1);
884 get(&mut lru, 3);
885 assert_eq!(builds.get(), 3, "second request for key 1 is a hit");
886 get(&mut lru, 1);
887 assert_eq!(builds.get(), 3, "key 1 was refreshed, so key 2 was evicted");
888 get(&mut lru, 2);
889 assert_eq!(builds.get(), 4);
890 assert_eq!(lru.entries.len(), 2);
891 }
892
729 #[test]893 #[test]
730 fn uv_affine_then_applies_self_first() {894 fn uv_affine_then_applies_self_first() {
731 let shift = UvAffine { m: [1.0, 0.0, 0.0, 1.0], t: [0.5, 0.0] };895 let shift = UvAffine { m: [1.0, 0.0, 0.0, 1.0], t: [0.5, 0.0] };
crates/engine/src/scene3d/shader.rs+27-12
...@@ -4,6 +4,8 @@ use bytemuck::{Pod, Zeroable};...@@ -4,6 +4,8 @@ use bytemuck::{Pod, Zeroable};
44
5/// Point and spot lights each get this many shader slots.5/// Point and spot lights each get this many shader slots.
6pub(super) const MAX_LIGHTS: usize = 8;6pub(super) const MAX_LIGHTS: usize = 8;
7/// Directional lights get this many shader slots.
8pub(super) const MAX_DIR_LIGHTS: usize = 4;
79
8#[repr(C)]10#[repr(C)]
9#[derive(Clone, Copy, Debug, Pod, Zeroable)]11#[derive(Clone, Copy, Debug, Pod, Zeroable)]
...@@ -28,13 +30,13 @@ pub(super) struct MeshUniform {...@@ -28,13 +30,13 @@ pub(super) struct MeshUniform {
28 pub(super) specular_col: [f32; 4],30 pub(super) specular_col: [f32; 4],
29 /// Ambient light `(r, g, b, 0)`31 /// Ambient light `(r, g, b, 0)`
30 pub(super) ambient: [f32; 4],32 pub(super) ambient: [f32; 4],
31 /// Directional light direction TO light `(dx, dy, dz, has_dir)`33 /// Directional light directions TO light `(dx, dy, dz, 0)`
32 pub(super) dir_to_light: [f32; 4],34 pub(super) dir_to_light: [[f32; 4]; MAX_DIR_LIGHTS],
33 /// Directional light color * intensity `(r, g, b, 0)`35 /// Directional light colors * intensity `(r, g, b, 0)`
34 pub(super) dir_color: [f32; 4],36 pub(super) dir_color: [[f32; 4]; MAX_DIR_LIGHTS],
35 /// Camera world position `(cx, cy, cz, 0)`37 /// Camera world position `(cx, cy, cz, 0)`
36 pub(super) cam_pos: [f32; 4],38 pub(super) cam_pos: [f32; 4],
37 /// `[num_point_lights, num_spot_lights, 0, 0]`39 /// `[num_point_lights, num_spot_lights, num_dir_lights, 0]`
38 pub(super) light_counts: [f32; 4],40 pub(super) light_counts: [f32; 4],
39 /// UV affine matrix, column-major `[m00, m10, m01, m11]`41 /// UV affine matrix, column-major `[m00, m10, m01, m11]`
40 pub(super) uv_xform: [f32; 4],42 pub(super) uv_xform: [f32; 4],
...@@ -54,7 +56,7 @@ pub(super) struct MeshUniform {...@@ -54,7 +56,7 @@ pub(super) struct MeshUniform {
54 pub(super) spot_col: [[f32; 4]; MAX_LIGHTS],56 pub(super) spot_col: [[f32; 4]; MAX_LIGHTS],
55}57}
5658
57/// WGSL source; `MAX_LIGHTS` is substituted with the Rust constant at pipeline creation.59/// WGSL source; `MAX_LIGHTS` and `MAX_DIR_LIGHTS` are substituted with the Rust constants at pipeline creation.
58pub(super) const SHADER_3D: &str = r#"60pub(super) const SHADER_3D: &str = r#"
59struct MeshUniform {61struct MeshUniform {
60 mvp: mat4x4<f32>,62 mvp: mat4x4<f32>,
...@@ -64,8 +66,8 @@ struct MeshUniform {...@@ -64,8 +66,8 @@ struct MeshUniform {
64 diffuse_col: vec4<f32>,66 diffuse_col: vec4<f32>,
65 specular_col: vec4<f32>,67 specular_col: vec4<f32>,
66 ambient: vec4<f32>,68 ambient: vec4<f32>,
67 dir_to_light: vec4<f32>,69 dir_to_light: array<vec4<f32>, MAX_DIR_LIGHTS>,
68 dir_color: vec4<f32>,70 dir_color: array<vec4<f32>, MAX_DIR_LIGHTS>,
69 cam_pos: vec4<f32>,71 cam_pos: vec4<f32>,
70 light_counts: vec4<f32>,72 light_counts: vec4<f32>,
71 uv_xform: vec4<f32>,73 uv_xform: vec4<f32>,
...@@ -97,6 +99,17 @@ struct VsOut {...@@ -97,6 +99,17 @@ struct VsOut {
97 @location(2) world_n: vec3<f32>,99 @location(2) world_n: vec3<f32>,
98};100};
99101
102// Cofactor matrix of the upper-left 3x3 of `m` (inverse-transpose up to scale), so normals stay
103// perpendicular under non-uniform scale. Dividing by |det| instead of det keeps mirrored
104// transforms pointing outward.
105fn normal_matrix(m: mat4x4<f32>) -> mat3x3<f32> {
106 let c0 = m[0].xyz;
107 let c1 = m[1].xyz;
108 let c2 = m[2].xyz;
109 let sign = select(-1.0, 1.0, dot(c0, cross(c1, c2)) >= 0.0);
110 return mat3x3<f32>(cross(c1, c2), cross(c2, c0), cross(c0, c1)) * sign;
111}
112
100@vertex113@vertex
101fn vs_mesh(v: VsIn) -> VsOut {114fn vs_mesh(v: VsIn) -> VsOut {
102 var out: VsOut;115 var out: VsOut;
...@@ -104,7 +117,7 @@ fn vs_mesh(v: VsIn) -> VsOut {...@@ -104,7 +117,7 @@ fn vs_mesh(v: VsIn) -> VsOut {
104 out.clip = u.mvp * vec4<f32>(v.pos, 1.0);117 out.clip = u.mvp * vec4<f32>(v.pos, 1.0);
105 out.uv = v.uv;118 out.uv = v.uv;
106 out.world_pos = wp.xyz;119 out.world_pos = wp.xyz;
107 let wn = (u.model * vec4<f32>(v.normal, 0.0)).xyz;120 let wn = normal_matrix(u.model) * v.normal;
108 let nlen = length(wn);121 let nlen = length(wn);
109 var n_norm = select(vec3<f32>(0.0, 0.0, 1.0), wn / nlen, nlen > 1e-5);122 var n_norm = select(vec3<f32>(0.0, 0.0, 1.0), wn / nlen, nlen > 1e-5);
110 if (u.flags.w > 0.5) {123 if (u.flags.w > 0.5) {
...@@ -278,9 +291,11 @@ fn fs_mesh(in: VsOut) -> @location(0) vec4<f32> {...@@ -278,9 +291,11 @@ fn fs_mesh(in: VsOut) -> @location(0) vec4<f32> {
278 let spec_int = u.flags.z;291 let spec_int = u.flags.z;
279292
280 var lit = albedo * u.ambient.rgb;293 var lit = albedo * u.ambient.rgb;
281 if (u.dir_to_light.w > 0.5) {294 let n_dir = i32(u.light_counts.z + 0.5);
282 let l = normalize(u.dir_to_light.xyz);295 for (var i: i32 = 0; i < MAX_DIR_LIGHTS; i = i + 1) {
283 lit = lit + eval_light_contrib(n, v, l, u.dir_color.rgb, albedo, spec_rgb, spec_int, shininess);296 if (i >= n_dir) { break; }
297 let l = normalize(u.dir_to_light[i].xyz);
298 lit = lit + eval_light_contrib(n, v, l, u.dir_color[i].rgb, albedo, spec_rgb, spec_int, shininess);
284 }299 }
285300
286 let n_pt = i32(u.light_counts.x + 0.5);301 let n_pt = i32(u.light_counts.x + 0.5);