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, mtime, obj_name, scale)`, and falls back gracefully
10//! to a unit bounding-box placeholder mesh (never cached) if the file is missing or unreadable.
11
12use std::collections::HashMap;
13use std::path::{Path, PathBuf};
14use std::sync::{Arc, Mutex, OnceLock};
15use std::time::SystemTime;
16
17use super::shader::Vertex3D;
18
19const FBX_BINARY_MAGIC: &[u8; 21] = b"Kaydara FBX Binary \0";
20const MAX_CACHE_ENTRIES: usize = 256;
21const MAX_FBX_DEPTH: usize = 32;
22const MAX_DECOMPRESS_BYTES: usize = 64 * 1024 * 1024;
23const MAX_TRIANGLES: usize = 500_000;
24
25type MeshCacheKey = (PathBuf, Option<SystemTime>, String, u32);
26static MESH_CACHE: OnceLock<Mutex<HashMap<MeshCacheKey, Arc<Vec<Vertex3D>>>>> = OnceLock::new();
27
28/// Loads a `.fbx` or `.obj` mesh (cached), applying `scale_units` (`ScaleFileUnitsBy`).
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.
31pub(super) fn load_mesh_cached(
32 raw_path: &str,
33 comp_path: Option<&Path>,
34 obj_name: Option<&str>,
35 scale_units: f32,
36) -> Arc<Vec<Vertex3D>> {
37 let scale = if scale_units.is_finite() && scale_units.abs() > 1e-7 {
38 scale_units
39 } else {
40 1.0
41 };
42 let resolved = resolve_import_path(raw_path, comp_path);
43 let mtime = resolved.as_ref().and_then(|p| std::fs::metadata(p).and_then(|m| m.modified()).ok());
44 let key = (
45 resolved.clone().unwrap_or_else(|| PathBuf::from(raw_path)),
46 mtime,
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 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 };
70
71 let arc = Arc::new(loaded);
72 if let Ok(mut guard) = cache.lock() {
73 if guard.len() >= MAX_CACHE_ENTRIES {
74 guard.clear();
75 }
76 guard.insert(key, Arc::clone(&arc));
77 }
78 arc
79}
80
81/// Resolves a Fusion `ImportFile` path (supporting `comp:` prefix and relative paths).
82fn resolve_import_path(raw_path: &str, comp_path: Option<&Path>) -> Option<PathBuf> {
83 let trimmed = raw_path.trim();
84 if trimmed.is_empty() {
85 return None;
86 }
87 let normalized = trimmed.replace('\\', "/");
88 let comp_dir = comp_path.and_then(|p| p.parent());
89
90 if let Some(rest) = normalized
91 .strip_prefix("comp:")
92 .or_else(|| normalized.strip_prefix("Comp:"))
93 .or_else(|| normalized.strip_prefix("COMP:"))
94 {
95 let rel = rest.trim_start_matches('/');
96 if let Some(dir) = comp_dir {
97 let candidate = dir.join(rel);
98 if candidate.exists() {
99 return Some(candidate);
100 }
101 return Some(candidate);
102 }
103 return Some(PathBuf::from(rel));
104 }
105
106 let p = PathBuf::from(&normalized);
107 if p.is_absolute() {
108 if p.exists() {
109 return Some(p);
110 }
111 // Fallback: check filename alongside comp file if moved across machines
112 if let (Some(dir), Some(fname)) = (comp_dir, p.file_name()) {
113 let beside = dir.join(fname);
114 if beside.exists() {
115 return Some(beside);
116 }
117 }
118 return Some(p);
119 }
120
121 if let Some(dir) = comp_dir {
122 let candidate = dir.join(&p);
123 if candidate.exists() {
124 return Some(candidate);
125 }
126 }
127 Some(p)
128}
129
130/// Parses OBJ, ASCII FBX, or Binary FBX mesh bytes into an unindexed triangle list of `Vertex3D`.
131pub(super) fn parse_mesh_bytes(
132 bytes: &[u8],
133 ext_hint: Option<&str>,
134 obj_name: Option<&str>,
135 scale_units: f32,
136) -> Option<Vec<Vertex3D>> {
137 if bytes.is_empty() {
138 return None;
139 }
140 let mut verts = if bytes.len() >= FBX_BINARY_MAGIC.len() && &bytes[..FBX_BINARY_MAGIC.len()] == FBX_BINARY_MAGIC {
141 parse_binary_fbx(bytes, obj_name)?
142 } else {
143 let text = std::str::from_utf8(bytes).ok()?;
144 let is_obj = matches!(ext_hint, Some("obj"))
145 || (!text.contains("PolygonVertexIndex:")
146 && !text.contains("FBXHeaderExtension")
147 && text.lines().any(|l| {
148 let t = l.trim_start();
149 t.starts_with("v ") || t.starts_with("f ")
150 }));
151 if is_obj {
152 parse_obj(text, obj_name)?
153 } else {
154 parse_ascii_fbx(text, obj_name)?
155 }
156 };
157
158 if verts.is_empty() {
159 return None;
160 }
161
162 let scale = if scale_units.is_finite() && scale_units.abs() > 1e-7 {
163 scale_units
164 } else {
165 1.0
166 };
167 if (scale - 1.0).abs() > 1e-6 {
168 for v in &mut verts {
169 v.pos[0] *= scale;
170 v.pos[1] *= scale;
171 v.pos[2] *= scale;
172 }
173 }
174 Some(verts)
175}
176
177/// Returns a unit `[-0.5, 0.5]^3` bounding-box placeholder mesh (36 vertices / 12 triangles).
178pub(super) fn unit_box_placeholder() -> Vec<Vertex3D> {
179 let h = 0.5_f32;
180 let faces: [([f32; 3], [[f32; 3]; 4]); 6] = [
181 ([0.0, 0.0, 1.0], [[-h, h, h], [-h, -h, h], [h, -h, h], [h, h, h]]),
182 ([0.0, 0.0, -1.0], [[h, h, -h], [h, -h, -h], [-h, -h, -h], [-h, h, -h]]),
183 ([1.0, 0.0, 0.0], [[h, h, h], [h, -h, h], [h, -h, -h], [h, h, -h]]),
184 ([-1.0, 0.0, 0.0], [[-h, h, -h], [-h, -h, -h], [-h, -h, h], [-h, h, h]]),
185 ([0.0, 1.0, 0.0], [[-h, h, -h], [-h, h, h], [h, h, h], [h, h, -h]]),
186 ([0.0, -1.0, 0.0], [[-h, -h, h], [-h, -h, -h], [h, -h, -h], [h, -h, h]]),
187 ];
188 let uvs = [[0.0, 0.0], [0.0, 1.0], [1.0, 1.0], [1.0, 0.0]];
189 let mut verts = Vec::with_capacity(36);
190 for (n, c) in faces {
191 let q = [
192 Vertex3D { pos: c[0], normal: n, uv: uvs[0] },
193 Vertex3D { pos: c[1], normal: n, uv: uvs[1] },
194 Vertex3D { pos: c[2], normal: n, uv: uvs[2] },
195 Vertex3D { pos: c[3], normal: n, uv: uvs[3] },
196 ];
197 verts.extend_from_slice(&[q[0], q[1], q[2], q[0], q[2], q[3]]);
198 }
199 verts
200}
201
202// ---------------------------------------------------------------------------
203// Wavefront OBJ parser
204// ---------------------------------------------------------------------------
205
206fn parse_obj(text: &str, obj_name: Option<&str>) -> Option<Vec<Vertex3D>> {
207 let mut positions: Vec<[f32; 3]> = Vec::new();
208 let mut normals: Vec<[f32; 3]> = Vec::new();
209 let mut uvs: Vec<[f32; 2]> = Vec::new();
210 let mut all_verts: Vec<Vertex3D> = Vec::new();
211 let mut named_verts: Vec<Vertex3D> = Vec::new();
212 let mut has_any_normal = false;
213 let mut current_obj = String::new();
214 let target = obj_name.map(str::trim).filter(|s| !s.is_empty());
215
216 let resolve_idx = |raw: i32, len: usize| -> Option<usize> {
217 if raw > 0 {
218 let idx = (raw - 1) as usize;
219 (idx < len).then_some(idx)
220 } else if raw < 0 {
221 let offset = raw.unsigned_abs() as usize;
222 len.checked_sub(offset)
223 } else {
224 None
225 }
226 };
227
228 for raw_line in text.lines() {
229 let line = raw_line.split('#').next().unwrap_or("").trim();
230 if line.is_empty() {
231 continue;
232 }
233 let mut parts = line.split_whitespace();
234 let Some(tag) = parts.next() else { continue };
235 match tag {
236 "o" | "g" => {
237 current_obj = parts.next().unwrap_or("").to_string();
238 }
239 "v" => {
240 let (Some(x), Some(y), Some(z)) = (
241 parts.next().and_then(|s| s.parse::<f32>().ok()),
242 parts.next().and_then(|s| s.parse::<f32>().ok()),
243 parts.next().and_then(|s| s.parse::<f32>().ok()),
244 ) else {
245 continue;
246 };
247 positions.push([x, y, z]);
248 }
249 "vn" => {
250 let (Some(x), Some(y), Some(z)) = (
251 parts.next().and_then(|s| s.parse::<f32>().ok()),
252 parts.next().and_then(|s| s.parse::<f32>().ok()),
253 parts.next().and_then(|s| s.parse::<f32>().ok()),
254 ) else {
255 continue;
256 };
257 normals.push(normalize3([x, y, z]));
258 }
259 "vt" => {
260 let (Some(u), Some(v)) = (
261 parts.next().and_then(|s| s.parse::<f32>().ok()),
262 parts.next().and_then(|s| s.parse::<f32>().ok()),
263 ) else {
264 continue;
265 };
266 uvs.push([u, 1.0 - v]);
267 }
268 "f" => {
269 if all_verts.len() / 3 >= MAX_TRIANGLES {
270 break;
271 }
272 let mut face: Vec<Vertex3D> = Vec::new();
273 for tok in parts {
274 let mut segs = tok.split('/');
275 let Some(vi) = segs
276 .next()
277 .and_then(|s| s.parse::<i32>().ok())
278 .and_then(|i| resolve_idx(i, positions.len()))
279 else {
280 continue;
281 };
282 let ti = segs
283 .next()
284 .filter(|s| !s.is_empty())
285 .and_then(|s| s.parse::<i32>().ok())
286 .and_then(|i| resolve_idx(i, uvs.len()));
287 let ni = segs
288 .next()
289 .filter(|s| !s.is_empty())
290 .and_then(|s| s.parse::<i32>().ok())
291 .and_then(|i| resolve_idx(i, normals.len()));
292 let normal = if let Some(idx) = ni {
293 has_any_normal = true;
294 normals[idx]
295 } else {
296 [0.0, 0.0, 0.0]
297 };
298 let uv = ti.map(|idx| uvs[idx]).unwrap_or([0.0, 0.0]);
299 face.push(Vertex3D {
300 pos: positions[vi],
301 normal,
302 uv,
303 });
304 }
305 if face.len() >= 3 {
306 let matches_target = target.is_some_and(|t| {
307 current_obj.eq_ignore_ascii_case(t)
308 });
309 for i in 1..(face.len() - 1) {
310 let tri = [face[0], face[i], face[i + 1]];
311 all_verts.extend_from_slice(&tri);
312 if matches_target {
313 named_verts.extend_from_slice(&tri);
314 }
315 }
316 }
317 }
318 _ => {}
319 }
320 }
321
322 let mut out = if !named_verts.is_empty() {
323 named_verts
324 } else {
325 all_verts
326 };
327 if out.is_empty() {
328 return None;
329 }
330 if !has_any_normal || out.iter().any(|v| vec3_len_sq(v.normal) < 1e-8) {
331 recompute_smooth_normals(&mut out);
332 }
333 Some(out)
334}
335
336// ---------------------------------------------------------------------------
337// Shared FBX geometry assembly
338// ---------------------------------------------------------------------------
339
340#[derive(Default)]
341struct FbxGeometryData {
342 id: i64,
343 name: String,
344 vertices: Vec<f32>,
345 poly_indices: Vec<i32>,
346 normals: Vec<f32>,
347 normal_indices: Vec<i32>,
348 normal_mapping: String,
349 uvs: Vec<f32>,
350 uv_indices: Vec<i32>,
351 uv_mapping: String,
352}
353
354fn assemble_fbx_geometry(g: &FbxGeometryData, out: &mut Vec<Vertex3D>) {
355 let vert_count = g.vertices.len() / 3;
356 if vert_count == 0 || g.poly_indices.is_empty() {
357 return;
358 }
359
360 let norm_by_vert = g.normal_mapping.eq_ignore_ascii_case("ByVertice")
361 || g.normal_mapping.eq_ignore_ascii_case("ByControlPoint");
362 let uv_by_vert = g.uv_mapping.eq_ignore_ascii_case("ByVertice")
363 || g.uv_mapping.eq_ignore_ascii_case("ByControlPoint");
364
365 let mut poly: Vec<(usize, usize)> = Vec::new(); // (vertex_idx, poly_vert_cursor)
366 let mut any_missing_normal = g.normals.len() < 3;
367 let start_len = out.len();
368
369 for (pv_idx, &raw_idx) in g.poly_indices.iter().enumerate() {
370 let is_end = raw_idx < 0;
371 let vi = if is_end { !raw_idx } else { raw_idx };
372 if vi >= 0 && (vi as usize) < vert_count {
373 poly.push((vi as usize, pv_idx));
374 }
375 if is_end {
376 if poly.len() >= 3 && out.len() / 3 < MAX_TRIANGLES {
377 for i in 1..(poly.len() - 1) {
378 for &(v_idx, p_idx) in &[poly[0], poly[i], poly[i + 1]] {
379 let pos = [
380 g.vertices[v_idx * 3],
381 g.vertices[v_idx * 3 + 1],
382 g.vertices[v_idx * 3 + 2],
383 ];
384 let n_slot = if norm_by_vert { v_idx } else { p_idx };
385 let n_resolved = if !g.normal_indices.is_empty() {
386 g.normal_indices
387 .get(n_slot)
388 .copied()
389 .filter(|&idx| idx >= 0)
390 .map(|idx| idx as usize)
391 } else {
392 Some(n_slot)
393 };
394 let normal = if let Some(ni) = n_resolved {
395 if ni * 3 + 2 < g.normals.len() {
396 normalize3([
397 g.normals[ni * 3],
398 g.normals[ni * 3 + 1],
399 g.normals[ni * 3 + 2],
400 ])
401 } else {
402 any_missing_normal = true;
403 [0.0, 0.0, 0.0]
404 }
405 } else {
406 any_missing_normal = true;
407 [0.0, 0.0, 0.0]
408 };
409
410 let uv_slot = if uv_by_vert { v_idx } else { p_idx };
411 let uv_resolved = if !g.uv_indices.is_empty() {
412 g.uv_indices
413 .get(uv_slot)
414 .copied()
415 .filter(|&idx| idx >= 0)
416 .map(|idx| idx as usize)
417 } else {
418 Some(uv_slot)
419 };
420 let uv = if let Some(ti) = uv_resolved {
421 if ti * 2 + 1 < g.uvs.len() {
422 [g.uvs[ti * 2], 1.0 - g.uvs[ti * 2 + 1]]
423 } else {
424 [0.0, 0.0]
425 }
426 } else {
427 [0.0, 0.0]
428 };
429
430 out.push(Vertex3D { pos, normal, uv });
431 }
432 }
433 }
434 poly.clear();
435 }
436 }
437
438 if any_missing_normal && out.len() > start_len {
439 recompute_smooth_normals(&mut out[start_len..]);
440 }
441}
442
443// ---------------------------------------------------------------------------
444// ASCII FBX parser
445// ---------------------------------------------------------------------------
446
447fn parse_ascii_fbx(text: &str, obj_name: Option<&str>) -> Option<Vec<Vertex3D>> {
448 let mut geometries: Vec<FbxGeometryData> = Vec::new();
449
450 // Find each `Geometry:` block; if none exist (minimal buffer), parse whole text as one geometry.
451 let geom_positions: Vec<usize> = text
452 .match_indices("Geometry:")
453 .map(|(idx, _)| idx)
454 .collect();
455
456 if geom_positions.is_empty() {
457 let g = parse_ascii_fbx_geometry_slice("", text);
458 if !g.vertices.is_empty() && !g.poly_indices.is_empty() {
459 geometries.push(g);
460 }
461 } else {
462 for &start in &geom_positions {
463 let slice = &text[start..];
464 let Some(open_brace) = slice.find('{') else {
465 continue;
466 };
467 let header = &slice[..open_brace];
468 let name = extract_fbx_quoted_name(header);
469 let block_end = find_matching_brace(slice, open_brace).unwrap_or(slice.len());
470 let body = &slice[open_brace + 1..block_end];
471 let g = parse_ascii_fbx_geometry_slice(&name, body);
472 if !g.vertices.is_empty() && !g.poly_indices.is_empty() {
473 geometries.push(g);
474 }
475 }
476 }
477
478 if geometries.is_empty() {
479 return None;
480 }
481
482 let target = obj_name.map(str::trim).filter(|s| !s.is_empty());
483 let mut out = Vec::new();
484 if let Some(t) = target {
485 for g in &geometries {
486 if fbx_name_matches(&g.name, t) {
487 assemble_fbx_geometry(g, &mut out);
488 }
489 }
490 }
491 if out.is_empty() {
492 for g in &geometries {
493 assemble_fbx_geometry(g, &mut out);
494 }
495 }
496 (!out.is_empty()).then_some(out)
497}
498
499fn parse_ascii_fbx_geometry_slice(name: &str, body: &str) -> FbxGeometryData {
500 let mut g = FbxGeometryData {
501 name: name.to_string(),
502 ..Default::default()
503 };
504 if let Some(nums) = extract_ascii_fbx_f32_array(body, "Vertices:") {
505 g.vertices = nums;
506 }
507 if let Some(nums) = extract_ascii_fbx_i32_array(body, "PolygonVertexIndex:") {
508 g.poly_indices = nums;
509 }
510 if let Some(sub) = extract_ascii_fbx_block(body, "LayerElementNormal:") {
511 g.normal_mapping = extract_ascii_fbx_string_prop(sub, "MappingInformationType:").unwrap_or_default();
512 if let Some(nums) = extract_ascii_fbx_f32_array(sub, "Normals:") {
513 g.normals = nums;
514 }
515 if let Some(nums) = extract_ascii_fbx_i32_array(sub, "NormalsIndex:") {
516 g.normal_indices = nums;
517 }
518 } else if let Some(nums) = extract_ascii_fbx_f32_array(body, "Normals:") {
519 g.normals = nums;
520 g.normal_mapping = extract_ascii_fbx_string_prop(body, "MappingInformationType:").unwrap_or_default();
521 }
522 if let Some(sub) = extract_ascii_fbx_block(body, "LayerElementUV:") {
523 g.uv_mapping = extract_ascii_fbx_string_prop(sub, "MappingInformationType:").unwrap_or_default();
524 if let Some(nums) = extract_ascii_fbx_f32_array(sub, "UV:") {
525 g.uvs = nums;
526 }
527 if let Some(nums) = extract_ascii_fbx_i32_array(sub, "UVIndex:") {
528 g.uv_indices = nums;
529 }
530 } else if let Some(nums) = extract_ascii_fbx_f32_array(body, "UV:") {
531 g.uvs = nums;
532 }
533 g
534}
535
536fn find_matching_brace(s: &str, open_idx: usize) -> Option<usize> {
537 let mut depth = 0usize;
538 let mut in_str = false;
539 for (i, b) in s.bytes().enumerate().skip(open_idx) {
540 if b == b'"' {
541 in_str = !in_str;
542 continue;
543 }
544 if in_str {
545 continue;
546 }
547 if b == b'{' {
548 depth += 1;
549 } else if b == b'}' {
550 depth = depth.saturating_sub(1);
551 if depth == 0 {
552 return Some(i);
553 }
554 }
555 }
556 None
557}
558
559fn extract_ascii_fbx_block<'a>(body: &'a str, key: &str) -> Option<&'a str> {
560 let idx = body.find(key)?;
561 let slice = &body[idx..];
562 let open = slice.find('{')?;
563 let close = find_matching_brace(slice, open)?;
564 Some(&slice[open + 1..close])
565}
566
567fn extract_ascii_fbx_string_prop(body: &str, key: &str) -> Option<String> {
568 let idx = body.find(key)?;
569 let rest = &body[idx + key.len()..];
570 let line = rest.lines().next()?;
571 let q1 = line.find('"')?;
572 let after = &line[q1 + 1..];
573 let q2 = after.find('"')?;
574 Some(after[..q2].to_string())
575}
576
577fn extract_ascii_fbx_array_str<'a>(body: &'a str, key: &str) -> Option<&'a str> {
578 let idx = body.find(key)?;
579 let rest = body[idx + key.len()..].trim_start();
580 if rest.starts_with('*') {
581 let open = rest.find('{')?;
582 let close = find_matching_brace(rest, open)?;
583 let inner = &rest[open + 1..close];
584 if let Some(a_pos) = inner.find("a:") {
585 return Some(&inner[a_pos + 2..]);
586 }
587 return Some(inner);
588 }
589 // Older ASCII FBX format: `Vertices: x,y,z,...` until next non-number line or closing brace
590 let mut end = rest.len();
591 for (i, b) in rest.bytes().enumerate() {
592 if b == b'}' || (b.is_ascii_alphabetic() && b != b'e' && b != b'E') {
593 end = i;
594 break;
595 }
596 }
597 Some(&rest[..end])
598}
599
600fn extract_ascii_fbx_f32_array(body: &str, key: &str) -> Option<Vec<f32>> {
601 let raw = extract_ascii_fbx_array_str(body, key)?;
602 let mut out = Vec::new();
603 for tok in raw.split(|c: char| c == ',' || c.is_ascii_whitespace()) {
604 if tok.is_empty() {
605 continue;
606 }
607 if let Ok(v) = tok.parse::<f32>() {
608 out.push(v);
609 }
610 }
611 (!out.is_empty()).then_some(out)
612}
613
614fn extract_ascii_fbx_i32_array(body: &str, key: &str) -> Option<Vec<i32>> {
615 let raw = extract_ascii_fbx_array_str(body, key)?;
616 let mut out = Vec::new();
617 for tok in raw.split(|c: char| c == ',' || c.is_ascii_whitespace()) {
618 if tok.is_empty() {
619 continue;
620 }
621 if let Ok(v) = tok.parse::<i32>() {
622 out.push(v);
623 }
624 }
625 (!out.is_empty()).then_some(out)
626}
627
628fn extract_fbx_quoted_name(header: &str) -> String {
629 let mut iter = header.split('"');
630 let _ = iter.next();
631 let raw = iter.next().unwrap_or("");
632 clean_fbx_symbol_name(raw)
633}
634
635fn clean_fbx_symbol_name(raw: &str) -> String {
636 // Binary FBX names often look like "Cube\x00\x01Geometry"; ASCII FBX like "Geometry::Cube"
637 let base = raw.split('\0').next().unwrap_or(raw);
638 base.rsplit("::").next().unwrap_or(base).trim().to_string()
639}
640
641fn fbx_name_matches(candidate: &str, target: &str) -> bool {
642 let c = clean_fbx_symbol_name(candidate);
643 let t = clean_fbx_symbol_name(target);
644 !c.is_empty() && c.eq_ignore_ascii_case(&t)
645}
646
647// ---------------------------------------------------------------------------
648// Binary FBX parser (v7100 - v7700+)
649// ---------------------------------------------------------------------------
650
651#[derive(Debug)]
652enum FbxProp {
653 I64(i64),
654 Str(String),
655 F32Array(Vec<f32>),
656 I32Array(Vec<i32>),
657 Other,
658}
659
660#[derive(Debug)]
661struct FbxBinNode {
662 name: String,
663 props: Vec<FbxProp>,
664 children: Vec<FbxBinNode>,
665}
666
667fn parse_binary_fbx(bytes: &[u8], obj_name: Option<&str>) -> Option<Vec<Vertex3D>> {
668 if bytes.len() < 27 || &bytes[..21] != FBX_BINARY_MAGIC {
669 return None;
670 }
671 let version = u32::from_le_bytes(bytes[23..27].try_into().ok()?);
672 let is_64 = version >= 7500;
673 let mut pos = 27usize;
674 let mut root_nodes = Vec::new();
675
676 while pos < bytes.len() {
677 let Some(node) = read_fbx_bin_node(bytes, &mut pos, is_64, 0) else {
678 break;
679 };
680 root_nodes.push(node);
681 }
682
683 let mut geometries: Vec<FbxGeometryData> = Vec::new();
684 let mut model_names: HashMap<i64, String> = HashMap::new();
685 let mut geom_to_model: HashMap<i64, i64> = HashMap::new();
686
687 for node in &root_nodes {
688 match node.name.as_str() {
689 "Objects" => {
690 for child in &node.children {
691 if child.name == "Geometry" {
692 let g = extract_bin_geometry(child);
693 if !g.vertices.is_empty() && !g.poly_indices.is_empty() {
694 geometries.push(g);
695 }
696 } else if child.name == "Model" {
697 if let (Some(FbxProp::I64(id)), Some(FbxProp::Str(s))) =
698 (child.props.first(), child.props.get(1))
699 {
700 model_names.insert(*id, clean_fbx_symbol_name(s));
701 }
702 }
703 }
704 }
705 "Connections" => {
706 for c in &node.children {
707 if c.name == "C" {
708 if let (Some(FbxProp::I64(child_id)), Some(FbxProp::I64(parent_id))) =
709 (c.props.get(1), c.props.get(2))
710 {
711 geom_to_model.insert(*child_id, *parent_id);
712 }
713 }
714 }
715 }
716 _ => {}
717 }
718 }
719
720 if geometries.is_empty() {
721 return None;
722 }
723
724 let target = obj_name.map(str::trim).filter(|s| !s.is_empty());
725 let mut out = Vec::new();
726 if let Some(t) = target {
727 for g in &geometries {
728 let model_match = geom_to_model
729 .get(&g.id)
730 .and_then(|mid| model_names.get(mid))
731 .is_some_and(|mn| fbx_name_matches(mn, t));
732 if fbx_name_matches(&g.name, t) || model_match {
733 assemble_fbx_geometry(g, &mut out);
734 }
735 }
736 }
737 if out.is_empty() {
738 for g in &geometries {
739 assemble_fbx_geometry(g, &mut out);
740 }
741 }
742 (!out.is_empty()).then_some(out)
743}
744
745fn extract_bin_geometry(node: &FbxBinNode) -> FbxGeometryData {
746 let mut g = FbxGeometryData::default();
747 if let Some(FbxProp::I64(id)) = node.props.first() {
748 g.id = *id;
749 }
750 for p in &node.props {
751 if let FbxProp::Str(s) = p {
752 let cleaned = clean_fbx_symbol_name(s);
753 if !cleaned.is_empty() && !cleaned.eq_ignore_ascii_case("Mesh") {
754 g.name = cleaned;
755 break;
756 }
757 }
758 }
759 for child in &node.children {
760 match child.name.as_str() {
761 "Vertices" => {
762 if let Some(FbxProp::F32Array(arr)) = child.props.first() {
763 g.vertices = arr.clone();
764 }
765 }
766 "PolygonVertexIndex" => {
767 if let Some(FbxProp::I32Array(arr)) = child.props.first() {
768 g.poly_indices = arr.clone();
769 }
770 }
771 "LayerElementNormal" => {
772 for sub in &child.children {
773 match sub.name.as_str() {
774 "MappingInformationType" => {
775 if let Some(FbxProp::Str(s)) = sub.props.first() {
776 g.normal_mapping = s.clone();
777 }
778 }
779 "Normals" => {
780 if let Some(FbxProp::F32Array(arr)) = sub.props.first() {
781 g.normals = arr.clone();
782 }
783 }
784 "NormalsIndex" => {
785 if let Some(FbxProp::I32Array(arr)) = sub.props.first() {
786 g.normal_indices = arr.clone();
787 }
788 }
789 _ => {}
790 }
791 }
792 }
793 "LayerElementUV" => {
794 if !g.uvs.is_empty() {
795 continue;
796 }
797 for sub in &child.children {
798 match sub.name.as_str() {
799 "MappingInformationType" => {
800 if let Some(FbxProp::Str(s)) = sub.props.first() {
801 g.uv_mapping = s.clone();
802 }
803 }
804 "UV" => {
805 if let Some(FbxProp::F32Array(arr)) = sub.props.first() {
806 g.uvs = arr.clone();
807 }
808 }
809 "UVIndex" => {
810 if let Some(FbxProp::I32Array(arr)) = sub.props.first() {
811 g.uv_indices = arr.clone();
812 }
813 }
814 _ => {}
815 }
816 }
817 }
818 _ => {}
819 }
820 }
821 g
822}
823
824fn read_fbx_bin_node(
825 bytes: &[u8],
826 pos: &mut usize,
827 is_64: bool,
828 depth: usize,
829) -> Option<FbxBinNode> {
830 if depth > MAX_FBX_DEPTH {
831 return None;
832 }
833 let sentinel_len = if is_64 { 25usize } else { 13usize };
834 if *pos + sentinel_len > bytes.len() {
835 return None;
836 }
837
838 let (end_offset, num_props, prop_list_len, name_len) = if is_64 {
839 let eo = u64::from_le_bytes(bytes[*pos..*pos + 8].try_into().ok()?) as usize;
840 let np = u64::from_le_bytes(bytes[*pos + 8..*pos + 16].try_into().ok()?) as usize;
841 let pl = u64::from_le_bytes(bytes[*pos + 16..*pos + 24].try_into().ok()?) as usize;
842 let nl = bytes[*pos + 24] as usize;
843 *pos += 25;
844 (eo, np, pl, nl)
845 } else {
846 let eo = u32::from_le_bytes(bytes[*pos..*pos + 4].try_into().ok()?) as usize;
847 let np = u32::from_le_bytes(bytes[*pos + 4..*pos + 8].try_into().ok()?) as usize;
848 let pl = u32::from_le_bytes(bytes[*pos + 8..*pos + 12].try_into().ok()?) as usize;
849 let nl = bytes[*pos + 12] as usize;
850 *pos += 13;
851 (eo, np, pl, nl)
852 };
853
854 // Null sentinel marks end of sibling list
855 if end_offset == 0 && num_props == 0 && prop_list_len == 0 && name_len == 0 {
856 return None;
857 }
858 if end_offset > bytes.len() || *pos + name_len > end_offset {
859 return None;
860 }
861
862 let name = String::from_utf8_lossy(&bytes[*pos..*pos + name_len]).into_owned();
863 *pos += name_len;
864
865 let props_end = (*pos).saturating_add(prop_list_len).min(end_offset);
866 let mut props = Vec::with_capacity(num_props.min(64));
867 for _ in 0..num_props {
868 if *pos >= props_end {
869 break;
870 }
871 let Some(p) = read_fbx_bin_prop(bytes, pos, props_end) else {
872 break;
873 };
874 props.push(p);
875 }
876 *pos = props_end;
877
878 let mut children = Vec::new();
879 while *pos + sentinel_len <= end_offset {
880 let Some(child) = read_fbx_bin_node(bytes, pos, is_64, depth + 1) else {
881 break;
882 };
883 children.push(child);
884 }
885 *pos = end_offset;
886
887 Some(FbxBinNode {
888 name,
889 props,
890 children,
891 })
892}
893
894fn read_fbx_bin_prop(bytes: &[u8], pos: &mut usize, limit: usize) -> Option<FbxProp> {
895 if *pos >= limit {
896 return None;
897 }
898 let tag = bytes[*pos];
899 *pos += 1;
900 match tag {
901 b'Y' => {
902 if *pos + 2 > limit { return None; }
903 let v = i16::from_le_bytes(bytes[*pos..*pos + 2].try_into().ok()?);
904 *pos += 2;
905 Some(FbxProp::I64(v as i64))
906 }
907 b'C' => {
908 if *pos + 1 > limit { return None; }
909 let v = bytes[*pos];
910 *pos += 1;
911 Some(FbxProp::I64(v as i64))
912 }
913 b'I' => {
914 if *pos + 4 > limit { return None; }
915 let v = i32::from_le_bytes(bytes[*pos..*pos + 4].try_into().ok()?);
916 *pos += 4;
917 Some(FbxProp::I64(v as i64))
918 }
919 b'F' => {
920 if *pos + 4 > limit { return None; }
921 *pos += 4;
922 Some(FbxProp::Other)
923 }
924 b'D' => {
925 if *pos + 8 > limit { return None; }
926 *pos += 8;
927 Some(FbxProp::Other)
928 }
929 b'L' => {
930 if *pos + 8 > limit { return None; }
931 let v = i64::from_le_bytes(bytes[*pos..*pos + 8].try_into().ok()?);
932 *pos += 8;
933 Some(FbxProp::I64(v))
934 }
935 b'S' | b'R' => {
936 if *pos + 4 > limit { return None; }
937 let len = u32::from_le_bytes(bytes[*pos..*pos + 4].try_into().ok()?) as usize;
938 *pos += 4;
939 if *pos + len > limit { return None; }
940 let slice = &bytes[*pos..*pos + len];
941 *pos += len;
942 if tag == b'S' {
943 Some(FbxProp::Str(String::from_utf8_lossy(slice).into_owned()))
944 } else {
945 Some(FbxProp::Other)
946 }
947 }
948 b'f' | b'd' | b'i' | b'l' | b'b' => {
949 if *pos + 12 > limit { return None; }
950 let array_len = u32::from_le_bytes(bytes[*pos..*pos + 4].try_into().ok()?) as usize;
951 let encoding = u32::from_le_bytes(bytes[*pos + 4..*pos + 8].try_into().ok()?);
952 let comp_len = u32::from_le_bytes(bytes[*pos + 8..*pos + 12].try_into().ok()?) as usize;
953 *pos += 12;
954 if *pos + comp_len > limit { return None; }
955 let raw_slice = &bytes[*pos..*pos + comp_len];
956 *pos += comp_len;
957
958 let elem_size = match tag {
959 b'b' => 1usize,
960 b'f' | b'i' => 4usize,
961 b'd' | b'l' => 8usize,
962 _ => return Some(FbxProp::Other),
963 };
964 let expected_bytes = array_len.checked_mul(elem_size)?;
965 if expected_bytes > MAX_DECOMPRESS_BYTES {
966 return Some(FbxProp::Other);
967 }
968
969 let decoded_owned;
970 let data: &[u8] = if encoding == 0 {
971 if raw_slice.len() < expected_bytes {
972 return Some(FbxProp::Other);
973 }
974 &raw_slice[..expected_bytes]
975 } else if encoding == 1 {
976 let Some(buf) = zlib_decompress(raw_slice, expected_bytes) else {
977 return Some(FbxProp::Other);
978 };
979 if buf.len() < expected_bytes {
980 return Some(FbxProp::Other);
981 }
982 decoded_owned = buf;
983 &decoded_owned[..expected_bytes]
984 } else {
985 return Some(FbxProp::Other);
986 };
987
988 match tag {
989 b'f' => {
990 let mut out = Vec::with_capacity(array_len);
991 for c in data.chunks_exact(4) {
992 out.push(f32::from_le_bytes([c[0], c[1], c[2], c[3]]));
993 }
994 Some(FbxProp::F32Array(out))
995 }
996 b'd' => {
997 let mut out = Vec::with_capacity(array_len);
998 for c in data.chunks_exact(8) {
999 out.push(f64::from_le_bytes([c[0], c[1], c[2], c[3], c[4], c[5], c[6], c[7]]) as f32);
1000 }
1001 Some(FbxProp::F32Array(out))
1002 }
1003 b'i' => {
1004 let mut out = Vec::with_capacity(array_len);
1005 for c in data.chunks_exact(4) {
1006 out.push(i32::from_le_bytes([c[0], c[1], c[2], c[3]]));
1007 }
1008 Some(FbxProp::I32Array(out))
1009 }
1010 _ => Some(FbxProp::Other),
1011 }
1012 }
1013 _ => None,
1014 }
1015}
1016
1017// ---------------------------------------------------------------------------
1018// Minimal pure-Rust RFC 1950 (zlib) + RFC 1951 (DEFLATE) inflater
1019// ---------------------------------------------------------------------------
1020
1021struct BitReader<'a> {
1022 data: &'a [u8],
1023 byte_pos: usize,
1024 bit_buf: u32,
1025 bit_count: u8,
1026}
1027
1028impl<'a> BitReader<'a> {
1029 fn new(data: &'a [u8]) -> Self {
1030 Self { data, byte_pos: 0, bit_buf: 0, bit_count: 0 }
1031 }
1032
1033 fn read_bits(&mut self, n: u8) -> Option<u32> {
1034 while self.bit_count < n {
1035 let b = *self.data.get(self.byte_pos)?;
1036 self.byte_pos += 1;
1037 self.bit_buf |= (b as u32) << self.bit_count;
1038 self.bit_count += 8;
1039 }
1040 let val = self.bit_buf & ((1u32 << n) - 1);
1041 self.bit_buf >>= n;
1042 self.bit_count -= n;
1043 Some(val)
1044 }
1045
1046 fn align_byte(&mut self) {
1047 let drop = self.bit_count % 8;
1048 self.bit_buf >>= drop;
1049 self.bit_count -= drop;
1050 }
1051
1052 fn read_aligned_bytes(&mut self, n: usize) -> Option<Vec<u8>> {
1053 self.align_byte();
1054 let mut out = Vec::with_capacity(n);
1055 while out.len() < n && self.bit_count >= 8 {
1056 out.push((self.bit_buf & 0xFF) as u8);
1057 self.bit_buf >>= 8;
1058 self.bit_count -= 8;
1059 }
1060 let rem = n - out.len();
1061 if self.byte_pos + rem > self.data.len() {
1062 return None;
1063 }
1064 out.extend_from_slice(&self.data[self.byte_pos..self.byte_pos + rem]);
1065 self.byte_pos += rem;
1066 Some(out)
1067 }
1068}
1069
1070struct HuffTree {
1071 counts: [u16; 16],
1072 symbols: Vec<u16>,
1073}
1074
1075impl HuffTree {
1076 fn build(lengths: &[u8]) -> Option<Self> {
1077 let mut counts = [0u16; 16];
1078 for &l in lengths {
1079 if l as usize >= 16 {
1080 return None;
1081 }
1082 if l > 0 {
1083 counts[l as usize] += 1;
1084 }
1085 }
1086 let mut offsets = [0usize; 16];
1087 let mut total = 0usize;
1088 for bits in 1..16 {
1089 offsets[bits] = total;
1090 total += counts[bits] as usize;
1091 }
1092 let mut symbols = vec![0u16; total];
1093 for (sym, &l) in lengths.iter().enumerate() {
1094 if l > 0 {
1095 let idx = offsets[l as usize];
1096 symbols[idx] = sym as u16;
1097 offsets[l as usize] += 1;
1098 }
1099 }
1100 Some(Self { counts, symbols })
1101 }
1102
1103 fn decode(&self, br: &mut BitReader<'_>) -> Option<u16> {
1104 let mut code = 0i32;
1105 let mut first = 0i32;
1106 let mut index = 0usize;
1107 for len in 1..16 {
1108 code |= br.read_bits(1)? as i32;
1109 let count = self.counts[len] as i32;
1110 if code - count < first {
1111 return self.symbols.get(index + (code - first) as usize).copied();
1112 }
1113 index += count as usize;
1114 first = (first + count) << 1;
1115 code <<= 1;
1116 }
1117 None
1118 }
1119}
1120
1121fn zlib_decompress(input: &[u8], max_out: usize) -> Option<Vec<u8>> {
1122 if input.len() < 6 {
1123 return None;
1124 }
1125 let cmf = input[0];
1126 let flg = input[1];
1127 if (cmf & 0x0F) != 8 || (((cmf as u16) * 256 + flg as u16) % 31) != 0 {
1128 return None;
1129 }
1130 let start = if (flg & 0x20) != 0 { 6 } else { 2 };
1131 if start > input.len() {
1132 return None;
1133 }
1134
1135 let mut br = BitReader::new(&input[start..]);
1136 let mut out = Vec::with_capacity(max_out.min(1024 * 1024));
1137 let cap = max_out.min(MAX_DECOMPRESS_BYTES);
1138
1139 const LEN_BASE: [u16; 29] = [
1140 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
1141 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258,
1142 ];
1143 const LEN_EXTRA: [u8; 29] = [
1144 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2,
1145 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0,
1146 ];
1147 const DIST_BASE: [u16; 30] = [
1148 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
1149 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577,
1150 ];
1151 const DIST_EXTRA: [u8; 30] = [
1152 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6,
1153 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13,
1154 ];
1155 const CL_ORDER: [usize; 19] = [
1156 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15,
1157 ];
1158
1159 loop {
1160 let bfinal = br.read_bits(1)?;
1161 let btype = br.read_bits(2)?;
1162 match btype {
1163 0 => {
1164 let hdr = br.read_aligned_bytes(4)?;
1165 let len = u16::from_le_bytes([hdr[0], hdr[1]]) as usize;
1166 let nlen = u16::from_le_bytes([hdr[2], hdr[3]]);
1167 if (len as u16) != !nlen || out.len() + len > cap {
1168 return None;
1169 }
1170 let block = br.read_aligned_bytes(len)?;
1171 out.extend_from_slice(&block);
1172 }
1173 1 | 2 => {
1174 let (lit_tree, dist_tree) = if btype == 1 {
1175 let mut ll = [0u8; 288];
1176 ll[..144].fill(8);
1177 ll[144..256].fill(9);
1178 ll[256..280].fill(7);
1179 ll[280..288].fill(8);
1180 let dl = [5u8; 32];
1181 (HuffTree::build(&ll)?, HuffTree::build(&dl)?)
1182 } else {
1183 let hlit = br.read_bits(5)? as usize + 257;
1184 let hdist = br.read_bits(5)? as usize + 1;
1185 let hclen = br.read_bits(4)? as usize + 4;
1186 let mut cl = [0u8; 19];
1187 for i in 0..hclen {
1188 cl[CL_ORDER[i]] = br.read_bits(3)? as u8;
1189 }
1190 let cl_tree = HuffTree::build(&cl)?;
1191 let total = hlit + hdist;
1192 let mut lengths = Vec::with_capacity(total);
1193 while lengths.len() < total {
1194 let sym = cl_tree.decode(&mut br)?;
1195 match sym {
1196 0..=15 => lengths.push(sym as u8),
1197 16 => {
1198 let prev = *lengths.last()?;
1199 let rep = br.read_bits(2)? as usize + 3;
1200 for _ in 0..rep {
1201 lengths.push(prev);
1202 }
1203 }
1204 17 => {
1205 let rep = br.read_bits(3)? as usize + 3;
1206 lengths.resize(lengths.len() + rep, 0);
1207 }
1208 18 => {
1209 let rep = br.read_bits(7)? as usize + 11;
1210 lengths.resize(lengths.len() + rep, 0);
1211 }
1212 _ => return None,
1213 }
1214 }
1215 if lengths.len() < total {
1216 return None;
1217 }
1218 (
1219 HuffTree::build(&lengths[..hlit])?,
1220 HuffTree::build(&lengths[hlit..total])?,
1221 )
1222 };
1223
1224 loop {
1225 let sym = lit_tree.decode(&mut br)?;
1226 if sym < 256 {
1227 if out.len() >= cap {
1228 return None;
1229 }
1230 out.push(sym as u8);
1231 } else if sym == 256 {
1232 break;
1233 } else {
1234 let li = (sym as usize).checked_sub(257)?;
1235 if li >= LEN_BASE.len() {
1236 return None;
1237 }
1238 let length = LEN_BASE[li] as usize
1239 + br.read_bits(LEN_EXTRA[li])? as usize;
1240 let di = dist_tree.decode(&mut br)? as usize;
1241 if di >= DIST_BASE.len() {
1242 return None;
1243 }
1244 let dist = DIST_BASE[di] as usize
1245 + br.read_bits(DIST_EXTRA[di])? as usize;
1246 if dist == 0 || dist > out.len() || out.len() + length > cap {
1247 return None;
1248 }
1249 for _ in 0..length {
1250 let b = out[out.len() - dist];
1251 out.push(b);
1252 }
1253 }
1254 }
1255 }
1256 _ => return None,
1257 }
1258 if bfinal != 0 {
1259 break;
1260 }
1261 }
1262 Some(out)
1263}
1264
1265// ---------------------------------------------------------------------------
1266// Normal recomputation helpers
1267// ---------------------------------------------------------------------------
1268
1269#[inline]
1270fn vec3_len_sq(v: [f32; 3]) -> f32 {
1271 v[0] * v[0] + v[1] * v[1] + v[2] * v[2]
1272}
1273
1274#[inline]
1275fn normalize3(v: [f32; 3]) -> [f32; 3] {
1276 let len = vec3_len_sq(v).sqrt();
1277 if len > 1e-6 {
1278 [v[0] / len, v[1] / len, v[2] / len]
1279 } else {
1280 [0.0, 0.0, 1.0]
1281 }
1282}
1283
1284fn quantize_pos(p: [f32; 3]) -> (i64, i64, i64) {
1285 (
1286 (p[0] * 10_000.0).round() as i64,
1287 (p[1] * 10_000.0).round() as i64,
1288 (p[2] * 10_000.0).round() as i64,
1289 )
1290}
1291
1292/// Recomputes smooth vertex normals by accumulating face normals at coincident vertex positions.
1293pub(super) fn recompute_smooth_normals(verts: &mut [Vertex3D]) {
1294 let mut acc: HashMap<(i64, i64, i64), [f32; 3]> = HashMap::new();
1295 for tri in verts.chunks_exact(3) {
1296 let p0 = tri[0].pos;
1297 let p1 = tri[1].pos;
1298 let p2 = tri[2].pos;
1299 let e1 = [p1[0] - p0[0], p1[1] - p0[1], p1[2] - p0[2]];
1300 let e2 = [p2[0] - p0[0], p2[1] - p0[1], p2[2] - p0[2]];
1301 let fn_v = [
1302 e1[1] * e2[2] - e1[2] * e2[1],
1303 e1[2] * e2[0] - e1[0] * e2[2],
1304 e1[0] * e2[1] - e1[1] * e2[0],
1305 ];
1306 for v in tri {
1307 let entry = acc.entry(quantize_pos(v.pos)).or_insert([0.0; 3]);
1308 entry[0] += fn_v[0];
1309 entry[1] += fn_v[1];
1310 entry[2] += fn_v[2];
1311 }
1312 }
1313 for v in verts.iter_mut() {
1314 if let Some(&n) = acc.get(&quantize_pos(v.pos)) {
1315 v.normal = normalize3(n);
1316 } else {
1317 v.normal = [0.0, 0.0, 1.0];
1318 }
1319 }
1320}
1321
1322#[cfg(test)]
1323mod tests {
1324 use super::*;
1325
1326 fn build_synthetic_binary_fbx(version: u32, compressed: bool) -> Vec<u8> {
1327 let is_64 = version >= 7500;
1328 let mut out = Vec::new();
1329 out.extend_from_slice(FBX_BINARY_MAGIC);
1330 out.extend_from_slice(&[0x1A, 0x00]);
1331 out.extend_from_slice(&version.to_le_bytes());
1332
1333 fn encode_node(
1334 name: &str,
1335 props: &[Vec<u8>],
1336 children: &[Vec<u8>],
1337 base_offset: usize,
1338 is_64: bool,
1339 ) -> Vec<u8> {
1340 let hdr_len = if is_64 { 25usize } else { 13usize };
1341 let prop_bytes: usize = props.iter().map(|p| p.len()).sum();
1342 let children_start = base_offset + hdr_len + name.len() + prop_bytes;
1343 let mut children_buf = Vec::new();
1344 let mut cur = children_start;
1345 for c in children {
1346 let _ = cur;
1347 children_buf.extend_from_slice(c);
1348 cur += c.len();
1349 }
1350 if !children.is_empty() {
1351 children_buf.resize(children_buf.len() + hdr_len, 0);
1352 }
1353 let end_offset = children_start + children_buf.len();
1354
1355 let mut buf = Vec::new();
1356 if is_64 {
1357 buf.extend_from_slice(&(end_offset as u64).to_le_bytes());
1358 buf.extend_from_slice(&(props.len() as u64).to_le_bytes());
1359 buf.extend_from_slice(&(prop_bytes as u64).to_le_bytes());
1360 } else {
1361 buf.extend_from_slice(&(end_offset as u32).to_le_bytes());
1362 buf.extend_from_slice(&(props.len() as u32).to_le_bytes());
1363 buf.extend_from_slice(&(prop_bytes as u32).to_le_bytes());
1364 }
1365 buf.push(name.len() as u8);
1366 buf.extend_from_slice(name.as_bytes());
1367 for p in props {
1368 buf.extend_from_slice(p);
1369 }
1370 buf.extend_from_slice(&children_buf);
1371 buf
1372 }
1373
1374 // Build a stored zlib stream for testing encoding==1 without external crates
1375 fn zlib_stored(raw: &[u8]) -> Vec<u8> {
1376 let mut z = vec![0x78, 0x01]; // zlib header: CMF=0x78, FLG=0x01
1377 z.push(0x01); // BFINAL=1, BTYPE=00 (stored)
1378 let len = raw.len() as u16;
1379 z.extend_from_slice(&len.to_le_bytes());
1380 z.extend_from_slice(&(!len).to_le_bytes());
1381 z.extend_from_slice(raw);
1382 z.extend_from_slice(&[0, 0, 0, 0]); // placeholder adler32 (unchecked by reader)
1383 z
1384 }
1385
1386 fn make_array_prop(tag: u8, count: u32, raw: &[u8], compressed: bool) -> Vec<u8> {
1387 let payload = if compressed { zlib_stored(raw) } else { raw.to_vec() };
1388 let mut p = vec![tag];
1389 p.extend_from_slice(&count.to_le_bytes());
1390 p.extend_from_slice(&(if compressed { 1u32 } else { 0u32 }).to_le_bytes());
1391 p.extend_from_slice(&(payload.len() as u32).to_le_bytes());
1392 p.extend_from_slice(&payload);
1393 p
1394 }
1395
1396 // Quad in XY plane (4 vertices, 2 triangles when fan-triangulated)
1397 let verts_f64: [f64; 12] = [
1398 0.0, 0.0, 0.0,
1399 1.0, 0.0, 0.0,
1400 1.0, 1.0, 0.0,
1401 0.0, 1.0, 0.0,
1402 ];
1403 let mut vraw = Vec::new();
1404 for v in verts_f64 {
1405 vraw.extend_from_slice(&v.to_le_bytes());
1406 }
1407 // Quad polygon: [0, 1, 2, !3] -> [0, 1, 2, -4]
1408 let poly_i32: [i32; 4] = [0, 1, 2, !3];
1409 let mut iraw = Vec::new();
1410 for i in poly_i32 {
1411 iraw.extend_from_slice(&i.to_le_bytes());
1412 }
1413
1414 let hdr_len = if is_64 { 25usize } else { 13usize };
1415 let objects_start = out.len();
1416 let geom_start = objects_start + hdr_len + "Objects".len();
1417
1418 let mut id_prop = vec![b'L'];
1419 id_prop.extend_from_slice(&1001i64.to_le_bytes());
1420 let gname = b"TestQuad\0\x01Geometry";
1421 let mut name_prop = vec![b'S'];
1422 name_prop.extend_from_slice(&(gname.len() as u32).to_le_bytes());
1423 name_prop.extend_from_slice(gname);
1424
1425 let vprop = make_array_prop(b'd', 12, &vraw, compressed);
1426 let iprop = make_array_prop(b'i', 4, &iraw, compressed);
1427
1428 let geom_children_start = geom_start + hdr_len + "Geometry".len() + id_prop.len() + name_prop.len();
1429 let v_node = encode_node("Vertices", &[vprop], &[], geom_children_start, is_64);
1430 let i_node = encode_node("PolygonVertexIndex", &[iprop], &[], geom_children_start + v_node.len(), is_64);
1431
1432 let geom_node = encode_node("Geometry", &[id_prop, name_prop], &[v_node, i_node], geom_start, is_64);
1433 let objects_node = encode_node("Objects", &[], &[geom_node], objects_start, is_64);
1434
1435 out.extend_from_slice(&objects_node);
1436 out.resize(out.len() + hdr_len, 0); // top-level sentinel
1437 out
1438 }
1439
1440 #[test]
1441 fn test_parse_obj_quad_and_normals() {
1442 let obj = r#"
1443# Simple quad OBJ without normals
1444o MyQuad
1445v 0 0 0
1446v 2 0 0
1447v 2 2 0
1448v 0 2 0
1449vt 0 0
1450vt 1 0
1451vt 1 1
1452vt 0 1
1453f 1/1 2/2 3/3 4/4
1454"#;
1455 let verts = parse_mesh_bytes(obj.as_bytes(), Some("obj"), Some("MyQuad"), 0.5)
1456 .expect("parse OBJ");
1457 assert_eq!(verts.len(), 6, "quad should fan-triangulate into 2 triangles (6 verts)");
1458 // Scaled by 0.5 -> max X/Y = 1.0
1459 assert!((verts[1].pos[0] - 1.0).abs() < 1e-5);
1460 assert!((verts[2].pos[1] - 1.0).abs() < 1e-5);
1461 // Smooth normals computed pointing +Z
1462 for v in &verts {
1463 assert!((v.normal[2] - 1.0).abs() < 1e-4, "expected +Z normal, got {:?}", v.normal);
1464 }
1465 }
1466
1467 #[test]
1468 fn test_parse_ascii_fbx() {
1469 let ascii = r#"
1470; FBX 7.4.0 project file
1471Objects: {
1472 Geometry: 1234, "Geometry::TriMesh", "Mesh" {
1473 Vertices: *9 {
1474 a: 0,0,0, 1,0,0, 0,1,0
1475 }
1476 PolygonVertexIndex: *3 {
1477 a: 0,1,-3
1478 }
1479 LayerElementUV: 0 {
1480 MappingInformationType: "ByPolygonVertex"
1481 UV: *6 {
1482 a: 0,0, 1,0, 0,1
1483 }
1484 }
1485 }
1486}
1487"#;
1488 let verts = parse_mesh_bytes(ascii.as_bytes(), Some("fbx"), Some("TriMesh"), 2.0)
1489 .expect("parse ASCII FBX");
1490 assert_eq!(verts.len(), 3, "1 triangle = 3 vertices");
1491 assert!((verts[1].pos[0] - 2.0).abs() < 1e-5);
1492 assert!((verts[2].pos[1] - 2.0).abs() < 1e-5);
1493 assert!((verts[0].normal[2] - 1.0).abs() < 1e-4);
1494 assert!((verts[2].uv[1] - 0.0).abs() < 1e-4, "V flipped from 1.0 -> 0.0");
1495 }
1496
1497 #[test]
1498 fn test_parse_binary_fbx_v7400_and_v7500_compressed() {
1499 let raw_7400 = build_synthetic_binary_fbx(7400, false);
1500 let verts_7400 = parse_mesh_bytes(&raw_7400, Some("fbx"), Some("TestQuad"), 1.0)
1501 .expect("parse binary FBX v7400");
1502 assert_eq!(verts_7400.len(), 6);
1503 assert!((verts_7400[0].normal[2] - 1.0).abs() < 1e-4);
1504
1505 let comp_7500 = build_synthetic_binary_fbx(7500, true);
1506 let verts_7500 = parse_mesh_bytes(&comp_7500, Some("fbx"), Some("TestQuad"), 3.0)
1507 .expect("parse compressed binary FBX v7500");
1508 assert_eq!(verts_7500.len(), 6);
1509 assert!((verts_7500[1].pos[0] - 3.0).abs() < 1e-5);
1510 assert!((verts_7500[2].pos[1] - 3.0).abs() < 1e-5);
1511 assert!((verts_7500[0].normal[2] - 1.0).abs() < 1e-4);
1512 }
1513
1514 #[test]
1515 fn test_missing_file_fallback_unit_box_is_not_cached() {
1516 let path = "/nonexistent/path/to/missing_model.fbx";
1517 let mesh = load_mesh_cached(path, None, None, 1.0);
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();
1545 }
1546}