authoravatarclover caruso<git@paperclover.net>2026-11-30 14:28:32-08:00
committeravatarclover caruso<git@paperclover.net>2026-11-30 14:37:05-08:00
logb509d0cf05d0ce95484aa119b66a81e1eb8836d1
tree951fac5e67889ccc7af15e264710da49333d5528
parent714f0307996641d4c23d9de8cfaedbc00282a00b
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

Add SurfaceFBXMesh, Cube3D, TextureTransformOperator, BumpMap, and pBounce (#20)


6 files changed, 2460 insertions(+), 80 deletions(-)

crates/engine/src/particles.rs+377-1
......@@ -1,7 +1,7 @@
11//! Fusion deterministic particle simulation & 2D rendering system.
22//!
33//! Supports `pEmitter`, `pPointForce`, `pDirectionalForce`, `pTurbulence`,
4//! `pDrag` / `pFriction`, `pKill`, `pMerge`, and `pRender` (2D mode).
4//! `pDrag` / `pFriction`, `pKill`, `pBounce`, `pMerge`, and `pRender` (2D mode).
55
66use std::collections::{HashMap, HashSet};
77
......@@ -297,6 +297,7 @@ fn build_plan_dfs(
297297 | "pDrag"
298298 | "pFriction"
299299 | "pKill"
300 | "pBounce"
300301 )
301302 {
302303 modifiers.push((node_id, scope.clone()));
......@@ -775,6 +776,265 @@ impl RegionSpec {
775776 }
776777 }
777778 }
779
780 /// Parses a `pBounce` region (supports `LineRgn`, `RectRgn`, `CubeRgn`, `SphereRgn`,
781 /// `MeshRegion`, and `Transform3DOp.Translate` fallback).
782 fn from_bounce_node(comp: &Comp, node: &Node, t: f64, expr: &ExprEngine) -> Self {
783 let tx = comp.eval_number(node, "Transform3DOp.Translate.X", t, 0.0, expr);
784 let ty = comp.eval_number(node, "Transform3DOp.Translate.Y", t, 0.0, expr);
785 let tz = comp.eval_number(node, "Transform3DOp.Translate.Z", t, 0.0, expr);
786 match node.static_str("Region") {
787 Some("RectRgn") => Self::Rect {
788 center: [
789 comp.eval_number(node, "RectRgn.Translate.X", t, tx, expr),
790 comp.eval_number(node, "RectRgn.Translate.Y", t, ty, expr),
791 comp.eval_number(node, "RectRgn.Translate.Z", t, tz, expr),
792 ],
793 width: comp.eval_number(node, "RectRgn.Width", t, 0.5, expr).abs(),
794 height: comp.eval_number(node, "RectRgn.Height", t, 0.5, expr).abs(),
795 },
796 Some("SphereRgn") => Self::Sphere {
797 center: [
798 comp.eval_number(node, "SphereRgn.Translate.X", t, tx, expr),
799 comp.eval_number(node, "SphereRgn.Translate.Y", t, ty, expr),
800 comp.eval_number(node, "SphereRgn.Translate.Z", t, tz, expr),
801 ],
802 radius: comp.eval_number(node, "SphereRgn.Size", t, 0.5, expr).abs() * 0.5,
803 },
804 Some("CubeRgn") => Self::Cube {
805 center: [
806 comp.eval_number(node, "CubeRgn.Translate.X", t, tx, expr),
807 comp.eval_number(node, "CubeRgn.Translate.Y", t, ty, expr),
808 comp.eval_number(node, "CubeRgn.Translate.Z", t, tz, expr),
809 ],
810 width: comp.eval_number(node, "CubeRgn.Width", t, 0.5, expr).abs(),
811 height: comp.eval_number(node, "CubeRgn.Height", t, 0.5, expr).abs(),
812 depth: comp.eval_number(node, "CubeRgn.Depth", t, 0.5, expr).abs(),
813 },
814 Some("LineRgn") => {
815 let lx = comp.eval_number(node, "LineRgn.Translate.X", t, tx, expr);
816 let ly = comp.eval_number(node, "LineRgn.Translate.Y", t, ty, expr);
817 let lz = comp.eval_number(node, "LineRgn.Translate.Z", t, tz, expr);
818 Self::Line {
819 start: [
820 lx + comp.eval_number(node, "LineRgn.Start.X", t, -0.5, expr),
821 ly + comp.eval_number(node, "LineRgn.Start.Y", t, 0.0, expr),
822 lz + comp.eval_number(node, "LineRgn.Start.Z", t, 0.0, expr),
823 ],
824 end: [
825 lx + comp.eval_number(node, "LineRgn.End.X", t, 0.5, expr),
826 ly + comp.eval_number(node, "LineRgn.End.Y", t, 0.0, expr),
827 lz + comp.eval_number(node, "LineRgn.End.Z", t, 0.0, expr),
828 ],
829 }
830 }
831 Some("MeshRegion") | None => Self::Point { center: [tx, ty, tz] },
832 _ => Self::from_node(comp, node, t, expr),
833 }
834 }
835
836 /// Checks whether a particle stepping `pos -> pos + vel` collides with this bounce region.
837 /// Returns `(contact_pos, outward_unit_normal)` when a reflection should occur.
838 fn bounce_collision(&self, pos: [f64; 3], vel: [f64; 3]) -> Option<([f64; 3], [f64; 3])> {
839 let next = [pos[0] + vel[0], pos[1] + vel[1], pos[2] + vel[2]];
840 match *self {
841 Self::Line { start, end } => {
842 let sx = end[0] - start[0];
843 let sy = end[1] - start[1];
844 let len_sq = sx * sx + sy * sy;
845 let len = len_sq.sqrt();
846 if len < 1e-9 {
847 return None;
848 }
849 let mut n = [-sy / len, sx / len, 0.0];
850 let d0 = (pos[0] - start[0]) * n[0] + (pos[1] - start[1]) * n[1];
851 let d1 = (next[0] - start[0]) * n[0] + (next[1] - start[1]) * n[1];
852 let crosses = (d0 * d1 <= 0.0 && (d0.abs() > 1e-12 || d1.abs() > 1e-12))
853 || d1.abs() <= 1e-4;
854 if !crosses {
855 return None;
856 }
857 let alpha = if (d0 - d1).abs() > 1e-12 {
858 (d0 / (d0 - d1)).clamp(0.0, 1.0)
859 } else {
860 1.0
861 };
862 let hit = [
863 pos[0] + vel[0] * alpha,
864 pos[1] + vel[1] * alpha,
865 pos[2] + vel[2] * alpha,
866 ];
867 let u = ((hit[0] - start[0]) * sx + (hit[1] - start[1]) * sy) / len_sq;
868 if !(-1e-4..=1.0 + 1e-4).contains(&u) {
869 return None;
870 }
871 let vn = vel[0] * n[0] + vel[1] * n[1];
872 if vn > 0.0 {
873 n[0] = -n[0];
874 n[1] = -n[1];
875 }
876 if vel[0] * n[0] + vel[1] * n[1] >= -1e-12 {
877 return None;
878 }
879 Some(([hit[0] + n[0] * 1e-5, hit[1] + n[1] * 1e-5, hit[2]], n))
880 }
881 Self::Sphere { center, radius } => {
882 if radius < 1e-6 {
883 return None;
884 }
885 let dp = [pos[0] - center[0], pos[1] - center[1], pos[2] - center[2]];
886 let dn = [next[0] - center[0], next[1] - center[1], next[2] - center[2]];
887 let r_pos = (dp[0] * dp[0] + dp[1] * dp[1] + dp[2] * dp[2]).sqrt();
888 let r_next = (dn[0] * dn[0] + dn[1] * dn[1] + dn[2] * dn[2]).sqrt();
889 if r_pos > radius && r_next > radius {
890 return None;
891 }
892 let ref_v = if r_pos > 1e-9 { dp } else if r_next > 1e-9 { dn } else { [0.0, 1.0, 0.0] };
893 let r_len = (ref_v[0] * ref_v[0] + ref_v[1] * ref_v[1] + ref_v[2] * ref_v[2]).sqrt().max(1e-9);
894 let mut n = [ref_v[0] / r_len, ref_v[1] / r_len, ref_v[2] / r_len];
895 if r_pos < radius && r_next >= radius {
896 // Particle hitting sphere wall from inside
897 n = [-n[0], -n[1], -n[2]];
898 let pushed = [
899 center[0] - n[0] * (radius - 1e-5).max(0.0),
900 center[1] - n[1] * (radius - 1e-5).max(0.0),
901 center[2] - n[2] * (radius - 1e-5).max(0.0),
902 ];
903 return Some((pushed, n));
904 }
905 let pushed = [
906 center[0] + n[0] * (radius + 1e-5),
907 center[1] + n[1] * (radius + 1e-5),
908 center[2] + n[2] * (radius + 1e-5),
909 ];
910 Some((pushed, n))
911 }
912 Self::Rect { center, width, height } => {
913 let hx = width * 0.5;
914 let hy = height * 0.5;
915 if hy < 1e-6 {
916 let line = Self::Line {
917 start: [center[0] - hx, center[1], center[2]],
918 end: [center[0] + hx, center[1], center[2]],
919 };
920 return line.bounce_collision(pos, vel);
921 }
922 if hx < 1e-6 {
923 let line = Self::Line {
924 start: [center[0], center[1] - hy, center[2]],
925 end: [center[0], center[1] + hy, center[2]],
926 };
927 return line.bounce_collision(pos, vel);
928 }
929 bounce_aabb(pos, vel, center, [hx, hy, 1e6], false)
930 }
931 Self::Cube { center, width, height, depth } => {
932 bounce_aabb(pos, vel, center, [width * 0.5, height * 0.5, depth * 0.5], true)
933 }
934 Self::Point { center } => {
935 let cy = center[1];
936 let d0 = pos[1] - cy;
937 let d1 = next[1] - cy;
938 if d0 * d1 <= 0.0 || d1.abs() <= 1e-5 {
939 let ny = if vel[1] < 0.0 { 1.0 } else if vel[1] > 0.0 { -1.0 } else { return None };
940 let alpha = if (d0 - d1).abs() > 1e-12 {
941 (d0 / (d0 - d1)).clamp(0.0, 1.0)
942 } else {
943 1.0
944 };
945 let hit = [
946 pos[0] + vel[0] * alpha,
947 cy + ny * 1e-5,
948 pos[2] + vel[2] * alpha,
949 ];
950 return Some((hit, [0.0, ny, 0.0]));
951 }
952 None
953 }
954 Self::All => None,
955 }
956 }
957}
958
959/// Slab-method segment-vs-AABB bounce helper (2D when `check_z == false`, 3D when `check_z == true`).
960fn bounce_aabb(
961 pos: [f64; 3],
962 vel: [f64; 3],
963 center: [f64; 3],
964 half: [f64; 3],
965 check_z: bool,
966) -> Option<([f64; 3], [f64; 3])> {
967 let axes = if check_z { 3 } else { 2 };
968 let mut inside_pos = true;
969 for a in 0..axes {
970 if (pos[a] - center[a]).abs() > half[a] {
971 inside_pos = false;
972 break;
973 }
974 }
975
976 if inside_pos {
977 // Already inside: push out through the closest face
978 let mut best_axis = 0usize;
979 let mut best_pen = f64::INFINITY;
980 let mut best_sign = 1.0f64;
981 for a in 0..axes {
982 let delta = pos[a] - center[a];
983 let pen = half[a] - delta.abs();
984 if pen < best_pen {
985 best_pen = pen;
986 best_axis = a;
987 best_sign = if delta >= 0.0 { 1.0 } else { -1.0 };
988 }
989 }
990 let mut n = [0.0; 3];
991 n[best_axis] = best_sign;
992 let mut pushed = pos;
993 pushed[best_axis] = center[best_axis] + best_sign * (half[best_axis] + 1e-5);
994 return Some((pushed, n));
995 }
996
997 let mut t_min = 0.0_f64;
998 let mut t_max = 1.0_f64;
999 let mut hit_axis = 0usize;
1000 let mut hit_sign = 1.0_f64;
1001
1002 for a in 0..axes {
1003 let min_b = center[a] - half[a];
1004 let max_b = center[a] + half[a];
1005 if vel[a].abs() < 1e-12 {
1006 if pos[a] < min_b || pos[a] > max_b {
1007 return None;
1008 }
1009 } else {
1010 let inv = 1.0 / vel[a];
1011 let mut t1 = (min_b - pos[a]) * inv;
1012 let mut t2 = (max_b - pos[a]) * inv;
1013 let mut s = -1.0;
1014 if t1 > t2 {
1015 std::mem::swap(&mut t1, &mut t2);
1016 s = 1.0;
1017 }
1018 if t1 > t_min {
1019 t_min = t1;
1020 hit_axis = a;
1021 hit_sign = s;
1022 }
1023 t_max = t_max.min(t2);
1024 if t_min > t_max {
1025 return None;
1026 }
1027 }
1028 }
1029
1030 let mut n = [0.0; 3];
1031 n[hit_axis] = hit_sign;
1032 let hit = [
1033 pos[0] + vel[0] * t_min + n[0] * 1e-5,
1034 pos[1] + vel[1] * t_min + n[1] * 1e-5,
1035 pos[2] + vel[2] * t_min + n[2] * 1e-5,
1036 ];
1037 Some((hit, n))
7781038}
7791039
7801040fn apply_modifier(
......@@ -903,6 +1163,49 @@ fn apply_modifier(
9031163 }
9041164 }
9051165 }
1166 "pBounce" => {
1167 let region = RegionSpec::from_bounce_node(comp, node, t, expr);
1168 let elasticity = comp.eval_number(node, "Elasticity", t, 1.0, expr).clamp(0.0, 2.0);
1169 let variance = comp.eval_number(node, "Variance", t, 0.0, expr).max(0.0);
1170 let friction = comp.eval_number(node, "Friction", t, 0.0, expr).clamp(0.0, 1.0);
1171 let roughness = comp.eval_number(node, "Roughness", t, 0.0, expr).max(0.0);
1172 let spin = comp.eval_number(node, "Spin", t, 0.0, expr);
1173 let seed = comp.eval_number(node, "RandomSeed", t, 0.0, expr).round() as i64;
1174 let mut rng = SplitMix64::from_parts(seed, t.round() as i64, node.id.0);
1175
1176 for p in particles.iter_mut() {
1177 if !p.alive || !scope.contains(&p.emitter_id) {
1178 continue;
1179 }
1180 let Some((pushed_pos, n)) = region.bounce_collision(p.pos, p.vel) else {
1181 continue;
1182 };
1183 let vn = p.vel[0] * n[0] + p.vel[1] * n[1] + p.vel[2] * n[2];
1184 if vn < 0.0 {
1185 let e = (elasticity * (1.0 + rng.signed() * variance)).clamp(0.0, 2.0);
1186 let t_damp = (1.0 - friction).clamp(0.0, 1.0);
1187 let vnx = vn * n[0];
1188 let vny = vn * n[1];
1189 let vnz = vn * n[2];
1190 let vtx = p.vel[0] - vnx;
1191 let vty = p.vel[1] - vny;
1192 let vtz = p.vel[2] - vnz;
1193 p.vel[0] = vtx * t_damp - vnx * e;
1194 p.vel[1] = vty * t_damp - vny * e;
1195 p.vel[2] = vtz * t_damp - vnz * e;
1196 if roughness > 1e-6 {
1197 let scatter = roughness * 0.01 * vn.abs();
1198 p.vel[0] += rng.signed() * scatter;
1199 p.vel[1] += rng.signed() * scatter;
1200 p.vel[2] += rng.signed() * scatter;
1201 }
1202 if spin.abs() > 1e-9 {
1203 p.spin_z += spin * (1.0 + 0.5 * rng.signed());
1204 }
1205 p.pos = pushed_pos;
1206 }
1207 }
1208 }
9061209 _ => {}
9071210 }
9081211}
......@@ -1538,4 +1841,77 @@ Composition {
15381841 "01_intro particle render should be fast, took {elapsed:?}"
15391842 );
15401843 }
1844
1845 #[test]
1846 fn test_pbounce_reverses_velocity_and_applies_friction() {
1847 let comp_src = r#"
1848Composition {
1849 GlobalRange = { 0, 20 },
1850 RenderRange = { 0, 20 },
1851 Tools = {
1852 pEmitter1 = pEmitter {
1853 Inputs = {
1854 Number = Input { Value = 1, },
1855 Lifespan = Input { Value = 50, },
1856 Velocity = Input { Value = 0.1, },
1857 Angle = Input { Value = -60, },
1858 Region = Input { Value = FuID { "Point" }, },
1859 ["Point.Translate.Y"] = Input { Value = 0.2, },
1860 },
1861 },
1862 pBounce1 = pBounce {
1863 Inputs = {
1864 Input = Input { SourceOp = "pEmitter1", Source = "Output", },
1865 Elasticity = Input { Value = 0.8, },
1866 Friction = Input { Value = 0.25, },
1867 Spin = Input { Value = 3.0, },
1868 Region = Input { Value = FuID { "CubeRgn" }, },
1869 ["CubeRgn.Translate.Y"] = Input { Value = -0.25, },
1870 ["CubeRgn.Width"] = Input { Value = 2.0, },
1871 ["CubeRgn.Height"] = Input { Value = 0.5, },
1872 ["CubeRgn.Depth"] = Input { Value = 2.0, },
1873 },
1874 },
1875 pRender1 = pRender {
1876 Inputs = {
1877 Input = Input { SourceOp = "pBounce1", Source = "Output", },
1878 },
1879 },
1880 },
1881}
1882"#;
1883 let comp = Comp::from_fusion_str(comp_src).expect("parse pBounce comp");
1884 let render_id = comp.node_by_name["pRender1"];
1885 let plan = build_particle_plan(&comp, render_id);
1886 let expr = ExprEngine::new();
1887 let mut state = SimState::default();
1888
1889 // Step until the first emitted particle (born at f=0 at y=0.2, vy≈-0.0866, vx=0.05)
1890 // crosses the floor at y=0.0 around frame 3.
1891 for f in 0..=4 {
1892 step_simulation(&mut state, &comp, &plan, f, &expr);
1893 }
1894 let first = state.particles.first().expect("particle emitted");
1895 let init_vx = 0.1 * (-60.0_f64).to_radians().cos();
1896 let init_vy = 0.1 * (-60.0_f64).to_radians().sin();
1897 assert!(
1898 first.vel[1] > 0.0,
1899 "pBounce should reverse downward Y velocity (got vy={})",
1900 first.vel[1]
1901 );
1902 assert!(
1903 (first.vel[1] - (-init_vy * 0.8)).abs() < 1e-4,
1904 "expected reflected vy={}, got {}",
1905 -init_vy * 0.8,
1906 first.vel[1]
1907 );
1908 assert!(
1909 (first.vel[0] - init_vx * 0.75).abs() < 1e-4,
1910 "expected friction-damped vx={}, got {}",
1911 init_vx * 0.75,
1912 first.vel[0]
1913 );
1914 assert!(first.spin_z.abs() > 0.5, "expected Spin impulse on bounce");
1915 assert!(first.pos[1] > 0.0, "bounced particle should be above floor y=0");
1916 }
15411917}
crates/engine/src/scene3d/collect.rs+389-60
......@@ -1,5 +1,6 @@
11//! 3D scene graph traversal, material resolution, and 3D transform evaluation.
22
3use super::fbx::load_mesh_cached;
34use super::math::{
45 mat4_identity, mat4_mul, mat4_rot_x, mat4_rot_y, mat4_rot_z, mat4_scale, mat4_translate,
56};
......@@ -287,19 +288,7 @@ fn collect_scene_inner(
287288 .and_then(|s| comp.find_node(s))
288289 });
289290 let mat = resolve_material(comp, mat_node, time, expr);
290 meshes.push(MeshInstance {
291 world,
292 shape: ShapeKind::ImagePlane,
293 material_node: mat.tex_node,
294 text3d: None,
295 diffuse_col: mat.diffuse_col,
296 specular_col: mat.specular_col,
297 specular_intensity: mat.specular_intensity,
298 specular_exponent: mat.specular_exponent,
299 affected_by_lights: ovr.affected_by_lights.unwrap_or(true),
300 flip_normals: ovr.flip_normals,
301 displace: ovr.displace.clone(),
302 });
291 meshes.push(make_mesh_instance(world, ShapeKind::ImagePlane, mat, None, ovr));
303292 }
304293 "Shape3D" => {
305294 let shape_name = node.static_str("Shape").unwrap_or("SurfacePlaneInputs");
......@@ -354,19 +343,79 @@ fn collect_scene_inner(
354343 comp.eval_number(node, "MtlStdInputs.Diffuse.Opacity", time, 1.0, expr) as f32,
355344 ];
356345 }
357 meshes.push(MeshInstance {
358 world,
359 shape,
360 material_node: mat.tex_node,
361 text3d: None,
362 diffuse_col: mat.diffuse_col,
363 specular_col: mat.specular_col,
364 specular_intensity: mat.specular_intensity,
365 specular_exponent: mat.specular_exponent,
366 affected_by_lights: ovr.affected_by_lights.unwrap_or(true),
367 flip_normals: ovr.flip_normals,
368 displace: ovr.displace.clone(),
346 meshes.push(make_mesh_instance(world, shape, mat, None, ovr));
347 }
348 "Cube3D" => {
349 let sz = comp.eval_number(node, "SurfaceCubeInputs.Size", time, 1.0, expr);
350 let shape = ShapeKind::Cube {
351 width: comp.eval_number(node, "SurfaceCubeInputs.Width", time, sz, expr) as f32,
352 height: comp.eval_number(node, "SurfaceCubeInputs.Height", time, sz, expr) as f32,
353 depth: comp.eval_number(node, "SurfaceCubeInputs.Depth", time, sz, expr) as f32,
354 };
355 let mat_node = ovr.material_override.or_else(|| {
356 [
357 "MaterialInput",
358 "FrontMaterialInput",
359 "BackMaterialInput",
360 "RightMaterialInput",
361 "LeftMaterialInput",
362 "TopMaterialInput",
363 "BottomMaterialInput",
364 ]
365 .iter()
366 .find_map(|k| node.connected_node(k))
367 .and_then(|s| comp.find_node(s))
369368 });
369 let mut mat = resolve_material(comp, mat_node, time, expr);
370 if mat_node.is_none() {
371 let r_def = comp.eval_number(node, "Front.MtlStdInputs.Diffuse.Color.Red", time, 1.0, expr);
372 let g_def = comp.eval_number(node, "Front.MtlStdInputs.Diffuse.Color.Green", time, 1.0, expr);
373 let b_def = comp.eval_number(node, "Front.MtlStdInputs.Diffuse.Color.Blue", time, 1.0, expr);
374 let a_def = comp.eval_number(node, "Front.MtlStdInputs.Diffuse.Opacity", time, 1.0, expr);
375 mat.diffuse_col = [
376 comp.eval_number(node, "MtlStdInputs.Diffuse.Color.Red", time, r_def, expr) as f32,
377 comp.eval_number(node, "MtlStdInputs.Diffuse.Color.Green", time, g_def, expr) as f32,
378 comp.eval_number(node, "MtlStdInputs.Diffuse.Color.Blue", time, b_def, expr) as f32,
379 comp.eval_number(node, "MtlStdInputs.Diffuse.Opacity", time, a_def, expr) as f32,
380 ];
381 }
382 meshes.push(make_mesh_instance(world, shape, mat, None, ovr));
383 if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) {
384 collect_scene_inner(comp, src_id, time, expr, world, render_aspect, ovr, cameras, meshes, lights, depth + 1);
385 }
386 }
387 "SurfaceFBXMesh" => {
388 let import_file = node.static_str("ImportFile").unwrap_or("");
389 let obj_name = node.static_str("ObjName");
390 let scale_units = comp.eval_number(node, "ScaleFileUnitsBy", time, 1.0, expr) as f32;
391 let verts = load_mesh_cached(import_file, comp.path.as_deref(), obj_name, scale_units);
392 let shape = ShapeKind::CustomMesh(verts);
393 let mat_node = ovr.material_override.or_else(|| {
394 node.connected_node("MaterialInput")
395 .or_else(|| {
396 let mut slots: Vec<&String> = node
397 .inputs
398 .keys()
399 .filter(|k| k.starts_with("Materials."))
400 .collect();
401 slots.sort();
402 slots.into_iter().find_map(|k| node.connected_node(k))
403 })
404 .and_then(|s| comp.find_node(s))
405 });
406 let mut mat = resolve_material(comp, mat_node, time, expr);
407 if mat_node.is_none() {
408 mat.diffuse_col = [
409 comp.eval_number(node, "MtlStdInputs.Diffuse.Color.Red", time, 1.0, expr) as f32,
410 comp.eval_number(node, "MtlStdInputs.Diffuse.Color.Green", time, 1.0, expr) as f32,
411 comp.eval_number(node, "MtlStdInputs.Diffuse.Color.Blue", time, 1.0, expr) as f32,
412 comp.eval_number(node, "MtlStdInputs.Diffuse.Opacity", time, 1.0, expr) as f32,
413 ];
414 }
415 meshes.push(make_mesh_instance(world, shape, mat, None, ovr));
416 if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) {
417 collect_scene_inner(comp, src_id, time, expr, world, render_aspect, ovr, cameras, meshes, lights, depth + 1);
418 }
370419 }
371420 "Text3D" => {
372421 let ext_depth = comp.eval_number(node, "Extrusion.ExtrusionDepth", time, 0.0, expr) as f32;
......@@ -379,24 +428,13 @@ fn collect_scene_inner(
379428 mat.diffuse_col = [1.0, 1.0, 1.0, 1.0];
380429 }
381430 // Text3D maps 1.0 vertical unit to the text frame height (width = 2.0 * height for 2:1 plate)
382 meshes.push(MeshInstance {
383 world,
384 shape: ShapeKind::TextPlate {
385 width: 4.0,
386 height: 2.0,
387 depth: ext_depth,
388 slices: if ext_depth.abs() > 1e-4 { 8 } else { 1 },
389 },
390 material_node: mat.tex_node,
391 text3d: Some(Text3DSpec { node_id }),
392 diffuse_col: mat.diffuse_col,
393 specular_col: mat.specular_col,
394 specular_intensity: mat.specular_intensity,
395 specular_exponent: mat.specular_exponent,
396 affected_by_lights: ovr.affected_by_lights.unwrap_or(true),
397 flip_normals: ovr.flip_normals,
398 displace: ovr.displace.clone(),
399 });
431 let shape = ShapeKind::TextPlate {
432 width: 4.0,
433 height: 2.0,
434 depth: ext_depth,
435 slices: if ext_depth.abs() > 1e-4 { 8 } else { 1 },
436 };
437 meshes.push(make_mesh_instance(world, shape, mat, Some(Text3DSpec { node_id }), ovr));
400438 }
401439 "MacroOperator" | "GroupOperator" => {
402440 if let Some(out_id) = node.macro_output {
......@@ -413,23 +451,130 @@ struct ResolvedMaterial {
413451 specular_col: [f32; 3],
414452 specular_intensity: f32,
415453 specular_exponent: f32,
454 uv_offset: [f32; 2],
455 uv_scale: [f32; 2],
456 uv_rot: f32,
457 uv_wrap: u32,
458 bump_scale: f32,
459 bump_mode: u32,
460}
461
462impl Default for ResolvedMaterial {
463 fn default() -> Self {
464 Self {
465 tex_node: None,
466 diffuse_col: [1.0, 1.0, 1.0, 1.0],
467 specular_col: [1.0, 1.0, 1.0],
468 specular_intensity: 0.15,
469 specular_exponent: 25.0,
470 uv_offset: [0.0, 0.0],
471 uv_scale: [1.0, 1.0],
472 uv_rot: 0.0,
473 uv_wrap: 0,
474 bump_scale: 0.0,
475 bump_mode: 0,
476 }
477 }
416478}
417479
418/// Resolves a 3D material input (either a 2D image node, `Texture2DOperator`, or a Fusion 3D
419/// material like `MtlBlinn` / `MtlCookTorrance` / `MtlPhong`).
480fn make_mesh_instance(
481 world: Mat4,
482 shape: ShapeKind,
483 mat: ResolvedMaterial,
484 text3d: Option<Text3DSpec>,
485 ovr: &SceneOverrides,
486) -> MeshInstance {
487 let has_fx = mat.uv_offset[0].abs() > 1e-6
488 || mat.uv_offset[1].abs() > 1e-6
489 || (mat.uv_scale[0] - 1.0).abs() > 1e-6
490 || (mat.uv_scale[1] - 1.0).abs() > 1e-6
491 || mat.uv_rot.abs() > 1e-6
492 || mat.uv_wrap != 0
493 || mat.bump_scale.abs() > 1e-6;
494 let wrapped_shape = if has_fx {
495 ShapeKind::WithMaterialFx {
496 inner: Box::new(shape),
497 uv_offset: mat.uv_offset,
498 uv_scale: mat.uv_scale,
499 uv_rot: mat.uv_rot,
500 uv_wrap: mat.uv_wrap,
501 bump_scale: mat.bump_scale,
502 bump_mode: mat.bump_mode,
503 }
504 } else {
505 shape
506 };
507 MeshInstance {
508 world,
509 shape: wrapped_shape,
510 material_node: mat.tex_node,
511 text3d,
512 diffuse_col: mat.diffuse_col,
513 specular_col: mat.specular_col,
514 specular_intensity: mat.specular_intensity,
515 specular_exponent: mat.specular_exponent,
516 affected_by_lights: ovr.affected_by_lights.unwrap_or(true),
517 flip_normals: ovr.flip_normals,
518 displace: ovr.displace.clone(),
519 uv_offset: mat.uv_offset,
520 uv_scale: mat.uv_scale,
521 uv_rot: mat.uv_rot,
522 uv_wrap: mat.uv_wrap,
523 bump_scale: mat.bump_scale,
524 bump_mode: mat.bump_mode,
525 }
526}
527
528fn eval_first_present(comp: &Comp, node: &Node, keys: &[&str], time: f64, default: f64, expr: &ExprEngine) -> f32 {
529 for &k in keys {
530 if node.inputs.contains_key(k) {
531 return comp.eval_number(node, k, time, default, expr) as f32;
532 }
533 }
534 default as f32
535}
536
537fn parse_wrap_mode(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> Option<u32> {
538 if let Some(s) = node.static_str("WrapMode") {
539 return Some(match s {
540 "Wrap" | "Repeat" => 1,
541 "Mirror" => 2,
542 _ => 0,
543 });
544 }
545 if node.inputs.contains_key("WrapMode") {
546 let v = comp.eval_number(node, "WrapMode", time, 0.0, expr).round() as i32;
547 return Some(match v {
548 1 => 1,
549 2 => 2,
550 _ => 0,
551 });
552 }
553 None
554}
555
556/// Resolves a 3D material input (`Texture2DOperator`, `TextureTransformOperator`, `BumpMap`,
557/// `MtlBlinn`, `MtlCookTorrance`, `MtlPhong`, or a direct 2D image node).
420558fn resolve_material(
421559 comp: &Comp,
422560 mat_node: Option<NodeId>,
423561 time: f64,
424562 expr: &ExprEngine,
425563) -> ResolvedMaterial {
426 let default_mat = ResolvedMaterial {
427 tex_node: None,
428 diffuse_col: [1.0, 1.0, 1.0, 1.0],
429 specular_col: [1.0, 1.0, 1.0],
430 specular_intensity: 0.15,
431 specular_exponent: 25.0,
432 };
564 resolve_material_inner(comp, mat_node, time, expr, 0)
565}
566
567fn resolve_material_inner(
568 comp: &Comp,
569 mat_node: Option<NodeId>,
570 time: f64,
571 expr: &ExprEngine,
572 depth: usize,
573) -> ResolvedMaterial {
574 let default_mat = ResolvedMaterial::default();
575 if depth > 16 {
576 return default_mat;
577 }
433578 let Some(mid) = mat_node else {
434579 return default_mat;
435580 };
......@@ -437,22 +582,69 @@ fn resolve_material(
437582 match n.kind.as_str() {
438583 "Texture2DOperator" => {
439584 let tex_src = n.connected_node("Input").and_then(|s| comp.find_node(s));
585 let uv_wrap = parse_wrap_mode(comp, n, time, expr).unwrap_or(0);
440586 ResolvedMaterial {
441587 tex_node: tex_src,
588 uv_wrap,
589 ..default_mat
590 }
591 }
592 "TextureTransformOperator" => {
593 let inner_id = n
594 .connected_node("MaterialInput")
595 .or_else(|| n.connected_node("Input"))
596 .and_then(|s| comp.find_node(s));
597 let mut mat = resolve_material_inner(comp, inner_id, time, expr, depth + 1);
598 let tx = eval_first_present(comp, n, &["TranslationOffset.X", "Translation.U", "Translation.X"], time, 0.0, expr);
599 let ty = eval_first_present(comp, n, &["TranslationOffset.Y", "Translation.V", "Translation.Y"], time, 0.0, expr);
600 let sx = eval_first_present(comp, n, &["Scale.X", "Scale.U"], time, 1.0, expr);
601 let sy = eval_first_present(comp, n, &["Scale.Y", "Scale.V"], time, 1.0, expr);
602 let rot_deg = eval_first_present(
603 comp,
604 n,
605 &["Rotation.Z", "RotationOffset", "Rotation.W", "Rotation.U"],
606 time,
607 0.0,
608 expr,
609 );
610 mat.uv_offset = [mat.uv_offset[0] + tx, mat.uv_offset[1] + ty];
611 mat.uv_scale = [mat.uv_scale[0] * sx, mat.uv_scale[1] * sy];
612 mat.uv_rot += rot_deg.to_radians();
613 if let Some(w) = parse_wrap_mode(comp, n, time, expr) {
614 mat.uv_wrap = w;
615 }
616 mat
617 }
618 "BumpMap" => {
619 let src = n.connected_node("Input").and_then(|s| comp.find_node(s));
620 let height_scale = comp.eval_number(n, "HeightScale", time, 1.0, expr) as f32;
621 let bump_mode = if let Some(s) = n.static_str("SourceImageType") {
622 if s.eq_ignore_ascii_case("NormalMap") || s == "1" { 1 } else { 0 }
623 } else {
624 comp.eval_number(n, "SourceImageType", time, 0.0, expr)
625 .round()
626 .clamp(0.0, 1.0) as u32
627 };
628 let uv_wrap = parse_wrap_mode(comp, n, time, expr).unwrap_or(0);
629 ResolvedMaterial {
630 tex_node: src,
631 uv_wrap,
632 bump_scale: height_scale,
633 bump_mode,
442634 ..default_mat
443635 }
444636 }
445637 "MtlBlinn" | "MtlCookTorrance" | "MtlPhong" => {
446 let mut diff_tex = n
638 let diff_in = n
447639 .connected_node("Diffuse.Color.Material")
448640 .or_else(|| n.connected_node("MaterialInput"))
449641 .and_then(|s| comp.find_node(s));
450 // Unwrap Texture2DOperator if feeding Diffuse.Color.Material
451 if let Some(tid) = diff_tex {
452 if comp.node(tid).kind == "Texture2DOperator" {
453 diff_tex = comp.node(tid).connected_node("Input").and_then(|s| comp.find_node(s));
454 }
455 }
642 let diff_mat = resolve_material_inner(comp, diff_in, time, expr, depth + 1);
643 let bump_in = n
644 .connected_node("Bumpmap.Material")
645 .and_then(|s| comp.find_node(s));
646 let bump_mat = bump_in.map(|bid| resolve_material_inner(comp, Some(bid), time, expr, depth + 1));
647
456648 let col = [
457649 comp.eval_number(n, "Diffuse.Color.Red", time, 1.0, expr) as f32,
458650 comp.eval_number(n, "Diffuse.Color.Green", time, 1.0, expr) as f32,
......@@ -471,12 +663,39 @@ fn resolve_material(
471663 } else {
472664 (comp.eval_number(n, "Specular.Exponent", time, 25.0, expr).max(1.0) as f32, 1.0)
473665 };
666
667 let mut tex_node = diff_mat.tex_node;
668 let mut uv_offset = diff_mat.uv_offset;
669 let mut uv_scale = diff_mat.uv_scale;
670 let mut uv_rot = diff_mat.uv_rot;
671 let mut uv_wrap = diff_mat.uv_wrap;
672 let mut bump_scale = diff_mat.bump_scale;
673 let mut bump_mode = diff_mat.bump_mode;
674
675 if let Some(bm) = bump_mat {
676 bump_scale = if bm.bump_scale.abs() > 1e-6 { bm.bump_scale } else { 1.0 };
677 bump_mode = bm.bump_mode;
678 if tex_node.is_none() {
679 tex_node = bm.tex_node;
680 uv_offset = bm.uv_offset;
681 uv_scale = bm.uv_scale;
682 uv_rot = bm.uv_rot;
683 uv_wrap = bm.uv_wrap;
684 }
685 }
686
474687 ResolvedMaterial {
475 tex_node: diff_tex,
688 tex_node,
476689 diffuse_col: col,
477690 specular_col: spec_col,
478691 specular_intensity: spec_int.clamp(0.0, 4.0) * spec_gain,
479692 specular_exponent: spec_exp,
693 uv_offset,
694 uv_scale,
695 uv_rot,
696 uv_wrap,
697 bump_scale,
698 bump_mode,
480699 }
481700 }
482701 _ => ResolvedMaterial {
......@@ -689,4 +908,114 @@ mod tests {
689908 assert_eq!(lights.spots.len(), 1);
690909 assert!(lights.spots[0].cos_inner > lights.spots[0].cos_outer);
691910 }
911
912 #[test]
913 fn test_collect_fbx_cube_tex_transform_and_bump() {
914 let src = r#"Composition {
915 CurrentTime = 0,
916 RenderRange = { 0, 10 },
917 GlobalRange = { 0, 10 },
918 Tools = ordered() {
919 BG1 = Background {
920 Inputs = {
921 Width = Input { Value = 64, },
922 Height = Input { Value = 64, },
923 },
924 },
925 Bump1 = BumpMap {
926 Inputs = {
927 Input = Input { SourceOp = "BG1", Source = "Output", },
928 HeightScale = Input { Value = 4.5, },
929 SourceImageType = Input { Value = 1, },
930 WrapMode = Input { Value = FuID { "Wrap" }, },
931 },
932 },
933 TexXf = TextureTransformOperator {
934 Inputs = {
935 MaterialInput = Input { SourceOp = "Bump1", Source = "MaterialOutput", },
936 ["TranslationOffset.X"] = Input { Value = 0.25, },
937 ["TranslationOffset.Y"] = Input { Value = -0.5, },
938 ["Scale.U"] = Input { Value = 2.0, },
939 ["Scale.V"] = Input { Value = 3.0, },
940 ["Rotation.Z"] = Input { Value = 90.0, },
941 },
942 },
943 BlinnBump = MtlBlinn {
944 Inputs = {
945 ["Diffuse.Color.Red"] = Input { Value = 0.7, },
946 ["Bumpmap.Material"] = Input { SourceOp = "TexXf", Source = "MaterialOutput", },
947 },
948 },
949 CubeNode = Cube3D {
950 Inputs = {
951 ["SurfaceCubeInputs.Size"] = Input { Value = 2.0, },
952 ["SurfaceCubeInputs.Height"] = Input { Value = 4.0, },
953 ["Transform3DOp.Translate.Y"] = Input { Value = 1.5, },
954 MaterialInput = Input { SourceOp = "BlinnBump", Source = "MaterialOutput", },
955 },
956 },
957 FbxNode = SurfaceFBXMesh {
958 Inputs = {
959 ImportFile = Input { Value = "/does/not/exist/model.fbx", },
960 ObjName = Input { Value = "HeroMesh", },
961 ScaleFileUnitsBy = Input { Value = 0.01, },
962 ["Transform3DOp.Translate.X"] = Input { Value = -2.0, },
963 ["Materials.Mat0_mat0"] = Input { SourceOp = "TexXf", Source = "MaterialOutput", },
964 },
965 },
966 Merge1 = Merge3D {
967 Inputs = {
968 SceneInput1 = Input { SourceOp = "CubeNode", Source = "Output", },
969 SceneInput2 = Input { SourceOp = "FbxNode", Source = "Output", },
970 },
971 },
972 },
973 }"#;
974 let comp = Comp::from_fusion_str(src).expect("parse comp");
975 let expr = ExprEngine::new();
976 let merge_id = comp.find_node("Merge1").expect("Merge1");
977 let bg_id = comp.find_node("BG1").expect("BG1");
978 let mut cams = Vec::new();
979 let mut meshes = Vec::new();
980 let mut lights = SceneLights::default();
981 collect_scene(
982 &comp,
983 merge_id,
984 0.0,
985 &expr,
986 mat4_identity(),
987 16.0 / 9.0,
988 &mut cams,
989 &mut meshes,
990 &mut lights,
991 0,
992 );
993 assert_eq!(meshes.len(), 2);
994
995 // Cube3D with Blinn + Bumpmap (TextureTransformOperator -> BumpMap)
996 let cube = &meshes[0];
997 assert!(matches!(
998 cube.shape.base_shape(),
999 ShapeKind::Cube { width, height, depth }
1000 if (*width - 2.0).abs() < 1e-4 && (*height - 4.0).abs() < 1e-4 && (*depth - 2.0).abs() < 1e-4
1001 ));
1002 assert!((cube.world[13] - 1.5).abs() < 1e-4);
1003 assert_eq!(cube.material_node, Some(bg_id));
1004 assert!((cube.diffuse_col[0] - 0.7).abs() < 1e-4);
1005 assert!((cube.bump_scale - 4.5).abs() < 1e-4);
1006 assert_eq!(cube.bump_mode, 1);
1007 assert!((cube.uv_offset[0] - 0.25).abs() < 1e-4);
1008 assert!((cube.uv_offset[1] + 0.5).abs() < 1e-4);
1009 assert!((cube.uv_scale[0] - 2.0).abs() < 1e-4);
1010 assert!((cube.uv_scale[1] - 3.0).abs() < 1e-4);
1011 assert!((cube.uv_rot - std::f32::consts::FRAC_PI_2).abs() < 1e-4);
1012 assert_eq!(cube.uv_wrap, 1);
1013
1014 // SurfaceFBXMesh fallback unit box + Materials.* slot resolution
1015 let fbx = &meshes[1];
1016 assert!(matches!(fbx.shape.base_shape(), ShapeKind::CustomMesh(v) if v.len() == 36));
1017 assert!((fbx.world[12] + 2.0).abs() < 1e-4);
1018 assert_eq!(fbx.material_node, Some(bg_id));
1019 assert!((fbx.bump_scale - 4.5).abs() < 1e-4);
1020 }
6921021}
crates/engine/src/scene3d/fbx.rs created+1515
......@@ -0,0 +1,1515 @@
1//! Pure-Rust panic-free mesh loader for Fusion's `SurfaceFBXMesh` node.
2//!
3//! Supports:
4//! - Wavefront `.obj` (`v`, `vn`, `vt`, `o`/`g`, `f` with fan triangulation)
5//! - ASCII FBX (`Vertices:`, `PolygonVertexIndex:`, `Normals:`, `UV:`)
6//! - Binary FBX (`Kaydara FBX Binary \0`, v7100–v7700+, raw & zlib-compressed arrays)
7//!
8//! Recomputes smooth vertex normals when absent, applies `ScaleFileUnitsBy`,
9//! caches loaded meshes by `(path, obj_name, scale)`, and falls back gracefully
10//! to a unit bounding-box placeholder mesh if the file is missing or unreadable.
11
12use std::collections::HashMap;
13use std::path::{Path, PathBuf};
14use std::sync::{Arc, Mutex, OnceLock};
15
16use super::shader::Vertex3D;
17
18const FBX_BINARY_MAGIC: &[u8; 21] = b"Kaydara FBX Binary \0";
19const MAX_CACHE_ENTRIES: usize = 256;
20const MAX_FBX_DEPTH: usize = 32;
21const MAX_DECOMPRESS_BYTES: usize = 64 * 1024 * 1024;
22const MAX_TRIANGLES: usize = 500_000;
23
24type MeshCacheKey = (String, String, u32);
25static MESH_CACHE: OnceLock<Mutex<HashMap<MeshCacheKey, Arc<Vec<Vertex3D>>>>> = OnceLock::new();
26
27/// 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.
29pub(super) fn load_mesh_cached(
30 raw_path: &str,
31 comp_path: Option<&Path>,
32 obj_name: Option<&str>,
33 scale_units: f32,
34) -> Arc<Vec<Vertex3D>> {
35 let scale = if scale_units.is_finite() && scale_units.abs() > 1e-7 {
36 scale_units
37 } else {
38 1.0
39 };
40 let resolved = resolve_import_path(raw_path, comp_path);
41 let cache_path = resolved
42 .as_ref()
43 .map(|p| p.to_string_lossy().into_owned())
44 .unwrap_or_else(|| raw_path.to_string());
45 let key = (
46 cache_path,
47 obj_name.unwrap_or("").to_string(),
48 scale.to_bits(),
49 );
50
51 let cache = MESH_CACHE.get_or_init(|| Mutex::new(HashMap::new()));
52 if let Ok(guard) = cache.lock() {
53 if let Some(hit) = guard.get(&key) {
54 return Arc::clone(hit);
55 }
56 }
57
58 let loaded = resolved
59 .and_then(|p| {
60 let ext = p.extension().and_then(|e| e.to_str()).map(|s| s.to_ascii_lowercase());
61 let bytes = std::fs::read(&p).ok()?;
62 parse_mesh_bytes(&bytes, ext.as_deref(), obj_name, scale)
63 })
64 .filter(|v| !v.is_empty())
65 .unwrap_or_else(unit_box_placeholder);
66
67 let arc = Arc::new(loaded);
68 if let Ok(mut guard) = cache.lock() {
69 if guard.len() >= MAX_CACHE_ENTRIES {
70 guard.clear();
71 }
72 guard.insert(key, Arc::clone(&arc));
73 }
74 arc
75}
76
77/// Resolves a Fusion `ImportFile` path (supporting `comp:` prefix and relative paths).
78fn resolve_import_path(raw_path: &str, comp_path: Option<&Path>) -> Option<PathBuf> {
79 let trimmed = raw_path.trim();
80 if trimmed.is_empty() {
81 return None;
82 }
83 let normalized = trimmed.replace('\\', "/");
84 let comp_dir = comp_path.and_then(|p| p.parent());
85
86 if let Some(rest) = normalized
87 .strip_prefix("comp:")
88 .or_else(|| normalized.strip_prefix("Comp:"))
89 .or_else(|| normalized.strip_prefix("COMP:"))
90 {
91 let rel = rest.trim_start_matches('/');
92 if let Some(dir) = comp_dir {
93 let candidate = dir.join(rel);
94 if candidate.exists() {
95 return Some(candidate);
96 }
97 return Some(candidate);
98 }
99 return Some(PathBuf::from(rel));
100 }
101
102 let p = PathBuf::from(&normalized);
103 if p.is_absolute() {
104 if p.exists() {
105 return Some(p);
106 }
107 // Fallback: check filename alongside comp file if moved across machines
108 if let (Some(dir), Some(fname)) = (comp_dir, p.file_name()) {
109 let beside = dir.join(fname);
110 if beside.exists() {
111 return Some(beside);
112 }
113 }
114 return Some(p);
115 }
116
117 if let Some(dir) = comp_dir {
118 let candidate = dir.join(&p);
119 if candidate.exists() {
120 return Some(candidate);
121 }
122 }
123 Some(p)
124}
125
126/// Parses OBJ, ASCII FBX, or Binary FBX mesh bytes into an unindexed triangle list of `Vertex3D`.
127pub(super) fn parse_mesh_bytes(
128 bytes: &[u8],
129 ext_hint: Option<&str>,
130 obj_name: Option<&str>,
131 scale_units: f32,
132) -> Option<Vec<Vertex3D>> {
133 if bytes.is_empty() {
134 return None;
135 }
136 let mut verts = if bytes.len() >= FBX_BINARY_MAGIC.len() && &bytes[..FBX_BINARY_MAGIC.len()] == FBX_BINARY_MAGIC {
137 parse_binary_fbx(bytes, obj_name)?
138 } else {
139 let text = std::str::from_utf8(bytes).ok()?;
140 let is_obj = matches!(ext_hint, Some("obj"))
141 || (!text.contains("PolygonVertexIndex:")
142 && !text.contains("FBXHeaderExtension")
143 && text.lines().any(|l| {
144 let t = l.trim_start();
145 t.starts_with("v ") || t.starts_with("f ")
146 }));
147 if is_obj {
148 parse_obj(text, obj_name)?
149 } else {
150 parse_ascii_fbx(text, obj_name)?
151 }
152 };
153
154 if verts.is_empty() {
155 return None;
156 }
157
158 let scale = if scale_units.is_finite() && scale_units.abs() > 1e-7 {
159 scale_units
160 } else {
161 1.0
162 };
163 if (scale - 1.0).abs() > 1e-6 {
164 for v in &mut verts {
165 v.pos[0] *= scale;
166 v.pos[1] *= scale;
167 v.pos[2] *= scale;
168 }
169 }
170 Some(verts)
171}
172
173/// Returns a unit `[-0.5, 0.5]^3` bounding-box placeholder mesh (36 vertices / 12 triangles).
174pub(super) fn unit_box_placeholder() -> Vec<Vertex3D> {
175 let h = 0.5_f32;
176 let faces: [([f32; 3], [[f32; 3]; 4]); 6] = [
177 ([0.0, 0.0, 1.0], [[-h, h, h], [-h, -h, h], [h, -h, h], [h, h, h]]),
178 ([0.0, 0.0, -1.0], [[h, h, -h], [h, -h, -h], [-h, -h, -h], [-h, h, -h]]),
179 ([1.0, 0.0, 0.0], [[h, h, h], [h, -h, h], [h, -h, -h], [h, h, -h]]),
180 ([-1.0, 0.0, 0.0], [[-h, h, -h], [-h, -h, -h], [-h, -h, h], [-h, h, h]]),
181 ([0.0, 1.0, 0.0], [[-h, h, -h], [-h, h, h], [h, h, h], [h, h, -h]]),
182 ([0.0, -1.0, 0.0], [[-h, -h, h], [-h, -h, -h], [h, -h, -h], [h, -h, h]]),
183 ];
184 let uvs = [[0.0, 0.0], [0.0, 1.0], [1.0, 1.0], [1.0, 0.0]];
185 let mut verts = Vec::with_capacity(36);
186 for (n, c) in faces {
187 let q = [
188 Vertex3D { pos: c[0], normal: n, uv: uvs[0] },
189 Vertex3D { pos: c[1], normal: n, uv: uvs[1] },
190 Vertex3D { pos: c[2], normal: n, uv: uvs[2] },
191 Vertex3D { pos: c[3], normal: n, uv: uvs[3] },
192 ];
193 verts.extend_from_slice(&[q[0], q[1], q[2], q[0], q[2], q[3]]);
194 }
195 verts
196}
197
198// ---------------------------------------------------------------------------
199// Wavefront OBJ parser
200// ---------------------------------------------------------------------------
201
202fn parse_obj(text: &str, obj_name: Option<&str>) -> Option<Vec<Vertex3D>> {
203 let mut positions: Vec<[f32; 3]> = Vec::new();
204 let mut normals: Vec<[f32; 3]> = Vec::new();
205 let mut uvs: Vec<[f32; 2]> = Vec::new();
206 let mut all_verts: Vec<Vertex3D> = Vec::new();
207 let mut named_verts: Vec<Vertex3D> = Vec::new();
208 let mut has_any_normal = false;
209 let mut current_obj = String::new();
210 let target = obj_name.map(str::trim).filter(|s| !s.is_empty());
211
212 let resolve_idx = |raw: i32, len: usize| -> Option<usize> {
213 if raw > 0 {
214 let idx = (raw - 1) as usize;
215 (idx < len).then_some(idx)
216 } else if raw < 0 {
217 let offset = raw.unsigned_abs() as usize;
218 len.checked_sub(offset)
219 } else {
220 None
221 }
222 };
223
224 for raw_line in text.lines() {
225 let line = raw_line.split('#').next().unwrap_or("").trim();
226 if line.is_empty() {
227 continue;
228 }
229 let mut parts = line.split_whitespace();
230 let Some(tag) = parts.next() else { continue };
231 match tag {
232 "o" | "g" => {
233 current_obj = parts.next().unwrap_or("").to_string();
234 }
235 "v" => {
236 let (Some(x), Some(y), Some(z)) = (
237 parts.next().and_then(|s| s.parse::<f32>().ok()),
238 parts.next().and_then(|s| s.parse::<f32>().ok()),
239 parts.next().and_then(|s| s.parse::<f32>().ok()),
240 ) else {
241 continue;
242 };
243 positions.push([x, y, z]);
244 }
245 "vn" => {
246 let (Some(x), Some(y), Some(z)) = (
247 parts.next().and_then(|s| s.parse::<f32>().ok()),
248 parts.next().and_then(|s| s.parse::<f32>().ok()),
249 parts.next().and_then(|s| s.parse::<f32>().ok()),
250 ) else {
251 continue;
252 };
253 normals.push(normalize3([x, y, z]));
254 }
255 "vt" => {
256 let (Some(u), Some(v)) = (
257 parts.next().and_then(|s| s.parse::<f32>().ok()),
258 parts.next().and_then(|s| s.parse::<f32>().ok()),
259 ) else {
260 continue;
261 };
262 uvs.push([u, 1.0 - v]);
263 }
264 "f" => {
265 if all_verts.len() / 3 >= MAX_TRIANGLES {
266 break;
267 }
268 let mut face: Vec<Vertex3D> = Vec::new();
269 for tok in parts {
270 let mut segs = tok.split('/');
271 let Some(vi) = segs
272 .next()
273 .and_then(|s| s.parse::<i32>().ok())
274 .and_then(|i| resolve_idx(i, positions.len()))
275 else {
276 continue;
277 };
278 let ti = segs
279 .next()
280 .filter(|s| !s.is_empty())
281 .and_then(|s| s.parse::<i32>().ok())
282 .and_then(|i| resolve_idx(i, uvs.len()));
283 let ni = segs
284 .next()
285 .filter(|s| !s.is_empty())
286 .and_then(|s| s.parse::<i32>().ok())
287 .and_then(|i| resolve_idx(i, normals.len()));
288 let normal = if let Some(idx) = ni {
289 has_any_normal = true;
290 normals[idx]
291 } else {
292 [0.0, 0.0, 0.0]
293 };
294 let uv = ti.map(|idx| uvs[idx]).unwrap_or([0.0, 0.0]);
295 face.push(Vertex3D {
296 pos: positions[vi],
297 normal,
298 uv,
299 });
300 }
301 if face.len() >= 3 {
302 let matches_target = target.is_some_and(|t| {
303 current_obj.eq_ignore_ascii_case(t)
304 });
305 for i in 1..(face.len() - 1) {
306 let tri = [face[0], face[i], face[i + 1]];
307 all_verts.extend_from_slice(&tri);
308 if matches_target {
309 named_verts.extend_from_slice(&tri);
310 }
311 }
312 }
313 }
314 _ => {}
315 }
316 }
317
318 let mut out = if !named_verts.is_empty() {
319 named_verts
320 } else {
321 all_verts
322 };
323 if out.is_empty() {
324 return None;
325 }
326 if !has_any_normal || out.iter().any(|v| vec3_len_sq(v.normal) < 1e-8) {
327 recompute_smooth_normals(&mut out);
328 }
329 Some(out)
330}
331
332// ---------------------------------------------------------------------------
333// Shared FBX geometry assembly
334// ---------------------------------------------------------------------------
335
336#[derive(Default)]
337struct FbxGeometryData {
338 id: i64,
339 name: String,
340 vertices: Vec<f32>,
341 poly_indices: Vec<i32>,
342 normals: Vec<f32>,
343 normal_indices: Vec<i32>,
344 normal_mapping: String,
345 uvs: Vec<f32>,
346 uv_indices: Vec<i32>,
347 uv_mapping: String,
348}
349
350fn assemble_fbx_geometry(g: &FbxGeometryData, out: &mut Vec<Vertex3D>) {
351 let vert_count = g.vertices.len() / 3;
352 if vert_count == 0 || g.poly_indices.is_empty() {
353 return;
354 }
355
356 let norm_by_vert = g.normal_mapping.eq_ignore_ascii_case("ByVertice")
357 || g.normal_mapping.eq_ignore_ascii_case("ByControlPoint");
358 let uv_by_vert = g.uv_mapping.eq_ignore_ascii_case("ByVertice")
359 || g.uv_mapping.eq_ignore_ascii_case("ByControlPoint");
360
361 let mut poly: Vec<(usize, usize)> = Vec::new(); // (vertex_idx, poly_vert_cursor)
362 let mut any_missing_normal = g.normals.len() < 3;
363 let start_len = out.len();
364
365 for (pv_idx, &raw_idx) in g.poly_indices.iter().enumerate() {
366 let is_end = raw_idx < 0;
367 let vi = if is_end { !raw_idx } else { raw_idx };
368 if vi >= 0 && (vi as usize) < vert_count {
369 poly.push((vi as usize, pv_idx));
370 }
371 if is_end {
372 if poly.len() >= 3 && out.len() / 3 < MAX_TRIANGLES {
373 for i in 1..(poly.len() - 1) {
374 for &(v_idx, p_idx) in &[poly[0], poly[i], poly[i + 1]] {
375 let pos = [
376 g.vertices[v_idx * 3],
377 g.vertices[v_idx * 3 + 1],
378 g.vertices[v_idx * 3 + 2],
379 ];
380 let n_slot = if norm_by_vert { v_idx } else { p_idx };
381 let n_resolved = if !g.normal_indices.is_empty() {
382 g.normal_indices
383 .get(n_slot)
384 .copied()
385 .filter(|&idx| idx >= 0)
386 .map(|idx| idx as usize)
387 } else {
388 Some(n_slot)
389 };
390 let normal = if let Some(ni) = n_resolved {
391 if ni * 3 + 2 < g.normals.len() {
392 normalize3([
393 g.normals[ni * 3],
394 g.normals[ni * 3 + 1],
395 g.normals[ni * 3 + 2],
396 ])
397 } else {
398 any_missing_normal = true;
399 [0.0, 0.0, 0.0]
400 }
401 } else {
402 any_missing_normal = true;
403 [0.0, 0.0, 0.0]
404 };
405
406 let uv_slot = if uv_by_vert { v_idx } else { p_idx };
407 let uv_resolved = if !g.uv_indices.is_empty() {
408 g.uv_indices
409 .get(uv_slot)
410 .copied()
411 .filter(|&idx| idx >= 0)
412 .map(|idx| idx as usize)
413 } else {
414 Some(uv_slot)
415 };
416 let uv = if let Some(ti) = uv_resolved {
417 if ti * 2 + 1 < g.uvs.len() {
418 [g.uvs[ti * 2], 1.0 - g.uvs[ti * 2 + 1]]
419 } else {
420 [0.0, 0.0]
421 }
422 } else {
423 [0.0, 0.0]
424 };
425
426 out.push(Vertex3D { pos, normal, uv });
427 }
428 }
429 }
430 poly.clear();
431 }
432 }
433
434 if any_missing_normal && out.len() > start_len {
435 recompute_smooth_normals(&mut out[start_len..]);
436 }
437}
438
439// ---------------------------------------------------------------------------
440// ASCII FBX parser
441// ---------------------------------------------------------------------------
442
443fn parse_ascii_fbx(text: &str, obj_name: Option<&str>) -> Option<Vec<Vertex3D>> {
444 let mut geometries: Vec<FbxGeometryData> = Vec::new();
445
446 // Find each `Geometry:` block; if none exist (minimal buffer), parse whole text as one geometry.
447 let geom_positions: Vec<usize> = text
448 .match_indices("Geometry:")
449 .map(|(idx, _)| idx)
450 .collect();
451
452 if geom_positions.is_empty() {
453 let g = parse_ascii_fbx_geometry_slice("", text);
454 if !g.vertices.is_empty() && !g.poly_indices.is_empty() {
455 geometries.push(g);
456 }
457 } else {
458 for &start in &geom_positions {
459 let slice = &text[start..];
460 let Some(open_brace) = slice.find('{') else {
461 continue;
462 };
463 let header = &slice[..open_brace];
464 let name = extract_fbx_quoted_name(header);
465 let block_end = find_matching_brace(slice, open_brace).unwrap_or(slice.len());
466 let body = &slice[open_brace + 1..block_end];
467 let g = parse_ascii_fbx_geometry_slice(&name, body);
468 if !g.vertices.is_empty() && !g.poly_indices.is_empty() {
469 geometries.push(g);
470 }
471 }
472 }
473
474 if geometries.is_empty() {
475 return None;
476 }
477
478 let target = obj_name.map(str::trim).filter(|s| !s.is_empty());
479 let mut out = Vec::new();
480 if let Some(t) = target {
481 for g in &geometries {
482 if fbx_name_matches(&g.name, t) {
483 assemble_fbx_geometry(g, &mut out);
484 }
485 }
486 }
487 if out.is_empty() {
488 for g in &geometries {
489 assemble_fbx_geometry(g, &mut out);
490 }
491 }
492 (!out.is_empty()).then_some(out)
493}
494
495fn parse_ascii_fbx_geometry_slice(name: &str, body: &str) -> FbxGeometryData {
496 let mut g = FbxGeometryData {
497 name: name.to_string(),
498 ..Default::default()
499 };
500 if let Some(nums) = extract_ascii_fbx_f32_array(body, "Vertices:") {
501 g.vertices = nums;
502 }
503 if let Some(nums) = extract_ascii_fbx_i32_array(body, "PolygonVertexIndex:") {
504 g.poly_indices = nums;
505 }
506 if let Some(sub) = extract_ascii_fbx_block(body, "LayerElementNormal:") {
507 g.normal_mapping = extract_ascii_fbx_string_prop(sub, "MappingInformationType:").unwrap_or_default();
508 if let Some(nums) = extract_ascii_fbx_f32_array(sub, "Normals:") {
509 g.normals = nums;
510 }
511 if let Some(nums) = extract_ascii_fbx_i32_array(sub, "NormalsIndex:") {
512 g.normal_indices = nums;
513 }
514 } else if let Some(nums) = extract_ascii_fbx_f32_array(body, "Normals:") {
515 g.normals = nums;
516 g.normal_mapping = extract_ascii_fbx_string_prop(body, "MappingInformationType:").unwrap_or_default();
517 }
518 if let Some(sub) = extract_ascii_fbx_block(body, "LayerElementUV:") {
519 g.uv_mapping = extract_ascii_fbx_string_prop(sub, "MappingInformationType:").unwrap_or_default();
520 if let Some(nums) = extract_ascii_fbx_f32_array(sub, "UV:") {
521 g.uvs = nums;
522 }
523 if let Some(nums) = extract_ascii_fbx_i32_array(sub, "UVIndex:") {
524 g.uv_indices = nums;
525 }
526 } else if let Some(nums) = extract_ascii_fbx_f32_array(body, "UV:") {
527 g.uvs = nums;
528 }
529 g
530}
531
532fn find_matching_brace(s: &str, open_idx: usize) -> Option<usize> {
533 let mut depth = 0usize;
534 let mut in_str = false;
535 for (i, b) in s.bytes().enumerate().skip(open_idx) {
536 if b == b'"' {
537 in_str = !in_str;
538 continue;
539 }
540 if in_str {
541 continue;
542 }
543 if b == b'{' {
544 depth += 1;
545 } else if b == b'}' {
546 depth = depth.saturating_sub(1);
547 if depth == 0 {
548 return Some(i);
549 }
550 }
551 }
552 None
553}
554
555fn extract_ascii_fbx_block<'a>(body: &'a str, key: &str) -> Option<&'a str> {
556 let idx = body.find(key)?;
557 let slice = &body[idx..];
558 let open = slice.find('{')?;
559 let close = find_matching_brace(slice, open)?;
560 Some(&slice[open + 1..close])
561}
562
563fn extract_ascii_fbx_string_prop(body: &str, key: &str) -> Option<String> {
564 let idx = body.find(key)?;
565 let rest = &body[idx + key.len()..];
566 let line = rest.lines().next()?;
567 let q1 = line.find('"')?;
568 let after = &line[q1 + 1..];
569 let q2 = after.find('"')?;
570 Some(after[..q2].to_string())
571}
572
573fn extract_ascii_fbx_array_str<'a>(body: &'a str, key: &str) -> Option<&'a str> {
574 let idx = body.find(key)?;
575 let rest = body[idx + key.len()..].trim_start();
576 if rest.starts_with('*') {
577 let open = rest.find('{')?;
578 let close = find_matching_brace(rest, open)?;
579 let inner = &rest[open + 1..close];
580 if let Some(a_pos) = inner.find("a:") {
581 return Some(&inner[a_pos + 2..]);
582 }
583 return Some(inner);
584 }
585 // Older ASCII FBX format: `Vertices: x,y,z,...` until next non-number line or closing brace
586 let mut end = rest.len();
587 for (i, b) in rest.bytes().enumerate() {
588 if b == b'}' || (b.is_ascii_alphabetic() && b != b'e' && b != b'E') {
589 end = i;
590 break;
591 }
592 }
593 Some(&rest[..end])
594}
595
596fn extract_ascii_fbx_f32_array(body: &str, key: &str) -> Option<Vec<f32>> {
597 let raw = extract_ascii_fbx_array_str(body, key)?;
598 let mut out = Vec::new();
599 for tok in raw.split(|c: char| c == ',' || c.is_ascii_whitespace()) {
600 if tok.is_empty() {
601 continue;
602 }
603 if let Ok(v) = tok.parse::<f32>() {
604 out.push(v);
605 }
606 }
607 (!out.is_empty()).then_some(out)
608}
609
610fn extract_ascii_fbx_i32_array(body: &str, key: &str) -> Option<Vec<i32>> {
611 let raw = extract_ascii_fbx_array_str(body, key)?;
612 let mut out = Vec::new();
613 for tok in raw.split(|c: char| c == ',' || c.is_ascii_whitespace()) {
614 if tok.is_empty() {
615 continue;
616 }
617 if let Ok(v) = tok.parse::<i32>() {
618 out.push(v);
619 }
620 }
621 (!out.is_empty()).then_some(out)
622}
623
624fn extract_fbx_quoted_name(header: &str) -> String {
625 let mut iter = header.split('"');
626 let _ = iter.next();
627 let raw = iter.next().unwrap_or("");
628 clean_fbx_symbol_name(raw)
629}
630
631fn clean_fbx_symbol_name(raw: &str) -> String {
632 // Binary FBX names often look like "Cube\x00\x01Geometry"; ASCII FBX like "Geometry::Cube"
633 let base = raw.split('\0').next().unwrap_or(raw);
634 base.rsplit("::").next().unwrap_or(base).trim().to_string()
635}
636
637fn fbx_name_matches(candidate: &str, target: &str) -> bool {
638 let c = clean_fbx_symbol_name(candidate);
639 let t = clean_fbx_symbol_name(target);
640 !c.is_empty() && c.eq_ignore_ascii_case(&t)
641}
642
643// ---------------------------------------------------------------------------
644// Binary FBX parser (v7100 - v7700+)
645// ---------------------------------------------------------------------------
646
647#[derive(Debug)]
648enum FbxProp {
649 I64(i64),
650 Str(String),
651 F32Array(Vec<f32>),
652 I32Array(Vec<i32>),
653 Other,
654}
655
656#[derive(Debug)]
657struct FbxBinNode {
658 name: String,
659 props: Vec<FbxProp>,
660 children: Vec<FbxBinNode>,
661}
662
663fn parse_binary_fbx(bytes: &[u8], obj_name: Option<&str>) -> Option<Vec<Vertex3D>> {
664 if bytes.len() < 27 || &bytes[..21] != FBX_BINARY_MAGIC {
665 return None;
666 }
667 let version = u32::from_le_bytes(bytes[23..27].try_into().ok()?);
668 let is_64 = version >= 7500;
669 let mut pos = 27usize;
670 let mut root_nodes = Vec::new();
671
672 while pos < bytes.len() {
673 let Some(node) = read_fbx_bin_node(bytes, &mut pos, is_64, 0) else {
674 break;
675 };
676 root_nodes.push(node);
677 }
678
679 let mut geometries: Vec<FbxGeometryData> = Vec::new();
680 let mut model_names: HashMap<i64, String> = HashMap::new();
681 let mut geom_to_model: HashMap<i64, i64> = HashMap::new();
682
683 for node in &root_nodes {
684 match node.name.as_str() {
685 "Objects" => {
686 for child in &node.children {
687 if child.name == "Geometry" {
688 let g = extract_bin_geometry(child);
689 if !g.vertices.is_empty() && !g.poly_indices.is_empty() {
690 geometries.push(g);
691 }
692 } else if child.name == "Model" {
693 if let (Some(FbxProp::I64(id)), Some(FbxProp::Str(s))) =
694 (child.props.first(), child.props.get(1))
695 {
696 model_names.insert(*id, clean_fbx_symbol_name(s));
697 }
698 }
699 }
700 }
701 "Connections" => {
702 for c in &node.children {
703 if c.name == "C" {
704 if let (Some(FbxProp::I64(child_id)), Some(FbxProp::I64(parent_id))) =
705 (c.props.get(1), c.props.get(2))
706 {
707 geom_to_model.insert(*child_id, *parent_id);
708 }
709 }
710 }
711 }
712 _ => {}
713 }
714 }
715
716 if geometries.is_empty() {
717 return None;
718 }
719
720 let target = obj_name.map(str::trim).filter(|s| !s.is_empty());
721 let mut out = Vec::new();
722 if let Some(t) = target {
723 for g in &geometries {
724 let model_match = geom_to_model
725 .get(&g.id)
726 .and_then(|mid| model_names.get(mid))
727 .is_some_and(|mn| fbx_name_matches(mn, t));
728 if fbx_name_matches(&g.name, t) || model_match {
729 assemble_fbx_geometry(g, &mut out);
730 }
731 }
732 }
733 if out.is_empty() {
734 for g in &geometries {
735 assemble_fbx_geometry(g, &mut out);
736 }
737 }
738 (!out.is_empty()).then_some(out)
739}
740
741fn extract_bin_geometry(node: &FbxBinNode) -> FbxGeometryData {
742 let mut g = FbxGeometryData::default();
743 if let Some(FbxProp::I64(id)) = node.props.first() {
744 g.id = *id;
745 }
746 for p in &node.props {
747 if let FbxProp::Str(s) = p {
748 let cleaned = clean_fbx_symbol_name(s);
749 if !cleaned.is_empty() && !cleaned.eq_ignore_ascii_case("Mesh") {
750 g.name = cleaned;
751 break;
752 }
753 }
754 }
755 for child in &node.children {
756 match child.name.as_str() {
757 "Vertices" => {
758 if let Some(FbxProp::F32Array(arr)) = child.props.first() {
759 g.vertices = arr.clone();
760 }
761 }
762 "PolygonVertexIndex" => {
763 if let Some(FbxProp::I32Array(arr)) = child.props.first() {
764 g.poly_indices = arr.clone();
765 }
766 }
767 "LayerElementNormal" => {
768 for sub in &child.children {
769 match sub.name.as_str() {
770 "MappingInformationType" => {
771 if let Some(FbxProp::Str(s)) = sub.props.first() {
772 g.normal_mapping = s.clone();
773 }
774 }
775 "Normals" => {
776 if let Some(FbxProp::F32Array(arr)) = sub.props.first() {
777 g.normals = arr.clone();
778 }
779 }
780 "NormalsIndex" => {
781 if let Some(FbxProp::I32Array(arr)) = sub.props.first() {
782 g.normal_indices = arr.clone();
783 }
784 }
785 _ => {}
786 }
787 }
788 }
789 "LayerElementUV" => {
790 if !g.uvs.is_empty() {
791 continue;
792 }
793 for sub in &child.children {
794 match sub.name.as_str() {
795 "MappingInformationType" => {
796 if let Some(FbxProp::Str(s)) = sub.props.first() {
797 g.uv_mapping = s.clone();
798 }
799 }
800 "UV" => {
801 if let Some(FbxProp::F32Array(arr)) = sub.props.first() {
802 g.uvs = arr.clone();
803 }
804 }
805 "UVIndex" => {
806 if let Some(FbxProp::I32Array(arr)) = sub.props.first() {
807 g.uv_indices = arr.clone();
808 }
809 }
810 _ => {}
811 }
812 }
813 }
814 _ => {}
815 }
816 }
817 g
818}
819
820fn read_fbx_bin_node(
821 bytes: &[u8],
822 pos: &mut usize,
823 is_64: bool,
824 depth: usize,
825) -> Option<FbxBinNode> {
826 if depth > MAX_FBX_DEPTH {
827 return None;
828 }
829 let sentinel_len = if is_64 { 25usize } else { 13usize };
830 if *pos + sentinel_len > bytes.len() {
831 return None;
832 }
833
834 let (end_offset, num_props, prop_list_len, name_len) = if is_64 {
835 let eo = u64::from_le_bytes(bytes[*pos..*pos + 8].try_into().ok()?) as usize;
836 let np = u64::from_le_bytes(bytes[*pos + 8..*pos + 16].try_into().ok()?) as usize;
837 let pl = u64::from_le_bytes(bytes[*pos + 16..*pos + 24].try_into().ok()?) as usize;
838 let nl = bytes[*pos + 24] as usize;
839 *pos += 25;
840 (eo, np, pl, nl)
841 } else {
842 let eo = u32::from_le_bytes(bytes[*pos..*pos + 4].try_into().ok()?) as usize;
843 let np = u32::from_le_bytes(bytes[*pos + 4..*pos + 8].try_into().ok()?) as usize;
844 let pl = u32::from_le_bytes(bytes[*pos + 8..*pos + 12].try_into().ok()?) as usize;
845 let nl = bytes[*pos + 12] as usize;
846 *pos += 13;
847 (eo, np, pl, nl)
848 };
849
850 // Null sentinel marks end of sibling list
851 if end_offset == 0 && num_props == 0 && prop_list_len == 0 && name_len == 0 {
852 return None;
853 }
854 if end_offset > bytes.len() || *pos + name_len > end_offset {
855 return None;
856 }
857
858 let name = String::from_utf8_lossy(&bytes[*pos..*pos + name_len]).into_owned();
859 *pos += name_len;
860
861 let props_end = (*pos).saturating_add(prop_list_len).min(end_offset);
862 let mut props = Vec::with_capacity(num_props.min(64));
863 for _ in 0..num_props {
864 if *pos >= props_end {
865 break;
866 }
867 let Some(p) = read_fbx_bin_prop(bytes, pos, props_end) else {
868 break;
869 };
870 props.push(p);
871 }
872 *pos = props_end;
873
874 let mut children = Vec::new();
875 while *pos + sentinel_len <= end_offset {
876 let Some(child) = read_fbx_bin_node(bytes, pos, is_64, depth + 1) else {
877 break;
878 };
879 children.push(child);
880 }
881 *pos = end_offset;
882
883 Some(FbxBinNode {
884 name,
885 props,
886 children,
887 })
888}
889
890fn read_fbx_bin_prop(bytes: &[u8], pos: &mut usize, limit: usize) -> Option<FbxProp> {
891 if *pos >= limit {
892 return None;
893 }
894 let tag = bytes[*pos];
895 *pos += 1;
896 match tag {
897 b'Y' => {
898 if *pos + 2 > limit { return None; }
899 let v = i16::from_le_bytes(bytes[*pos..*pos + 2].try_into().ok()?);
900 *pos += 2;
901 Some(FbxProp::I64(v as i64))
902 }
903 b'C' => {
904 if *pos + 1 > limit { return None; }
905 let v = bytes[*pos];
906 *pos += 1;
907 Some(FbxProp::I64(v as i64))
908 }
909 b'I' => {
910 if *pos + 4 > limit { return None; }
911 let v = i32::from_le_bytes(bytes[*pos..*pos + 4].try_into().ok()?);
912 *pos += 4;
913 Some(FbxProp::I64(v as i64))
914 }
915 b'F' => {
916 if *pos + 4 > limit { return None; }
917 *pos += 4;
918 Some(FbxProp::Other)
919 }
920 b'D' => {
921 if *pos + 8 > limit { return None; }
922 *pos += 8;
923 Some(FbxProp::Other)
924 }
925 b'L' => {
926 if *pos + 8 > limit { return None; }
927 let v = i64::from_le_bytes(bytes[*pos..*pos + 8].try_into().ok()?);
928 *pos += 8;
929 Some(FbxProp::I64(v))
930 }
931 b'S' | b'R' => {
932 if *pos + 4 > limit { return None; }
933 let len = u32::from_le_bytes(bytes[*pos..*pos + 4].try_into().ok()?) as usize;
934 *pos += 4;
935 if *pos + len > limit { return None; }
936 let slice = &bytes[*pos..*pos + len];
937 *pos += len;
938 if tag == b'S' {
939 Some(FbxProp::Str(String::from_utf8_lossy(slice).into_owned()))
940 } else {
941 Some(FbxProp::Other)
942 }
943 }
944 b'f' | b'd' | b'i' | b'l' | b'b' => {
945 if *pos + 12 > limit { return None; }
946 let array_len = u32::from_le_bytes(bytes[*pos..*pos + 4].try_into().ok()?) as usize;
947 let encoding = u32::from_le_bytes(bytes[*pos + 4..*pos + 8].try_into().ok()?);
948 let comp_len = u32::from_le_bytes(bytes[*pos + 8..*pos + 12].try_into().ok()?) as usize;
949 *pos += 12;
950 if *pos + comp_len > limit { return None; }
951 let raw_slice = &bytes[*pos..*pos + comp_len];
952 *pos += comp_len;
953
954 let elem_size = match tag {
955 b'b' => 1usize,
956 b'f' | b'i' => 4usize,
957 b'd' | b'l' => 8usize,
958 _ => return Some(FbxProp::Other),
959 };
960 let expected_bytes = array_len.checked_mul(elem_size)?;
961 if expected_bytes > MAX_DECOMPRESS_BYTES {
962 return Some(FbxProp::Other);
963 }
964
965 let decoded_owned;
966 let data: &[u8] = if encoding == 0 {
967 if raw_slice.len() < expected_bytes {
968 return Some(FbxProp::Other);
969 }
970 &raw_slice[..expected_bytes]
971 } else if encoding == 1 {
972 let Some(buf) = zlib_decompress(raw_slice, expected_bytes) else {
973 return Some(FbxProp::Other);
974 };
975 if buf.len() < expected_bytes {
976 return Some(FbxProp::Other);
977 }
978 decoded_owned = buf;
979 &decoded_owned[..expected_bytes]
980 } else {
981 return Some(FbxProp::Other);
982 };
983
984 match tag {
985 b'f' => {
986 let mut out = Vec::with_capacity(array_len);
987 for c in data.chunks_exact(4) {
988 out.push(f32::from_le_bytes([c[0], c[1], c[2], c[3]]));
989 }
990 Some(FbxProp::F32Array(out))
991 }
992 b'd' => {
993 let mut out = Vec::with_capacity(array_len);
994 for c in data.chunks_exact(8) {
995 out.push(f64::from_le_bytes([c[0], c[1], c[2], c[3], c[4], c[5], c[6], c[7]]) as f32);
996 }
997 Some(FbxProp::F32Array(out))
998 }
999 b'i' => {
1000 let mut out = Vec::with_capacity(array_len);
1001 for c in data.chunks_exact(4) {
1002 out.push(i32::from_le_bytes([c[0], c[1], c[2], c[3]]));
1003 }
1004 Some(FbxProp::I32Array(out))
1005 }
1006 _ => Some(FbxProp::Other),
1007 }
1008 }
1009 _ => None,
1010 }
1011}
1012
1013// ---------------------------------------------------------------------------
1014// Minimal pure-Rust RFC 1950 (zlib) + RFC 1951 (DEFLATE) inflater
1015// ---------------------------------------------------------------------------
1016
1017struct BitReader<'a> {
1018 data: &'a [u8],
1019 byte_pos: usize,
1020 bit_buf: u32,
1021 bit_count: u8,
1022}
1023
1024impl<'a> BitReader<'a> {
1025 fn new(data: &'a [u8]) -> Self {
1026 Self { data, byte_pos: 0, bit_buf: 0, bit_count: 0 }
1027 }
1028
1029 fn read_bits(&mut self, n: u8) -> Option<u32> {
1030 while self.bit_count < n {
1031 let b = *self.data.get(self.byte_pos)?;
1032 self.byte_pos += 1;
1033 self.bit_buf |= (b as u32) << self.bit_count;
1034 self.bit_count += 8;
1035 }
1036 let val = self.bit_buf & ((1u32 << n) - 1);
1037 self.bit_buf >>= n;
1038 self.bit_count -= n;
1039 Some(val)
1040 }
1041
1042 fn align_byte(&mut self) {
1043 let drop = self.bit_count % 8;
1044 self.bit_buf >>= drop;
1045 self.bit_count -= drop;
1046 }
1047
1048 fn read_aligned_bytes(&mut self, n: usize) -> Option<Vec<u8>> {
1049 self.align_byte();
1050 let mut out = Vec::with_capacity(n);
1051 while out.len() < n && self.bit_count >= 8 {
1052 out.push((self.bit_buf & 0xFF) as u8);
1053 self.bit_buf >>= 8;
1054 self.bit_count -= 8;
1055 }
1056 let rem = n - out.len();
1057 if self.byte_pos + rem > self.data.len() {
1058 return None;
1059 }
1060 out.extend_from_slice(&self.data[self.byte_pos..self.byte_pos + rem]);
1061 self.byte_pos += rem;
1062 Some(out)
1063 }
1064}
1065
1066struct HuffTree {
1067 counts: [u16; 16],
1068 symbols: Vec<u16>,
1069}
1070
1071impl HuffTree {
1072 fn build(lengths: &[u8]) -> Option<Self> {
1073 let mut counts = [0u16; 16];
1074 for &l in lengths {
1075 if l as usize >= 16 {
1076 return None;
1077 }
1078 if l > 0 {
1079 counts[l as usize] += 1;
1080 }
1081 }
1082 let mut offsets = [0usize; 16];
1083 let mut total = 0usize;
1084 for bits in 1..16 {
1085 offsets[bits] = total;
1086 total += counts[bits] as usize;
1087 }
1088 let mut symbols = vec![0u16; total];
1089 for (sym, &l) in lengths.iter().enumerate() {
1090 if l > 0 {
1091 let idx = offsets[l as usize];
1092 symbols[idx] = sym as u16;
1093 offsets[l as usize] += 1;
1094 }
1095 }
1096 Some(Self { counts, symbols })
1097 }
1098
1099 fn decode(&self, br: &mut BitReader<'_>) -> Option<u16> {
1100 let mut code = 0i32;
1101 let mut first = 0i32;
1102 let mut index = 0usize;
1103 for len in 1..16 {
1104 code |= br.read_bits(1)? as i32;
1105 let count = self.counts[len] as i32;
1106 if code - count < first {
1107 return self.symbols.get(index + (code - first) as usize).copied();
1108 }
1109 index += count as usize;
1110 first = (first + count) << 1;
1111 code <<= 1;
1112 }
1113 None
1114 }
1115}
1116
1117fn zlib_decompress(input: &[u8], max_out: usize) -> Option<Vec<u8>> {
1118 if input.len() < 6 {
1119 return None;
1120 }
1121 let cmf = input[0];
1122 let flg = input[1];
1123 if (cmf & 0x0F) != 8 || (((cmf as u16) * 256 + flg as u16) % 31) != 0 {
1124 return None;
1125 }
1126 let start = if (flg & 0x20) != 0 { 6 } else { 2 };
1127 if start > input.len() {
1128 return None;
1129 }
1130
1131 let mut br = BitReader::new(&input[start..]);
1132 let mut out = Vec::with_capacity(max_out.min(1024 * 1024));
1133 let cap = max_out.min(MAX_DECOMPRESS_BYTES);
1134
1135 const LEN_BASE: [u16; 29] = [
1136 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
1137 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258,
1138 ];
1139 const LEN_EXTRA: [u8; 29] = [
1140 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2,
1141 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0,
1142 ];
1143 const DIST_BASE: [u16; 30] = [
1144 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
1145 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577,
1146 ];
1147 const DIST_EXTRA: [u8; 30] = [
1148 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6,
1149 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13,
1150 ];
1151 const CL_ORDER: [usize; 19] = [
1152 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15,
1153 ];
1154
1155 loop {
1156 let bfinal = br.read_bits(1)?;
1157 let btype = br.read_bits(2)?;
1158 match btype {
1159 0 => {
1160 let hdr = br.read_aligned_bytes(4)?;
1161 let len = u16::from_le_bytes([hdr[0], hdr[1]]) as usize;
1162 let nlen = u16::from_le_bytes([hdr[2], hdr[3]]);
1163 if (len as u16) != !nlen || out.len() + len > cap {
1164 return None;
1165 }
1166 let block = br.read_aligned_bytes(len)?;
1167 out.extend_from_slice(&block);
1168 }
1169 1 | 2 => {
1170 let (lit_tree, dist_tree) = if btype == 1 {
1171 let mut ll = [0u8; 288];
1172 ll[..144].fill(8);
1173 ll[144..256].fill(9);
1174 ll[256..280].fill(7);
1175 ll[280..288].fill(8);
1176 let dl = [5u8; 32];
1177 (HuffTree::build(&ll)?, HuffTree::build(&dl)?)
1178 } else {
1179 let hlit = br.read_bits(5)? as usize + 257;
1180 let hdist = br.read_bits(5)? as usize + 1;
1181 let hclen = br.read_bits(4)? as usize + 4;
1182 let mut cl = [0u8; 19];
1183 for i in 0..hclen {
1184 cl[CL_ORDER[i]] = br.read_bits(3)? as u8;
1185 }
1186 let cl_tree = HuffTree::build(&cl)?;
1187 let total = hlit + hdist;
1188 let mut lengths = Vec::with_capacity(total);
1189 while lengths.len() < total {
1190 let sym = cl_tree.decode(&mut br)?;
1191 match sym {
1192 0..=15 => lengths.push(sym as u8),
1193 16 => {
1194 let prev = *lengths.last()?;
1195 let rep = br.read_bits(2)? as usize + 3;
1196 for _ in 0..rep {
1197 lengths.push(prev);
1198 }
1199 }
1200 17 => {
1201 let rep = br.read_bits(3)? as usize + 3;
1202 lengths.resize(lengths.len() + rep, 0);
1203 }
1204 18 => {
1205 let rep = br.read_bits(7)? as usize + 11;
1206 lengths.resize(lengths.len() + rep, 0);
1207 }
1208 _ => return None,
1209 }
1210 }
1211 if lengths.len() < total {
1212 return None;
1213 }
1214 (
1215 HuffTree::build(&lengths[..hlit])?,
1216 HuffTree::build(&lengths[hlit..total])?,
1217 )
1218 };
1219
1220 loop {
1221 let sym = lit_tree.decode(&mut br)?;
1222 if sym < 256 {
1223 if out.len() >= cap {
1224 return None;
1225 }
1226 out.push(sym as u8);
1227 } else if sym == 256 {
1228 break;
1229 } else {
1230 let li = (sym as usize).checked_sub(257)?;
1231 if li >= LEN_BASE.len() {
1232 return None;
1233 }
1234 let length = LEN_BASE[li] as usize
1235 + br.read_bits(LEN_EXTRA[li])? as usize;
1236 let di = dist_tree.decode(&mut br)? as usize;
1237 if di >= DIST_BASE.len() {
1238 return None;
1239 }
1240 let dist = DIST_BASE[di] as usize
1241 + br.read_bits(DIST_EXTRA[di])? as usize;
1242 if dist == 0 || dist > out.len() || out.len() + length > cap {
1243 return None;
1244 }
1245 for _ in 0..length {
1246 let b = out[out.len() - dist];
1247 out.push(b);
1248 }
1249 }
1250 }
1251 }
1252 _ => return None,
1253 }
1254 if bfinal != 0 {
1255 break;
1256 }
1257 }
1258 Some(out)
1259}
1260
1261// ---------------------------------------------------------------------------
1262// Normal recomputation helpers
1263// ---------------------------------------------------------------------------
1264
1265#[inline]
1266fn vec3_len_sq(v: [f32; 3]) -> f32 {
1267 v[0] * v[0] + v[1] * v[1] + v[2] * v[2]
1268}
1269
1270#[inline]
1271fn normalize3(v: [f32; 3]) -> [f32; 3] {
1272 let len = vec3_len_sq(v).sqrt();
1273 if len > 1e-6 {
1274 [v[0] / len, v[1] / len, v[2] / len]
1275 } else {
1276 [0.0, 0.0, 1.0]
1277 }
1278}
1279
1280fn quantize_pos(p: [f32; 3]) -> (i64, i64, i64) {
1281 (
1282 (p[0] * 10_000.0).round() as i64,
1283 (p[1] * 10_000.0).round() as i64,
1284 (p[2] * 10_000.0).round() as i64,
1285 )
1286}
1287
1288/// Recomputes smooth vertex normals by accumulating face normals at coincident vertex positions.
1289pub(super) fn recompute_smooth_normals(verts: &mut [Vertex3D]) {
1290 let mut acc: HashMap<(i64, i64, i64), [f32; 3]> = HashMap::new();
1291 for tri in verts.chunks_exact(3) {
1292 let p0 = tri[0].pos;
1293 let p1 = tri[1].pos;
1294 let p2 = tri[2].pos;
1295 let e1 = [p1[0] - p0[0], p1[1] - p0[1], p1[2] - p0[2]];
1296 let e2 = [p2[0] - p0[0], p2[1] - p0[1], p2[2] - p0[2]];
1297 let fn_v = [
1298 e1[1] * e2[2] - e1[2] * e2[1],
1299 e1[2] * e2[0] - e1[0] * e2[2],
1300 e1[0] * e2[1] - e1[1] * e2[0],
1301 ];
1302 for v in tri {
1303 let entry = acc.entry(quantize_pos(v.pos)).or_insert([0.0; 3]);
1304 entry[0] += fn_v[0];
1305 entry[1] += fn_v[1];
1306 entry[2] += fn_v[2];
1307 }
1308 }
1309 for v in verts.iter_mut() {
1310 if let Some(&n) = acc.get(&quantize_pos(v.pos)) {
1311 v.normal = normalize3(n);
1312 } else {
1313 v.normal = [0.0, 0.0, 1.0];
1314 }
1315 }
1316}
1317
1318#[cfg(test)]
1319mod tests {
1320 use super::*;
1321
1322 fn build_synthetic_binary_fbx(version: u32, compressed: bool) -> Vec<u8> {
1323 let is_64 = version >= 7500;
1324 let mut out = Vec::new();
1325 out.extend_from_slice(FBX_BINARY_MAGIC);
1326 out.extend_from_slice(&[0x1A, 0x00]);
1327 out.extend_from_slice(&version.to_le_bytes());
1328
1329 fn encode_node(
1330 name: &str,
1331 props: &[Vec<u8>],
1332 children: &[Vec<u8>],
1333 base_offset: usize,
1334 is_64: bool,
1335 ) -> Vec<u8> {
1336 let hdr_len = if is_64 { 25usize } else { 13usize };
1337 let prop_bytes: usize = props.iter().map(|p| p.len()).sum();
1338 let children_start = base_offset + hdr_len + name.len() + prop_bytes;
1339 let mut children_buf = Vec::new();
1340 let mut cur = children_start;
1341 for c in children {
1342 let _ = cur;
1343 children_buf.extend_from_slice(c);
1344 cur += c.len();
1345 }
1346 if !children.is_empty() {
1347 children_buf.resize(children_buf.len() + hdr_len, 0);
1348 }
1349 let end_offset = children_start + children_buf.len();
1350
1351 let mut buf = Vec::new();
1352 if is_64 {
1353 buf.extend_from_slice(&(end_offset as u64).to_le_bytes());
1354 buf.extend_from_slice(&(props.len() as u64).to_le_bytes());
1355 buf.extend_from_slice(&(prop_bytes as u64).to_le_bytes());
1356 } else {
1357 buf.extend_from_slice(&(end_offset as u32).to_le_bytes());
1358 buf.extend_from_slice(&(props.len() as u32).to_le_bytes());
1359 buf.extend_from_slice(&(prop_bytes as u32).to_le_bytes());
1360 }
1361 buf.push(name.len() as u8);
1362 buf.extend_from_slice(name.as_bytes());
1363 for p in props {
1364 buf.extend_from_slice(p);
1365 }
1366 buf.extend_from_slice(&children_buf);
1367 buf
1368 }
1369
1370 // Build a stored zlib stream for testing encoding==1 without external crates
1371 fn zlib_stored(raw: &[u8]) -> Vec<u8> {
1372 let mut z = vec![0x78, 0x01]; // zlib header: CMF=0x78, FLG=0x01
1373 z.push(0x01); // BFINAL=1, BTYPE=00 (stored)
1374 let len = raw.len() as u16;
1375 z.extend_from_slice(&len.to_le_bytes());
1376 z.extend_from_slice(&(!len).to_le_bytes());
1377 z.extend_from_slice(raw);
1378 z.extend_from_slice(&[0, 0, 0, 0]); // placeholder adler32 (unchecked by reader)
1379 z
1380 }
1381
1382 fn make_array_prop(tag: u8, count: u32, raw: &[u8], compressed: bool) -> Vec<u8> {
1383 let payload = if compressed { zlib_stored(raw) } else { raw.to_vec() };
1384 let mut p = vec![tag];
1385 p.extend_from_slice(&count.to_le_bytes());
1386 p.extend_from_slice(&(if compressed { 1u32 } else { 0u32 }).to_le_bytes());
1387 p.extend_from_slice(&(payload.len() as u32).to_le_bytes());
1388 p.extend_from_slice(&payload);
1389 p
1390 }
1391
1392 // Quad in XY plane (4 vertices, 2 triangles when fan-triangulated)
1393 let verts_f64: [f64; 12] = [
1394 0.0, 0.0, 0.0,
1395 1.0, 0.0, 0.0,
1396 1.0, 1.0, 0.0,
1397 0.0, 1.0, 0.0,
1398 ];
1399 let mut vraw = Vec::new();
1400 for v in verts_f64 {
1401 vraw.extend_from_slice(&v.to_le_bytes());
1402 }
1403 // Quad polygon: [0, 1, 2, !3] -> [0, 1, 2, -4]
1404 let poly_i32: [i32; 4] = [0, 1, 2, !3];
1405 let mut iraw = Vec::new();
1406 for i in poly_i32 {
1407 iraw.extend_from_slice(&i.to_le_bytes());
1408 }
1409
1410 let hdr_len = if is_64 { 25usize } else { 13usize };
1411 let objects_start = out.len();
1412 let geom_start = objects_start + hdr_len + "Objects".len();
1413
1414 let mut id_prop = vec![b'L'];
1415 id_prop.extend_from_slice(&1001i64.to_le_bytes());
1416 let gname = b"TestQuad\0\x01Geometry";
1417 let mut name_prop = vec![b'S'];
1418 name_prop.extend_from_slice(&(gname.len() as u32).to_le_bytes());
1419 name_prop.extend_from_slice(gname);
1420
1421 let vprop = make_array_prop(b'd', 12, &vraw, compressed);
1422 let iprop = make_array_prop(b'i', 4, &iraw, compressed);
1423
1424 let geom_children_start = geom_start + hdr_len + "Geometry".len() + id_prop.len() + name_prop.len();
1425 let v_node = encode_node("Vertices", &[vprop], &[], geom_children_start, is_64);
1426 let i_node = encode_node("PolygonVertexIndex", &[iprop], &[], geom_children_start + v_node.len(), is_64);
1427
1428 let geom_node = encode_node("Geometry", &[id_prop, name_prop], &[v_node, i_node], geom_start, is_64);
1429 let objects_node = encode_node("Objects", &[], &[geom_node], objects_start, is_64);
1430
1431 out.extend_from_slice(&objects_node);
1432 out.resize(out.len() + hdr_len, 0); // top-level sentinel
1433 out
1434 }
1435
1436 #[test]
1437 fn test_parse_obj_quad_and_normals() {
1438 let obj = r#"
1439# Simple quad OBJ without normals
1440o MyQuad
1441v 0 0 0
1442v 2 0 0
1443v 2 2 0
1444v 0 2 0
1445vt 0 0
1446vt 1 0
1447vt 1 1
1448vt 0 1
1449f 1/1 2/2 3/3 4/4
1450"#;
1451 let verts = parse_mesh_bytes(obj.as_bytes(), Some("obj"), Some("MyQuad"), 0.5)
1452 .expect("parse OBJ");
1453 assert_eq!(verts.len(), 6, "quad should fan-triangulate into 2 triangles (6 verts)");
1454 // Scaled by 0.5 -> max X/Y = 1.0
1455 assert!((verts[1].pos[0] - 1.0).abs() < 1e-5);
1456 assert!((verts[2].pos[1] - 1.0).abs() < 1e-5);
1457 // Smooth normals computed pointing +Z
1458 for v in &verts {
1459 assert!((v.normal[2] - 1.0).abs() < 1e-4, "expected +Z normal, got {:?}", v.normal);
1460 }
1461 }
1462
1463 #[test]
1464 fn test_parse_ascii_fbx() {
1465 let ascii = r#"
1466; FBX 7.4.0 project file
1467Objects: {
1468 Geometry: 1234, "Geometry::TriMesh", "Mesh" {
1469 Vertices: *9 {
1470 a: 0,0,0, 1,0,0, 0,1,0
1471 }
1472 PolygonVertexIndex: *3 {
1473 a: 0,1,-3
1474 }
1475 LayerElementUV: 0 {
1476 MappingInformationType: "ByPolygonVertex"
1477 UV: *6 {
1478 a: 0,0, 1,0, 0,1
1479 }
1480 }
1481 }
1482}
1483"#;
1484 let verts = parse_mesh_bytes(ascii.as_bytes(), Some("fbx"), Some("TriMesh"), 2.0)
1485 .expect("parse ASCII FBX");
1486 assert_eq!(verts.len(), 3, "1 triangle = 3 vertices");
1487 assert!((verts[1].pos[0] - 2.0).abs() < 1e-5);
1488 assert!((verts[2].pos[1] - 2.0).abs() < 1e-5);
1489 assert!((verts[0].normal[2] - 1.0).abs() < 1e-4);
1490 assert!((verts[2].uv[1] - 0.0).abs() < 1e-4, "V flipped from 1.0 -> 0.0");
1491 }
1492
1493 #[test]
1494 fn test_parse_binary_fbx_v7400_and_v7500_compressed() {
1495 let raw_7400 = build_synthetic_binary_fbx(7400, false);
1496 let verts_7400 = parse_mesh_bytes(&raw_7400, Some("fbx"), Some("TestQuad"), 1.0)
1497 .expect("parse binary FBX v7400");
1498 assert_eq!(verts_7400.len(), 6);
1499 assert!((verts_7400[0].normal[2] - 1.0).abs() < 1e-4);
1500
1501 let comp_7500 = build_synthetic_binary_fbx(7500, true);
1502 let verts_7500 = parse_mesh_bytes(&comp_7500, Some("fbx"), Some("TestQuad"), 3.0)
1503 .expect("parse compressed binary FBX v7500");
1504 assert_eq!(verts_7500.len(), 6);
1505 assert!((verts_7500[1].pos[0] - 3.0).abs() < 1e-5);
1506 assert!((verts_7500[2].pos[1] - 3.0).abs() < 1e-5);
1507 assert!((verts_7500[0].normal[2] - 1.0).abs() < 1e-4);
1508 }
1509
1510 #[test]
1511 fn test_missing_file_fallback_unit_box() {
1512 let mesh = load_mesh_cached("/nonexistent/path/to/missing_model.fbx", None, None, 1.0);
1513 assert_eq!(mesh.len(), 36, "fallback placeholder should be a 12-triangle unit box");
1514 }
1515}
crates/engine/src/scene3d/mesh.rs+12-6
......@@ -4,14 +4,14 @@ use super::shader::Vertex3D;
44use super::{DisplaceHeightmap, ShapeKind};
55
66pub(super) fn build_shape_mesh(shape: &ShapeKind, tex_aspect: f32) -> (Vec<Vertex3D>, Vec<u32>) {
7 match *shape {
7 match shape {
88 ShapeKind::ImagePlane => build_image_plane(tex_aspect),
9 ShapeKind::Plane { width, height, sub_w, sub_h } => build_plane(width, height, sub_w, sub_h),
9 ShapeKind::Plane { width, height, sub_w, sub_h } => build_plane(*width, *height, *sub_w, *sub_h),
1010 ShapeKind::TextPlate { width, height, depth, slices } => {
11 build_text_plate(width, height, depth, slices)
11 build_text_plate(*width, *height, *depth, *slices)
1212 }
1313 ShapeKind::Sphere { radius, sub_base, sub_height } => {
14 build_sphere(radius, sub_base, sub_height)
14 build_sphere(*radius, *sub_base, *sub_height)
1515 }
1616 ShapeKind::Cylinder {
1717 radius,
......@@ -19,8 +19,14 @@ pub(super) fn build_shape_mesh(shape: &ShapeKind, tex_aspect: f32) -> (Vec<Verte
1919 start_sweep_deg,
2020 end_sweep_deg,
2121 sub_base,
22 } => build_cylinder(radius, height, start_sweep_deg, end_sweep_deg, sub_base),
23 ShapeKind::Cube { width, height, depth } => build_cube(width, height, depth),
22 } => build_cylinder(*radius, *height, *start_sweep_deg, *end_sweep_deg, *sub_base),
23 ShapeKind::Cube { width, height, depth } => build_cube(*width, *height, *depth),
24 ShapeKind::CustomMesh(verts) => {
25 let v = verts.as_ref().clone();
26 let idx = (0..v.len() as u32).collect();
27 (v, idx)
28 }
29 ShapeKind::WithMaterialFx { inner, .. } => build_shape_mesh(inner, tex_aspect),
2430 }
2531}
2632
crates/engine/src/scene3d/mod.rs+61-2
......@@ -7,6 +7,7 @@
77//! and `Camera3D` film-gate `AoV` / `ApertureW` / `ApertureH` projection.
88
99mod collect;
10mod fbx;
1011mod math;
1112mod mesh;
1213mod shader;
......@@ -16,11 +17,14 @@ pub use math::{
1617 mat4_identity, mat4_inverse_rigid, mat4_mul, mat4_perspective_wgpu, mat4_rot_x, mat4_rot_y,
1718 mat4_rot_z, mat4_scale, mat4_translate,
1819};
20pub use shader::Vertex3D;
21
22use std::sync::Arc;
1923
2024use crate::cache::CachedTexture;
2125use mesh::{apply_heightmap_displace, build_shape_mesh};
2226use model::NodeId;
23use shader::{MeshUniform, SHADER_3D, Vertex3D};
27use shader::{MeshUniform, SHADER_3D};
2428
2529pub type Mat4 = [f32; 16]; // Column-major 4x4
2630
......@@ -46,6 +50,51 @@ pub enum ShapeKind {
4650 Plane { width: f32, height: f32, sub_w: u32, sub_h: u32 },
4751 Cube { width: f32, height: f32, depth: f32 },
4852 TextPlate { width: f32, height: f32, depth: f32, slices: u32 },
53 CustomMesh(Arc<Vec<Vertex3D>>),
54 /// Wraps a base `ShapeKind` with UV transform and bump parameters so they travel
55 /// cleanly through `DrawMesh` into `Scene3DRenderer::render_meshes`.
56 WithMaterialFx {
57 inner: Box<ShapeKind>,
58 uv_offset: [f32; 2],
59 uv_scale: [f32; 2],
60 uv_rot: f32,
61 uv_wrap: u32,
62 bump_scale: f32,
63 bump_mode: u32,
64 },
65}
66
67impl ShapeKind {
68 /// Returns the underlying geometry shape without any `WithMaterialFx` wrapper.
69 pub fn base_shape(&self) -> &ShapeKind {
70 match self {
71 ShapeKind::WithMaterialFx { inner, .. } => inner.base_shape(),
72 other => other,
73 }
74 }
75
76 pub(super) fn unwrap_fx(&self) -> (&ShapeKind, [f32; 2], [f32; 2], f32, u32, f32, u32) {
77 match self {
78 ShapeKind::WithMaterialFx {
79 inner,
80 uv_offset,
81 uv_scale,
82 uv_rot,
83 uv_wrap,
84 bump_scale,
85 bump_mode,
86 } => (
87 inner.base_shape(),
88 *uv_offset,
89 *uv_scale,
90 *uv_rot,
91 *uv_wrap,
92 *bump_scale,
93 *bump_mode,
94 ),
95 other => (other, [0.0, 0.0], [1.0, 1.0], 0.0, 0, 0.0, 0),
96 }
97 }
4998}
5099
51100#[derive(Clone, Debug)]
......@@ -83,6 +132,12 @@ pub struct MeshInstance {
83132 pub affected_by_lights: bool,
84133 pub flip_normals: bool,
85134 pub displace: Option<Displace3DSpec>,
135 pub uv_offset: [f32; 2],
136 pub uv_scale: [f32; 2],
137 pub uv_rot: f32,
138 pub uv_wrap: u32,
139 pub bump_scale: f32,
140 pub bump_mode: u32,
86141}
87142
88143#[derive(Clone, Copy, Debug)]
......@@ -296,7 +351,9 @@ impl Scene3DRenderer {
296351 .as_ref()
297352 .map(|t| (t.canvas_size[0] as f32 / t.canvas_size[1].max(1) as f32).max(1e-4))
298353 .unwrap_or(16.0 / 9.0);
299 let (mut verts, indices) = build_shape_mesh(&m.shape, aspect);
354 let (base_shape, uv_offset, uv_scale, uv_rot, uv_wrap, bump_scale, bump_mode) =
355 m.shape.unwrap_fx();
356 let (mut verts, indices) = build_shape_mesh(base_shape, aspect);
300357 if indices.is_empty() {
301358 continue;
302359 }
......@@ -373,6 +430,8 @@ impl Scene3DRenderer {
373430 dir_color: [lights.dir_color[0], lights.dir_color[1], lights.dir_color[2], 0.0],
374431 cam_pos: [cam_pos[0], cam_pos[1], cam_pos[2], 0.0],
375432 light_counts: [n_pt as f32, n_sp as f32, 0.0, 0.0],
433 uv_xform: [uv_offset[0], uv_offset[1], uv_scale[0], uv_scale[1]],
434 mat_fx: [uv_rot, uv_wrap as f32, bump_scale, bump_mode as f32],
376435 point_pos,
377436 point_col,
378437 spot_pos,
crates/engine/src/scene3d/shader.rs+106-11
......@@ -3,11 +3,11 @@
33use bytemuck::{Pod, Zeroable};
44
55#[repr(C)]
6#[derive(Clone, Copy, Pod, Zeroable)]
7pub(super) struct Vertex3D {
8 pub(super) pos: [f32; 3],
9 pub(super) normal: [f32; 3],
10 pub(super) uv: [f32; 2],
6#[derive(Clone, Copy, Debug, Pod, Zeroable)]
7pub struct Vertex3D {
8 pub pos: [f32; 3],
9 pub normal: [f32; 3],
10 pub uv: [f32; 2],
1111}
1212
1313#[repr(C)]
......@@ -33,6 +33,10 @@ pub(super) struct MeshUniform {
3333 pub(super) cam_pos: [f32; 4],
3434 /// `[num_point_lights, num_spot_lights, 0, 0]`
3535 pub(super) light_counts: [f32; 4],
36 /// UV transform `[offset_x, offset_y, scale_x, scale_y]`
37 pub(super) uv_xform: [f32; 4],
38 /// Material effects `[uv_rot_rad, uv_wrap_mode, bump_scale, bump_mode]`
39 pub(super) mat_fx: [f32; 4],
3640 /// Point light positions `(x, y, z, decay_type: 0=none, 1=linear, 2=quad)`
3741 pub(super) point_pos: [[f32; 4]; 4],
3842 /// Point light colors * intensity `(r, g, b, decay_rate)`
......@@ -58,6 +62,8 @@ struct MeshUniform {
5862 dir_color: vec4<f32>,
5963 cam_pos: vec4<f32>,
6064 light_counts: vec4<f32>,
65 uv_xform: vec4<f32>,
66 mat_fx: vec4<f32>,
6167 point_pos: array<vec4<f32>, 4>,
6268 point_col: array<vec4<f32>, 4>,
6369 spot_pos: array<vec4<f32>, 4>,
......@@ -134,20 +140,96 @@ fn eval_light_contrib(
134140 return out;
135141}
136142
143fn apply_uv_xform(raw_uv: vec2<f32>, uv_xform: vec4<f32>, rot_wrap: vec2<f32>) -> vec2<f32> {
144 let p = raw_uv - vec2<f32>(0.5, 0.5);
145 let c = cos(rot_wrap.x);
146 let s = sin(rot_wrap.x);
147 let r = vec2<f32>(p.x * c - p.y * s, p.x * s + p.y * c);
148 var uv = r * uv_xform.zw + vec2<f32>(0.5, 0.5) + uv_xform.xy;
149 let wrap = i32(rot_wrap.y + 0.5);
150 if (wrap == 1) {
151 uv = fract(uv);
152 } else if (wrap == 2) {
153 uv = vec2<f32>(1.0) - abs(fract(uv * 0.5) * 2.0 - vec2<f32>(1.0));
154 }
155 return uv;
156}
157
158fn perturb_bump_normal(
159 base_n: vec3<f32>,
160 dpdx_w: vec3<f32>,
161 dpdy_w: vec3<f32>,
162 duvdx: vec2<f32>,
163 duvdy: vec2<f32>,
164 uv: vec2<f32>,
165 tex_col: vec4<f32>,
166 bump_scale: f32,
167 bump_mode: f32,
168) -> vec3<f32> {
169 let det = duvdx.x * duvdy.y - duvdx.y * duvdy.x;
170 var t_vec: vec3<f32>;
171 var b_vec: vec3<f32>;
172 if (abs(det) > 1e-6) {
173 let inv_det = 1.0 / det;
174 t_vec = (dpdx_w * duvdy.y - dpdy_w * duvdx.y) * inv_det;
175 b_vec = (dpdy_w * duvdx.x - dpdx_w * duvdy.x) * inv_det;
176 // Gram-Schmidt orthogonalize against base_n
177 t_vec = t_vec - base_n * dot(t_vec, base_n);
178 let t_len = length(t_vec);
179 if (t_len > 1e-5) {
180 t_vec = t_vec / t_len;
181 let b_sign = select(-1.0, 1.0, dot(cross(base_n, t_vec), b_vec) >= 0.0);
182 b_vec = cross(base_n, t_vec) * b_sign;
183 } else {
184 let up = select(vec3<f32>(0.0, 1.0, 0.0), vec3<f32>(1.0, 0.0, 0.0), abs(base_n.y) > 0.9);
185 t_vec = normalize(cross(up, base_n));
186 b_vec = cross(base_n, t_vec);
187 }
188 } else {
189 let up = select(vec3<f32>(0.0, 1.0, 0.0), vec3<f32>(1.0, 0.0, 0.0), abs(base_n.y) > 0.9);
190 t_vec = normalize(cross(up, base_n));
191 b_vec = cross(base_n, t_vec);
192 }
193
194 if (bump_mode > 0.5) {
195 let tn_xy = (tex_col.rg * 2.0 - vec2<f32>(1.0)) * bump_scale;
196 let tn_z = max(tex_col.b * 2.0 - 1.0, 0.05);
197 return normalize(t_vec * tn_xy.x + b_vec * tn_xy.y + base_n * tn_z);
198 }
199
200 let inv_dim = vec2<f32>(1.0) / max(vec2<f32>(textureDimensions(mat_tex)), vec2<f32>(1.0));
201 let luma_w = vec3<f32>(0.299, 0.587, 0.114);
202 let h_l = dot(textureSampleLevel(mat_tex, mat_samp, uv - vec2<f32>(inv_dim.x, 0.0), 0.0).rgb, luma_w);
203 let h_r = dot(textureSampleLevel(mat_tex, mat_samp, uv + vec2<f32>(inv_dim.x, 0.0), 0.0).rgb, luma_w);
204 let h_d = dot(textureSampleLevel(mat_tex, mat_samp, uv - vec2<f32>(0.0, inv_dim.y), 0.0).rgb, luma_w);
205 let h_u = dot(textureSampleLevel(mat_tex, mat_samp, uv + vec2<f32>(0.0, inv_dim.y), 0.0).rgb, luma_w);
206 let dhdu = (h_r - h_l) * 0.5 * bump_scale;
207 let dhdv = (h_u - h_d) * 0.5 * bump_scale;
208 return normalize(base_n - t_vec * dhdu - b_vec * dhdv);
209}
210
137211@fragment
138212fn fs_mesh(in: VsOut) -> @location(0) vec4<f32> {
213 let uv_xformed = apply_uv_xform(in.uv, u.uv_xform, u.mat_fx.xy);
214 let dpdx_w = dpdx(in.world_pos);
215 let dpdy_w = dpdy(in.world_pos);
216 let duvdx = dpdx(uv_xformed);
217 let duvdy = dpdy(uv_xformed);
218
139219 var col = u.diffuse_col;
220 var tex_col = vec4<f32>(1.0);
221 var uv_samp = uv_xformed;
140222 if (u.flags.x > 0.5) {
141 var uv = in.uv;
142223 if (u.dod.z > 0.5 && u.dod.w > 0.5) {
143224 let tdims = vec2<f32>(textureDimensions(mat_tex));
144 let canvas_px = vec2<f32>(uv.x * u.dod.z, uv.y * u.dod.w);
145 uv = (canvas_px - u.dod.xy) / tdims;
146 if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0) {
225 let canvas_px = vec2<f32>(uv_samp.x * u.dod.z, uv_samp.y * u.dod.w);
226 uv_samp = (canvas_px - u.dod.xy) / tdims;
227 if (uv_samp.x < 0.0 || uv_samp.x > 1.0 || uv_samp.y < 0.0 || uv_samp.y > 1.0) {
147228 discard;
148229 }
149230 }
150 col = textureSample(mat_tex, mat_samp, uv) * u.diffuse_col;
231 tex_col = textureSampleLevel(mat_tex, mat_samp, uv_samp, 0.0);
232 col = tex_col * u.diffuse_col;
151233 }
152234 if (col.a <= 0.002) {
153235 discard;
......@@ -156,7 +238,20 @@ fn fs_mesh(in: VsOut) -> @location(0) vec4<f32> {
156238 if (u.flags.y > 0.5) {
157239 // Premultiplied -> unpremultiplied albedo for lighting
158240 let albedo = select(vec3<f32>(0.0), col.rgb / max(col.a, 1e-5), col.a > 1e-5);
159 let n = normalize(in.world_n);
241 var n = normalize(in.world_n);
242 if (u.flags.x > 0.5 && abs(u.mat_fx.z) > 1e-5) {
243 n = perturb_bump_normal(
244 n,
245 dpdx_w,
246 dpdy_w,
247 duvdx,
248 duvdy,
249 uv_samp,
250 tex_col,
251 u.mat_fx.z,
252 u.mat_fx.w,
253 );
254 }
160255 let v = normalize(u.cam_pos.xyz - in.world_pos);
161256 let spec_rgb = u.specular_col.rgb;
162257 let shininess = max(u.specular_col.w, 1.0);