BlueGit

golden-age paperdoll-renderer

Robustness gate: mutation tests for bodies/presets/manifest/ppda; glTF rejects non-finite data, bad lengths, out-of-range indices; parser panics become load errors

timfa Grok Bot · pushed by timfa

Authored 2026-11-07 · 7 days ago

Hash
31c279340003a994472f10dda450c75a3a712f14
Parent
26122ebc
4 files changed +241 −5
README.md +3 −1
@@ -183,11 +183,13 @@ Het venster, de Linux-starter en de Windows-executable gebruiken Tims applicatie
183 183
184 184 ## Tests
185 185
186 `tests/robustness.rs` bewaakt dat beschadigde invoer een gewone foutmelding geeft en nooit een crash: honderden deterministische mutaties (afgekapt, bitflips, nul- en 0xFF-blokken) van de glTF/GLB-, FBX- en OBJ-lichamen, het equipment-preset en de projectmanifest, kapotte `.ppda`-bestanden, en glTF-nodes met schaal 0 of een overlopende schaal. Bij het laden van glTF worden niet-eindige posities/normalen/gewichten, verkeerde attribuutlengtes en indices buiten het vertexbereik geweigerd; een paniek in de glTF-parser wordt een laadfout.
187
186 188 ```bash
187 189 cargo fmt --check
188 190 cargo check --workspace --all-targets --locked
189 191 cargo clippy --workspace --all-targets --locked -- -D warnings
190 cargo test --workspace --locked
192 cargo test --workspace --locked # incl. tests/robustness.rs
191 193 # Linux GPU-regressie: echte depth-occlusie, normal/depth/specular en lichtonafhankelijke albedo
192 194 xvfb-run -a cargo run --example preview_depth_probe --locked
193 195 # Productie op echte GPU (body of equipment); controleert daarna iedere atlascel tegen de losse PNG
@@ -183,11 +183,13 @@ Het venster, de Linux-starter en de Windows-executable gebruiken Tims applicatie
183
183
184## Tests
184## Tests
185
185
186`tests/robustness.rs` bewaakt dat beschadigde invoer een gewone foutmelding geeft en nooit een crash: honderden deterministische mutaties (afgekapt, bitflips, nul- en 0xFF-blokken) van de glTF/GLB-, FBX- en OBJ-lichamen, het equipment-preset en de projectmanifest, kapotte `.ppda`-bestanden, en glTF-nodes met schaal 0 of een overlopende schaal. Bij het laden van glTF worden niet-eindige posities/normalen/gewichten, verkeerde attribuutlengtes en indices buiten het vertexbereik geweigerd; een paniek in de glTF-parser wordt een laadfout.
187
186```bash
188```bash
187cargo fmt --check
189cargo fmt --check
188cargo check --workspace --all-targets --locked
190cargo check --workspace --all-targets --locked
189cargo clippy --workspace --all-targets --locked -- -D warnings
191cargo clippy --workspace --all-targets --locked -- -D warnings
190cargo test --workspace --locked
192cargo test --workspace --locked # incl. tests/robustness.rs
191# Linux GPU-regressie: echte depth-occlusie, normal/depth/specular en lichtonafhankelijke albedo
193# Linux GPU-regressie: echte depth-occlusie, normal/depth/specular en lichtonafhankelijke albedo
192xvfb-run -a cargo run --example preview_depth_probe --locked
194xvfb-run -a cargo run --example preview_depth_probe --locked
193# Productie op echte GPU (body of equipment); controleert daarna iedere atlascel tegen de losse PNG
195# Productie op echte GPU (body of equipment); controleert daarna iedere atlascel tegen de losse PNG
src/import.rs +5 −4
@@ -145,10 +145,11 @@ fn import_gltf(
145 145 detail,
146 146 })?;
147 147 reject_unsafe_uris(&json)?;
148 let (document, buffers, images) = gltf::import(full).map_err(|err| ImportError::Parse {
149 path: relative.to_string(),
150 detail: err.to_string(),
151 })?;
148 let (document, buffers, images) =
149 crate::preview::gltf_import_guarded(full).map_err(|detail| ImportError::Parse {
150 path: relative.to_string(),
151 detail,
152 })?;
152 153 let mut materials = Vec::new();
153 154 for material in document.materials() {
154 155 let pbr = material.pbr_metallic_roughness();
@@ -145,10 +145,11 @@ fn import_gltf(
145 detail,
145 detail,
146 })?;
146 })?;
147 reject_unsafe_uris(&json)?;
147 reject_unsafe_uris(&json)?;
148 let (document, buffers, images) = gltf::import(full).map_err(|err| ImportError::Parse {
148 let (document, buffers, images) =
149 path: relative.to_string(),
149 crate::preview::gltf_import_guarded(full).map_err(|detail| ImportError::Parse {
150 detail: err.to_string(),
150 path: relative.to_string(),
151 })?;
151 detail,
152 })?;
152 let mut materials = Vec::new();
153 let mut materials = Vec::new();
153 for material in document.materials() {
154 for material in document.materials() {
154 let pbr = material.pbr_metallic_roughness();
155 let pbr = material.pbr_metallic_roughness();
src/preview.rs +49 −0
@@ -491,6 +491,29 @@ impl StaticAcc {
491 491 }
492 492
493 493 pub fn load_gltf_file(path: &Path) -> Result<PreviewCharacter, String> {
494 // The gltf crate can panic on some malformed documents; that must stay a
495 // recoverable load error for the editor and batch.
496 std::panic::catch_unwind(|| load_gltf_file_unguarded(path))
497 .unwrap_or_else(|_| Err("ongeldig glTF-bestand (parser weigerde het document)".into()))
498 }
499
500 /// `gltf::import` with parser panics turned into an error.
501 pub fn gltf_import_guarded(
502 path: &Path,
503 ) -> Result<
504 (
505 gltf::Document,
506 Vec<gltf::buffer::Data>,
507 Vec<gltf::image::Data>,
508 ),
509 String,
510 > {
511 std::panic::catch_unwind(|| gltf::import(path))
512 .map_err(|_| "ongeldig glTF-bestand (parser weigerde het document)".to_string())?
513 .map_err(|err| err.to_string())
514 }
515
516 fn load_gltf_file_unguarded(path: &Path) -> Result<PreviewCharacter, String> {
494 517 let (document, buffers, images) = gltf::import(path).map_err(|err| err.to_string())?;
495 518 let mut nodes = Vec::new();
496 519 let mut parents = vec![None; document.nodes().len()];
@@ -655,6 +678,14 @@ pub fn load_gltf_file(path: &Path) -> Result<PreviewCharacter, String> {
655 678 if positions.is_empty() || indices.len() < 3 {
656 679 return Err("het glTF-bestand heeft geen tekenbare driehoeken".to_string());
657 680 }
681 if positions
682 .iter()
683 .chain(&normals)
684 .flatten()
685 .any(|v| !v.is_finite())
686 {
687 return Err("glTF-mesh heeft niet-eindige posities na de node-transformatie".into());
688 }
658 689 let mut clips = Vec::new();
659 690 for animation in document.animations() {
660 691 let mut channels = Vec::new();
@@ -780,6 +811,21 @@ fn read_gltf_primitive(
780 811 .read_weights(0)
781 812 .map(|iter| iter.into_f32().collect())
782 813 .unwrap_or_else(|| vec![[1.0, 0.0, 0.0, 0.0]; positions.len()]);
814 if positions.iter().flatten().any(|v| !v.is_finite()) {
815 return Err("glTF-primitive heeft niet-eindige posities".into());
816 }
817 if normals
818 .as_ref()
819 .is_some_and(|n| n.len() != positions.len() || n.iter().flatten().any(|v| !v.is_finite()))
820 {
821 return Err("glTF-primitive heeft ongeldige normalen".into());
822 }
823 if joints.len() != positions.len()
824 || weights.len() != positions.len()
825 || weights.iter().flatten().any(|w| !w.is_finite() || *w < 0.)
826 {
827 return Err("glTF-primitive heeft ongeldige joints/gewichten".into());
828 }
783 829 let material = primitive.material();
784 830 let pbr = material.pbr_metallic_roughness();
785 831 let texture = pbr.base_color_texture();
@@ -808,6 +854,9 @@ fn read_gltf_primitive(
808 854 Some(read_indices) => read_indices.into_u32().collect(),
809 855 None => (0..positions.len() as u32).collect(),
810 856 };
857 if indices.iter().any(|i| *i as usize >= positions.len()) {
858 return Err("glTF-primitive heeft indices buiten het vertexbereik".into());
859 }
811 860 let albedo = texture
812 861 .map(|t| {
813 862 let image = images
@@ -491,6 +491,29 @@ impl StaticAcc {
491}
491}
492
492
493pub fn load_gltf_file(path: &Path) -> Result<PreviewCharacter, String> {
493pub fn load_gltf_file(path: &Path) -> Result<PreviewCharacter, String> {
494 // The gltf crate can panic on some malformed documents; that must stay a
495 // recoverable load error for the editor and batch.
496 std::panic::catch_unwind(|| load_gltf_file_unguarded(path))
497 .unwrap_or_else(|_| Err("ongeldig glTF-bestand (parser weigerde het document)".into()))
498}
499
500/// `gltf::import` with parser panics turned into an error.
501pub fn gltf_import_guarded(
502 path: &Path,
503) -> Result<
504 (
505 gltf::Document,
506 Vec<gltf::buffer::Data>,
507 Vec<gltf::image::Data>,
508 ),
509 String,
510> {
511 std::panic::catch_unwind(|| gltf::import(path))
512 .map_err(|_| "ongeldig glTF-bestand (parser weigerde het document)".to_string())?
513 .map_err(|err| err.to_string())
514}
515
516fn load_gltf_file_unguarded(path: &Path) -> Result<PreviewCharacter, String> {
494 let (document, buffers, images) = gltf::import(path).map_err(|err| err.to_string())?;
517 let (document, buffers, images) = gltf::import(path).map_err(|err| err.to_string())?;
495 let mut nodes = Vec::new();
518 let mut nodes = Vec::new();
496 let mut parents = vec![None; document.nodes().len()];
519 let mut parents = vec![None; document.nodes().len()];
@@ -655,6 +678,14 @@ pub fn load_gltf_file(path: &Path) -> Result<PreviewCharacter, String> {
655 if positions.is_empty() || indices.len() < 3 {
678 if positions.is_empty() || indices.len() < 3 {
656 return Err("het glTF-bestand heeft geen tekenbare driehoeken".to_string());
679 return Err("het glTF-bestand heeft geen tekenbare driehoeken".to_string());
657 }
680 }
681 if positions
682 .iter()
683 .chain(&normals)
684 .flatten()
685 .any(|v| !v.is_finite())
686 {
687 return Err("glTF-mesh heeft niet-eindige posities na de node-transformatie".into());
688 }
658 let mut clips = Vec::new();
689 let mut clips = Vec::new();
659 for animation in document.animations() {
690 for animation in document.animations() {
660 let mut channels = Vec::new();
691 let mut channels = Vec::new();
@@ -780,6 +811,21 @@ fn read_gltf_primitive(
780 .read_weights(0)
811 .read_weights(0)
781 .map(|iter| iter.into_f32().collect())
812 .map(|iter| iter.into_f32().collect())
782 .unwrap_or_else(|| vec![[1.0, 0.0, 0.0, 0.0]; positions.len()]);
813 .unwrap_or_else(|| vec![[1.0, 0.0, 0.0, 0.0]; positions.len()]);
814 if positions.iter().flatten().any(|v| !v.is_finite()) {
815 return Err("glTF-primitive heeft niet-eindige posities".into());
816 }
817 if normals
818 .as_ref()
819 .is_some_and(|n| n.len() != positions.len() || n.iter().flatten().any(|v| !v.is_finite()))
820 {
821 return Err("glTF-primitive heeft ongeldige normalen".into());
822 }
823 if joints.len() != positions.len()
824 || weights.len() != positions.len()
825 || weights.iter().flatten().any(|w| !w.is_finite() || *w < 0.)
826 {
827 return Err("glTF-primitive heeft ongeldige joints/gewichten".into());
828 }
783 let material = primitive.material();
829 let material = primitive.material();
784 let pbr = material.pbr_metallic_roughness();
830 let pbr = material.pbr_metallic_roughness();
785 let texture = pbr.base_color_texture();
831 let texture = pbr.base_color_texture();
@@ -808,6 +854,9 @@ fn read_gltf_primitive(
808 Some(read_indices) => read_indices.into_u32().collect(),
854 Some(read_indices) => read_indices.into_u32().collect(),
809 None => (0..positions.len() as u32).collect(),
855 None => (0..positions.len() as u32).collect(),
810 };
856 };
857 if indices.iter().any(|i| *i as usize >= positions.len()) {
858 return Err("glTF-primitive heeft indices buiten het vertexbereik".into());
859 }
811 let albedo = texture
860 let albedo = texture
812 .map(|t| {
861 .map(|t| {
813 let image = images
862 let image = images
tests/robustness.rs added +184 −0
@@ -0,0 +1,184 @@
1 //! #14 robustness gate: corrupt, truncated and mutated inputs must give a
2 //! recoverable `Err` (or a still-valid `Ok`), never a panic, hang or NaN body.
3 use paperdoll_renderer::{atlas::AtlasSet, equipment::Preset, preview, project};
4 use std::panic::{catch_unwind, AssertUnwindSafe};
5 use std::path::{Path, PathBuf};
6
7 fn fixture(rel: &str) -> PathBuf {
8 Path::new(env!("CARGO_MANIFEST_DIR"))
9 .join("tests/fixtures")
10 .join(rel)
11 }
12
13 struct Temp(PathBuf);
14 impl Temp {
15 fn new(tag: &str) -> Self {
16 let p = std::env::temp_dir().join(format!("ppd-robust-{tag}-{}", std::process::id()));
17 let _ = std::fs::remove_dir_all(&p);
18 std::fs::create_dir_all(&p).unwrap();
19 Temp(p)
20 }
21 }
22 impl Drop for Temp {
23 fn drop(&mut self) {
24 let _ = std::fs::remove_dir_all(&self.0);
25 }
26 }
27
28 /// Deterministic mutations: truncations, byte flips, zeroed and 0xFF runs.
29 fn mutations(bytes: &[u8], count: usize) -> Vec<Vec<u8>> {
30 let mut out = vec![Vec::new(), bytes[..bytes.len() / 2].to_vec()];
31 let mut seed = 0x9e37_79b9_u64;
32 let mut next = || {
33 seed = seed
34 .wrapping_mul(6364136223846793005)
35 .wrapping_add(1442695040888963407);
36 (seed >> 33) as usize
37 };
38 for i in 0..count {
39 let mut m = bytes.to_vec();
40 match i % 4 {
41 0 => m.truncate(next() % bytes.len()),
42 1 => {
43 for _ in 0..1 + next() % 8 {
44 let at = next() % m.len();
45 m[at] ^= 1 << (next() % 8);
46 }
47 }
48 2 => {
49 let at = next() % m.len();
50 let end = (at + 1 + next() % 64).min(m.len());
51 m[at..end].fill(0);
52 }
53 _ => {
54 let at = next() % m.len();
55 let end = (at + 1 + next() % 64).min(m.len());
56 m[at..end].fill(0xff);
57 }
58 }
59 out.push(m);
60 }
61 out
62 }
63
64 fn body_ok(body: &preview::PreviewCharacter) {
65 assert!(body.positions.iter().flatten().all(|v| v.is_finite()));
66 let n = body.positions.len() as u32;
67 assert!(body.indices.iter().all(|i| *i < n));
68 }
69
70 fn fuzz_body(src: &str, ext: &str, count: usize) {
71 let bytes = std::fs::read(fixture(src)).unwrap();
72 let temp = Temp::new(&src.replace(['/', '.'], "-"));
73 for (i, m) in mutations(&bytes, count).into_iter().enumerate() {
74 let path = temp.0.join(format!("m{i}.{ext}"));
75 std::fs::write(&path, &m).unwrap();
76 let result = catch_unwind(AssertUnwindSafe(|| preview::load_body_file(&path)));
77 match result {
78 Ok(Ok(body)) => body_ok(&body),
79 Ok(Err(e)) => assert!(!e.is_empty()),
80 Err(_) => panic!("{src} mutation {i} panicked"),
81 }
82 }
83 }
84
85 #[test]
86 fn mutated_glb_bodies_never_panic() {
87 fuzz_body("bodies/test-body-male.glb", "glb", 800);
88 fuzz_body("bodies/static/static-body-male.glb", "glb", 80);
89 }
90
91 #[test]
92 fn mutated_fbx_body_never_panics() {
93 fuzz_body("bodies/test-body-male.fbx", "fbx", 120);
94 }
95
96 #[test]
97 fn mutated_obj_body_never_panics() {
98 let temp = Temp::new("obj");
99 for f in ["static-body-albedo.png", "static-body-male.mtl"] {
100 std::fs::copy(fixture(&format!("bodies/static/{f}")), temp.0.join(f)).unwrap();
101 }
102 let bytes = std::fs::read(fixture("bodies/static/static-body-male.obj")).unwrap();
103 for (i, m) in mutations(&bytes, 120).into_iter().enumerate() {
104 let path = temp.0.join(format!("m{i}.obj"));
105 std::fs::write(&path, &m).unwrap();
106 match catch_unwind(AssertUnwindSafe(|| preview::load_body_file(&path))) {
107 Ok(Ok(body)) => body_ok(&body),
108 Ok(Err(_)) => {}
109 Err(_) => panic!("obj mutation {i} panicked"),
110 }
111 }
112 }
113
114 #[test]
115 fn mutated_equipment_preset_never_panics() {
116 let bytes = std::fs::read(fixture("equipment/sword.ppe")).unwrap();
117 for (i, m) in mutations(&bytes, 200).into_iter().enumerate() {
118 if catch_unwind(AssertUnwindSafe(|| Preset::decode(&m))).is_err() {
119 panic!("ppe mutation {i} panicked");
120 }
121 }
122 }
123
124 #[test]
125 fn mutated_project_manifest_is_a_recoverable_error() {
126 let temp = Temp::new("ppd");
127 let opened = project::create_project(&temp.0, "robust").unwrap();
128 let text = std::fs::read(&opened.manifest_path).unwrap();
129 for (i, m) in mutations(&text, 200).into_iter().enumerate() {
130 let s = String::from_utf8_lossy(&m);
131 if catch_unwind(AssertUnwindSafe(|| project::parse_manifest(&s))).is_err() {
132 panic!("manifest mutation {i} panicked");
133 }
134 }
135 }
136
137 #[test]
138 fn garbage_ppda_is_an_error() {
139 let temp = Temp::new("ppda");
140 let cases: [&[u8]; 4] = [b"", b"{", b"{\"format\":3}", &[0xff; 64]];
141 for (i, c) in cases.iter().enumerate() {
142 let path = temp.0.join(format!("x{i}.ppda"));
143 std::fs::write(&path, c).unwrap();
144 assert!(AtlasSet::open(&path).is_err());
145 }
146 assert!(AtlasSet::open(&temp.0.join("missing.ppda")).is_err());
147 }
148
149 #[test]
150 fn non_finite_and_singular_gltf_transforms_are_errors() {
151 let source = std::fs::read(fixture("bodies/static/static-body-male.glb")).unwrap();
152 let json_len = u32::from_le_bytes(source[12..16].try_into().unwrap()) as usize;
153 let doc: serde_json::Value = serde_json::from_slice(&source[20..20 + json_len]).unwrap();
154 let temp = Temp::new("nan");
155 let edits: [(&str, serde_json::Value); 2] = [
156 ("scale0", serde_json::json!([0.0, 0.0, 0.0])),
157 ("huge", serde_json::json!([3.0e38, 3.0e38, 3.0e38])),
158 ];
159 for (name, scale) in edits {
160 let mut d = doc.clone();
161 for node in d["nodes"].as_array_mut().unwrap() {
162 if node.get("mesh").is_some() {
163 node["scale"] = scale.clone();
164 }
165 }
166 let mut json = serde_json::to_vec(&d).unwrap();
167 while !json.len().is_multiple_of(4) {
168 json.push(b' ');
169 }
170 let rest = &source[20 + json_len..];
171 let mut out = source[0..8].to_vec();
172 out.extend(((20 + json.len() + rest.len()) as u32).to_le_bytes());
173 out.extend((json.len() as u32).to_le_bytes());
174 out.extend(b"JSON");
175 out.extend(&json);
176 out.extend(rest);
177 let path = temp.0.join(format!("{name}.glb"));
178 std::fs::write(&path, out).unwrap();
179 match preview::load_body_file(&path) {
180 Err(_) => {}
181 Ok(body) => panic!("{name}: loaded {} vertices", body.positions.len()),
182 }
183 }
184 }
@@ -0,0 +1,184 @@
1//! #14 robustness gate: corrupt, truncated and mutated inputs must give a
2//! recoverable `Err` (or a still-valid `Ok`), never a panic, hang or NaN body.
3use paperdoll_renderer::{atlas::AtlasSet, equipment::Preset, preview, project};
4use std::panic::{catch_unwind, AssertUnwindSafe};
5use std::path::{Path, PathBuf};
6
7fn fixture(rel: &str) -> PathBuf {
8 Path::new(env!("CARGO_MANIFEST_DIR"))
9 .join("tests/fixtures")
10 .join(rel)
11}
12
13struct Temp(PathBuf);
14impl Temp {
15 fn new(tag: &str) -> Self {
16 let p = std::env::temp_dir().join(format!("ppd-robust-{tag}-{}", std::process::id()));
17 let _ = std::fs::remove_dir_all(&p);
18 std::fs::create_dir_all(&p).unwrap();
19 Temp(p)
20 }
21}
22impl Drop for Temp {
23 fn drop(&mut self) {
24 let _ = std::fs::remove_dir_all(&self.0);
25 }
26}
27
28/// Deterministic mutations: truncations, byte flips, zeroed and 0xFF runs.
29fn mutations(bytes: &[u8], count: usize) -> Vec<Vec<u8>> {
30 let mut out = vec![Vec::new(), bytes[..bytes.len() / 2].to_vec()];
31 let mut seed = 0x9e37_79b9_u64;
32 let mut next = || {
33 seed = seed
34 .wrapping_mul(6364136223846793005)
35 .wrapping_add(1442695040888963407);
36 (seed >> 33) as usize
37 };
38 for i in 0..count {
39 let mut m = bytes.to_vec();
40 match i % 4 {
41 0 => m.truncate(next() % bytes.len()),
42 1 => {
43 for _ in 0..1 + next() % 8 {
44 let at = next() % m.len();
45 m[at] ^= 1 << (next() % 8);
46 }
47 }
48 2 => {
49 let at = next() % m.len();
50 let end = (at + 1 + next() % 64).min(m.len());
51 m[at..end].fill(0);
52 }
53 _ => {
54 let at = next() % m.len();
55 let end = (at + 1 + next() % 64).min(m.len());
56 m[at..end].fill(0xff);
57 }
58 }
59 out.push(m);
60 }
61 out
62}
63
64fn body_ok(body: &preview::PreviewCharacter) {
65 assert!(body.positions.iter().flatten().all(|v| v.is_finite()));
66 let n = body.positions.len() as u32;
67 assert!(body.indices.iter().all(|i| *i < n));
68}
69
70fn fuzz_body(src: &str, ext: &str, count: usize) {
71 let bytes = std::fs::read(fixture(src)).unwrap();
72 let temp = Temp::new(&src.replace(['/', '.'], "-"));
73 for (i, m) in mutations(&bytes, count).into_iter().enumerate() {
74 let path = temp.0.join(format!("m{i}.{ext}"));
75 std::fs::write(&path, &m).unwrap();
76 let result = catch_unwind(AssertUnwindSafe(|| preview::load_body_file(&path)));
77 match result {
78 Ok(Ok(body)) => body_ok(&body),
79 Ok(Err(e)) => assert!(!e.is_empty()),
80 Err(_) => panic!("{src} mutation {i} panicked"),
81 }
82 }
83}
84
85#[test]
86fn mutated_glb_bodies_never_panic() {
87 fuzz_body("bodies/test-body-male.glb", "glb", 800);
88 fuzz_body("bodies/static/static-body-male.glb", "glb", 80);
89}
90
91#[test]
92fn mutated_fbx_body_never_panics() {
93 fuzz_body("bodies/test-body-male.fbx", "fbx", 120);
94}
95
96#[test]
97fn mutated_obj_body_never_panics() {
98 let temp = Temp::new("obj");
99 for f in ["static-body-albedo.png", "static-body-male.mtl"] {
100 std::fs::copy(fixture(&format!("bodies/static/{f}")), temp.0.join(f)).unwrap();
101 }
102 let bytes = std::fs::read(fixture("bodies/static/static-body-male.obj")).unwrap();
103 for (i, m) in mutations(&bytes, 120).into_iter().enumerate() {
104 let path = temp.0.join(format!("m{i}.obj"));
105 std::fs::write(&path, &m).unwrap();
106 match catch_unwind(AssertUnwindSafe(|| preview::load_body_file(&path))) {
107 Ok(Ok(body)) => body_ok(&body),
108 Ok(Err(_)) => {}
109 Err(_) => panic!("obj mutation {i} panicked"),
110 }
111 }
112}
113
114#[test]
115fn mutated_equipment_preset_never_panics() {
116 let bytes = std::fs::read(fixture("equipment/sword.ppe")).unwrap();
117 for (i, m) in mutations(&bytes, 200).into_iter().enumerate() {
118 if catch_unwind(AssertUnwindSafe(|| Preset::decode(&m))).is_err() {
119 panic!("ppe mutation {i} panicked");
120 }
121 }
122}
123
124#[test]
125fn mutated_project_manifest_is_a_recoverable_error() {
126 let temp = Temp::new("ppd");
127 let opened = project::create_project(&temp.0, "robust").unwrap();
128 let text = std::fs::read(&opened.manifest_path).unwrap();
129 for (i, m) in mutations(&text, 200).into_iter().enumerate() {
130 let s = String::from_utf8_lossy(&m);
131 if catch_unwind(AssertUnwindSafe(|| project::parse_manifest(&s))).is_err() {
132 panic!("manifest mutation {i} panicked");
133 }
134 }
135}
136
137#[test]
138fn garbage_ppda_is_an_error() {
139 let temp = Temp::new("ppda");
140 let cases: [&[u8]; 4] = [b"", b"{", b"{\"format\":3}", &[0xff; 64]];
141 for (i, c) in cases.iter().enumerate() {
142 let path = temp.0.join(format!("x{i}.ppda"));
143 std::fs::write(&path, c).unwrap();
144 assert!(AtlasSet::open(&path).is_err());
145 }
146 assert!(AtlasSet::open(&temp.0.join("missing.ppda")).is_err());
147}
148
149#[test]
150fn non_finite_and_singular_gltf_transforms_are_errors() {
151 let source = std::fs::read(fixture("bodies/static/static-body-male.glb")).unwrap();
152 let json_len = u32::from_le_bytes(source[12..16].try_into().unwrap()) as usize;
153 let doc: serde_json::Value = serde_json::from_slice(&source[20..20 + json_len]).unwrap();
154 let temp = Temp::new("nan");
155 let edits: [(&str, serde_json::Value); 2] = [
156 ("scale0", serde_json::json!([0.0, 0.0, 0.0])),
157 ("huge", serde_json::json!([3.0e38, 3.0e38, 3.0e38])),
158 ];
159 for (name, scale) in edits {
160 let mut d = doc.clone();
161 for node in d["nodes"].as_array_mut().unwrap() {
162 if node.get("mesh").is_some() {
163 node["scale"] = scale.clone();
164 }
165 }
166 let mut json = serde_json::to_vec(&d).unwrap();
167 while !json.len().is_multiple_of(4) {
168 json.push(b' ');
169 }
170 let rest = &source[20 + json_len..];
171 let mut out = source[0..8].to_vec();
172 out.extend(((20 + json.len() + rest.len()) as u32).to_le_bytes());
173 out.extend((json.len() as u32).to_le_bytes());
174 out.extend(b"JSON");
175 out.extend(&json);
176 out.extend(rest);
177 let path = temp.0.join(format!("{name}.glb"));
178 std::fs::write(&path, out).unwrap();
179 match preview::load_body_file(&path) {
180 Err(_) => {}
181 Ok(body) => panic!("{name}: loaded {} vertices", body.positions.len()),
182 }
183 }
184}