1use std::collections::BTreeSet;
4
5use serde_json::{Map, Value};
6
7use crate::document::Document;
8use crate::mesh::{MAX_POINTS, MAX_TRIANGLES, TRIANGLE_CEILING};
9
10#[non_exhaustive]
43#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
44#[allow(clippy::struct_excessive_bools, reason = "independent switches")]
45pub struct Keep {
46 pub animations: bool,
48 pub skins: bool,
51 pub morph_targets: bool,
53 pub materials: bool,
56 pub textures: bool,
58 pub image_bytes: bool,
65 pub cameras: bool,
67 pub lights: bool,
69 pub extras: bool,
73 pub max_triangles: usize,
78 pub lines_and_points: bool,
83 pub max_points: usize,
88 pub threads: usize,
93}
94
95impl Default for Keep {
96 fn default() -> Self {
97 Self::ALL
98 }
99}
100
101impl Keep {
102 pub const ALL: Keep = Keep {
104 animations: true,
105 skins: true,
106 morph_targets: true,
107 materials: true,
108 textures: true,
109 image_bytes: true,
110 cameras: true,
111 lights: true,
112 extras: true,
113 max_triangles: MAX_TRIANGLES,
114 lines_and_points: true,
115 max_points: MAX_POINTS,
116 threads: 1,
117 };
118
119 pub const MESHES: Keep = Keep {
122 animations: false,
123 cameras: false,
124 lights: false,
125 ..Keep::ALL
126 };
127
128 pub const LIGHT: Keep = Keep {
131 image_bytes: false,
132 ..Keep::MESHES
133 };
134
135 #[must_use]
137 pub const fn with_animations(mut self, animations: bool) -> Self {
138 self.animations = animations;
139 self
140 }
141
142 #[must_use]
144 pub const fn with_skins(mut self, skins: bool) -> Self {
145 self.skins = skins;
146 self
147 }
148
149 #[must_use]
151 pub const fn with_morph_targets(mut self, morph_targets: bool) -> Self {
152 self.morph_targets = morph_targets;
153 self
154 }
155
156 #[must_use]
158 pub const fn with_materials(mut self, materials: bool) -> Self {
159 self.materials = materials;
160 self
161 }
162
163 #[must_use]
165 pub const fn with_textures(mut self, textures: bool) -> Self {
166 self.textures = textures;
167 self
168 }
169
170 #[must_use]
172 pub const fn with_image_bytes(mut self, image_bytes: bool) -> Self {
173 self.image_bytes = image_bytes;
174 self
175 }
176
177 #[must_use]
179 pub const fn with_cameras(mut self, cameras: bool) -> Self {
180 self.cameras = cameras;
181 self
182 }
183
184 #[must_use]
186 pub const fn with_lights(mut self, lights: bool) -> Self {
187 self.lights = lights;
188 self
189 }
190
191 #[must_use]
193 pub const fn with_extras(mut self, extras: bool) -> Self {
194 self.extras = extras;
195 self
196 }
197
198 #[must_use]
200 pub const fn with_max_triangles(mut self, max_triangles: usize) -> Self {
201 self.max_triangles = max_triangles;
202 self
203 }
204
205 #[must_use]
207 pub const fn with_lines_and_points(mut self, lines_and_points: bool) -> Self {
208 self.lines_and_points = lines_and_points;
209 self
210 }
211
212 #[must_use]
214 pub const fn with_max_points(mut self, max_points: usize) -> Self {
215 self.max_points = max_points;
216 self
217 }
218
219 #[must_use]
221 pub const fn with_threads(mut self, threads: usize) -> Self {
222 self.threads = threads;
223 self
224 }
225
226 pub(crate) fn triangles(self) -> usize {
228 self.max_triangles.min(TRIANGLE_CEILING)
229 }
230
231 pub(crate) fn points(self) -> usize {
233 self.max_points.min(TRIANGLE_CEILING)
234 }
235
236 #[cfg_attr(
239 not(any(
240 feature = "obj",
241 feature = "spz",
242 feature = "las",
243 feature = "pcd",
244 feature = "xyz",
245 feature = "e57",
246 feature = "ac3d"
247 )),
248 allow(dead_code, reason = "only the OBJ and SPZ readers take threads")
249 )]
250 pub(crate) fn thread_count(self) -> usize {
251 if cfg!(all(target_family = "wasm", not(target_feature = "atomics"))) {
252 1
253 } else if self.threads == 0 {
254 std::thread::available_parallelism().map_or(1, std::num::NonZero::get)
255 } else {
256 self.threads
257 }
258 }
259}
260
261#[cfg(test)]
262thread_local! {
263 pub(crate) static NO_THREADS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
265}
266
267#[cfg_attr(
269 not(any(
270 feature = "obj",
271 feature = "spz",
272 feature = "las",
273 feature = "pcd",
274 feature = "xyz",
275 feature = "e57",
276 feature = "ac3d"
277 )),
278 allow(dead_code, reason = "only the OBJ and SPZ readers take threads")
279)]
280pub(crate) fn spawn<'s>(s: &'s std::thread::Scope<'s, '_>, f: impl FnOnce() + Send + 's) -> bool {
281 #[cfg(test)]
282 if NO_THREADS.get() {
283 return false;
284 }
285 std::thread::Builder::new().spawn_scoped(s, f).is_ok()
286}
287
288fn each(obj: &mut Map<String, Value>, key: &str, mut f: impl FnMut(&mut Map<String, Value>)) {
290 let items = obj.get_mut(key).and_then(Value::as_array_mut);
291 for item in items.into_iter().flatten().filter_map(Value::as_object_mut) {
292 f(item);
293 }
294}
295
296fn primitives(json: &mut Map<String, Value>, mut f: impl FnMut(&mut Map<String, Value>)) {
298 each(json, "meshes", |m| each(m, "primitives", &mut f));
299}
300
301fn remove_extension(obj: &mut Map<String, Value>, name: &str) {
303 if let Some(exts) = obj.get_mut("extensions").and_then(Value::as_object_mut) {
304 exts.remove(name);
305 if exts.is_empty() {
306 obj.remove("extensions");
307 }
308 }
309}
310
311fn remove_extension_everywhere(v: &mut Value, name: &str) {
313 match v {
314 Value::Object(obj) => {
315 remove_extension(obj, name);
316 obj.values_mut().for_each(|v| remove_extension_everywhere(v, name));
317 }
318 Value::Array(a) => a.iter_mut().for_each(|v| remove_extension_everywhere(v, name)),
319 _ => {}
320 }
321}
322
323fn remove_key_everywhere(v: &mut Value, key: &str) {
325 match v {
326 Value::Object(obj) => {
327 obj.remove(key);
328 obj.values_mut().for_each(|v| remove_key_everywhere(v, key));
329 }
330 Value::Array(a) => a.iter_mut().for_each(|v| remove_key_everywhere(v, key)),
331 _ => {}
332 }
333}
334
335fn remove_textures(obj: &mut Map<String, Value>) {
338 obj.retain(|k, v| !(k.ends_with("Texture") && v.is_object()));
339 for v in obj.values_mut() {
340 if let Value::Object(o) = v {
341 remove_textures(o);
342 }
343 }
344}
345
346fn extensions_present(v: &Value, out: &mut BTreeSet<String>) {
348 match v {
349 Value::Object(obj) => {
350 if let Some(exts) = obj.get("extensions").and_then(Value::as_object) {
351 out.extend(exts.keys().cloned());
352 }
353 obj.values().for_each(|v| extensions_present(v, out));
354 }
355 Value::Array(a) => a.iter().for_each(|v| extensions_present(v, out)),
356 _ => {}
357 }
358}
359
360impl Document {
361 pub fn prune(&mut self, keep: Keep) {
369 self.lines_and_points = keep.lines_and_points;
370 self.max_points = keep.points();
371 if (Keep {
372 image_bytes: true,
373 max_triangles: Keep::ALL.max_triangles,
374 lines_and_points: true,
375 max_points: Keep::ALL.max_points,
376 threads: Keep::ALL.threads,
377 ..keep
378 }) == Keep::ALL
379 {
380 return;
381 }
382 let mut before = BTreeSet::new();
383 let mut root = Value::Object(std::mem::take(self.json_mut()));
384 extensions_present(&root, &mut before);
385 let Value::Object(json) = &mut root else { unreachable!() };
386 let mut dead: Vec<&str> = Vec::new();
388 if !keep.animations {
389 json.remove("animations");
390 }
391 if !keep.cameras {
392 json.remove("cameras");
393 each(json, "nodes", |n| {
394 n.remove("camera");
395 });
396 dead.push("/cameras/");
397 }
398 if !keep.lights {
399 remove_extension_everywhere(&mut root, "KHR_lights_punctual");
400 dead.push("/extensions/KHR_lights_punctual/");
401 }
402 let Value::Object(json) = &mut root else { unreachable!() };
403 if !keep.skins {
404 json.remove("skins");
405 each(json, "nodes", |n| {
406 n.remove("skin");
407 });
408 primitives(json, |p| {
409 let skinning = |k: &String| k.starts_with("JOINTS_") || k.starts_with("WEIGHTS_");
410 if let Some(a) = p.get_mut("attributes").and_then(Value::as_object_mut) {
411 a.retain(|k, _| !skinning(k));
412 }
413 let draco = p
414 .get_mut("extensions")
415 .and_then(|e| e.get_mut("KHR_draco_mesh_compression"))
416 .and_then(|d| d.get_mut("attributes"))
417 .and_then(Value::as_object_mut);
418 if let Some(a) = draco {
419 a.retain(|k, _| !skinning(k));
420 }
421 });
422 }
423 if !keep.morph_targets {
424 primitives(json, |p| {
425 p.remove("targets");
426 });
427 each(json, "meshes", |m| {
428 m.remove("weights");
429 if let Some(x) = m.get_mut("extras").and_then(Value::as_object_mut) {
430 x.remove("targetNames");
431 }
432 });
433 each(json, "nodes", |n| {
434 n.remove("weights");
435 });
436 each(json, "animations", |a| {
437 if let Some(ch) = a.get_mut("channels").and_then(Value::as_array_mut) {
438 ch.retain(|c| c.pointer("/target/path").and_then(Value::as_str) != Some("weights"));
439 }
440 });
441 dead.extend(["/meshes/*/weights", "/nodes/*/weights"]);
442 }
443 let textures = keep.textures && keep.materials;
444 if !keep.materials {
445 json.remove("materials");
446 primitives(json, |p| {
447 p.remove("material");
448 });
449 dead.push("/materials/");
450 }
451 if !keep.materials {
452 remove_extension_everywhere(&mut root, "KHR_materials_variants");
453 }
454 let Value::Object(json) = &mut root else { unreachable!() };
455 if !textures {
456 for key in ["textures", "images", "samplers"] {
457 json.remove(key);
458 }
459 each(json, "materials", remove_textures);
460 dead.push("/textures/");
461 self.refs.clear();
462 }
463 if !keep.extras {
464 let info: Option<Map<String, Value>> = root
466 .pointer("/asset/extras/source")
467 .and_then(Value::as_object)
468 .map(|s| {
469 s.iter()
470 .filter(|(k, _)| crate::source::KEYS.contains(&k.as_str()))
471 .map(|(k, v)| (k.clone(), v.clone()))
472 .collect()
473 })
474 .filter(|m: &Map<String, Value>| !m.is_empty());
475 remove_key_everywhere(&mut root, "extras");
476 if let (Some(info), Some(asset)) = (info, root.get_mut("asset").and_then(Value::as_object_mut)) {
477 asset.insert("extras".into(), serde_json::json!({ "source": info }));
478 }
479 }
480 let Value::Object(json) = &mut root else { unreachable!() };
481 if !dead.is_empty() {
482 each(json, "animations", |a| {
483 if let Some(ch) = a.get_mut("channels").and_then(Value::as_array_mut) {
484 ch.retain(|c| {
485 let pointer = c
486 .pointer("/target/extensions/KHR_animation_pointer/pointer")
487 .and_then(Value::as_str);
488 !pointer.is_some_and(|p| dead.iter().any(|d| matches_pointer(p, d)))
489 });
490 }
491 });
492 }
493 if let Some(anims) = json.get_mut("animations").and_then(Value::as_array_mut) {
495 anims.retain(|a| {
496 a.get("channels")
497 .and_then(Value::as_array)
498 .is_some_and(|c| !c.is_empty())
499 });
500 if anims.is_empty() {
501 json.remove("animations");
502 }
503 }
504 let mut after = BTreeSet::new();
505 extensions_present(&root, &mut after);
506 let Value::Object(json) = &mut root else { unreachable!() };
507 for key in ["extensionsUsed", "extensionsRequired"] {
508 if let Some(list) = json.get_mut(key).and_then(Value::as_array_mut) {
509 list.retain(|e| e.as_str().is_none_or(|e| !before.contains(e) || after.contains(e)));
510 if list.is_empty() {
511 json.remove(key);
512 }
513 }
514 }
515 let Value::Object(json) = root else { unreachable!() };
516 *self.json_mut() = json;
517 }
518}
519
520fn matches_pointer(p: &str, prefix: &str) -> bool {
523 let mut segs = p.split('/');
524 let pre: Vec<&str> = prefix.trim_end_matches('/').split('/').collect();
525 pre.iter()
526 .all(|want| segs.next().is_some_and(|s| *want == "*" || s == *want))
527}
528
529#[cfg(test)]
530mod tests {
531 use serde_json::json;
532
533 use super::*;
534
535 fn doc(v: Value) -> Document {
536 let Value::Object(json) = v else { unreachable!() };
537 let mut d = Document::empty(Map::new());
538 *d.json_mut() = json;
539 d
540 }
541
542 #[test]
543 fn keeps_everything_by_default() {
544 let v = json!({ "asset": { "version": "2.0" }, "animations": [{ "channels": [{}] }], "extras": { "a": 1 } });
545 let mut d = doc(v.clone());
546 d.prune(Keep::default());
547 assert_eq!(Value::Object(d.json().clone()), v);
548 }
549
550 #[test]
551 fn a_triangle_limit_alone_prunes_nothing() {
552 let v = json!({ "asset": { "version": "2.0" }, "animations": [{ "channels": [] }] });
554 let mut d = doc(v.clone());
555 d.prune(Keep {
556 max_triangles: 10,
557 image_bytes: false,
558 ..Keep::ALL
559 });
560 assert_eq!(Value::Object(d.json().clone()), v);
561 let mut d = doc(v);
562 d.prune(Keep {
563 extras: false,
564 ..Keep::ALL
565 });
566 assert!(!d.json().contains_key("animations"));
567 }
568
569 #[test]
570 fn point_settings_prune_nothing_but_reach_flatten() {
571 let v = json!({ "asset": { "version": "2.0" }, "animations": [{ "channels": [] }] });
572 let mut d = doc(v.clone());
573 d.prune(Keep {
574 lines_and_points: false,
575 max_points: usize::MAX,
576 ..Keep::ALL
577 });
578 assert_eq!(Value::Object(d.json().clone()), v);
579 assert!(!d.lines_and_points());
580 assert_eq!(d.max_points(), TRIANGLE_CEILING);
581 d.prune(Keep::LIGHT);
582 assert!(d.lines_and_points());
583 assert_eq!(d.max_points(), MAX_POINTS);
584 }
585
586 #[test]
587 fn the_triangle_limit_is_clamped() {
588 assert_eq!(Keep::ALL.triangles(), MAX_TRIANGLES);
589 assert_eq!(Keep::LIGHT.max_triangles, MAX_TRIANGLES);
590 let keep = |max_triangles| Keep {
591 max_triangles,
592 ..Keep::ALL
593 };
594 assert_eq!(keep(12_000_000).triangles(), 12_000_000);
595 assert_eq!(keep(usize::MAX).triangles(), TRIANGLE_CEILING);
596 }
597
598 #[test]
599 fn drops_animations_but_keeps_skins() {
600 let mut d = doc(json!({
601 "asset": { "version": "2.0" },
602 "nodes": [{ "mesh": 0, "skin": 0 }, { "camera": 0 }],
603 "skins": [{ "joints": [1] }],
604 "cameras": [{ "type": "perspective" }],
605 "meshes": [{ "primitives": [{ "attributes": { "POSITION": 0, "JOINTS_0": 1, "WEIGHTS_0": 2 } }] }],
606 "animations": [{ "channels": [{ "sampler": 0, "target": { "node": 1, "path": "rotation" } }] }],
607 "extensions": { "KHR_lights_punctual": { "lights": [{ "type": "point" }] } },
608 "extensionsUsed": ["KHR_lights_punctual", "KHR_mesh_quantization"],
609 }));
610 d.prune(Keep::MESHES);
611 assert_eq!(
612 Value::Object(d.json().clone()),
613 json!({
614 "asset": { "version": "2.0" },
615 "nodes": [{ "mesh": 0, "skin": 0 }, {}],
616 "skins": [{ "joints": [1] }],
617 "meshes": [{ "primitives": [{ "attributes": { "POSITION": 0, "JOINTS_0": 1, "WEIGHTS_0": 2 } }] }],
618 "extensionsUsed": ["KHR_mesh_quantization"],
619 })
620 );
621 }
622
623 #[test]
624 fn drops_skins_morphs_and_textures() {
625 let mut d = doc(json!({
626 "asset": { "version": "2.0" },
627 "nodes": [{ "mesh": 0, "skin": 0, "weights": [0.5] }],
628 "skins": [{ "joints": [0] }],
629 "meshes": [{
630 "weights": [0.0],
631 "extras": { "targetNames": ["smile"], "keep": true },
632 "primitives": [{ "attributes": { "POSITION": 0, "JOINTS_0": 1 }, "targets": [{ "POSITION": 2 }], "material": 0 }],
633 }],
634 "materials": [{
635 "pbrMetallicRoughness": { "baseColorTexture": { "index": 0 }, "baseColorFactor": [1, 1, 1, 1] },
636 "extensions": { "KHR_materials_clearcoat": { "clearcoatTexture": { "index": 0 }, "clearcoatFactor": 1 } },
637 }],
638 "textures": [{ "source": 0 }],
639 "images": [{ "uri": "a.png" }],
640 "animations": [
641 { "channels": [{ "sampler": 0, "target": { "node": 0, "path": "weights" } }] },
642 { "channels": [{ "sampler": 0, "target": { "node": 0, "path": "translation" } }] },
643 ],
644 "extensionsUsed": ["KHR_materials_clearcoat"],
645 }));
646 d.prune(Keep {
647 skins: false,
648 morph_targets: false,
649 textures: false,
650 ..Keep::ALL
651 });
652 assert_eq!(
653 Value::Object(d.json().clone()),
654 json!({
655 "asset": { "version": "2.0" },
656 "nodes": [{ "mesh": 0 }],
657 "meshes": [{ "extras": { "keep": true }, "primitives": [{ "attributes": { "POSITION": 0 }, "material": 0 }] }],
658 "materials": [{
659 "pbrMetallicRoughness": { "baseColorFactor": [1, 1, 1, 1] },
660 "extensions": { "KHR_materials_clearcoat": { "clearcoatFactor": 1 } },
661 }],
662 "animations": [{ "channels": [{ "sampler": 0, "target": { "node": 0, "path": "translation" } }] }],
663 "extensionsUsed": ["KHR_materials_clearcoat"],
664 })
665 );
666 }
667
668 #[test]
669 fn drops_extras_and_pointer_channels() {
670 let mut d = doc(json!({
671 "asset": { "version": "2.0", "extras": 1 },
672 "materials": [{ "extras": { "x": 1 } }],
673 "animations": [{ "channels": [
674 { "sampler": 0, "target": { "path": "pointer", "extensions": { "KHR_animation_pointer": { "pointer": "/materials/0/emissiveFactor" } } } },
675 { "sampler": 0, "target": { "path": "pointer", "extensions": { "KHR_animation_pointer": { "pointer": "/nodes/0/translation" } } } },
676 ] }],
677 }));
678 d.prune(Keep {
679 materials: false,
680 extras: false,
681 ..Keep::ALL
682 });
683 assert_eq!(
684 Value::Object(d.json().clone()),
685 json!({
686 "asset": { "version": "2.0" },
687 "animations": [{ "channels": [
688 { "sampler": 0, "target": { "path": "pointer", "extensions": { "KHR_animation_pointer": { "pointer": "/nodes/0/translation" } } } },
689 ] }],
690 })
691 );
692 }
693
694 #[test]
695 fn pointer_prefixes() {
696 assert!(matches_pointer("/meshes/3/weights", "/meshes/*/weights"));
697 assert!(matches_pointer("/meshes/3/weights/1", "/meshes/*/weights"));
698 assert!(!matches_pointer("/meshes/3/primitives", "/meshes/*/weights"));
699 assert!(matches_pointer("/cameras/0/perspective/yfov", "/cameras/"));
700 assert!(!matches_pointer("/camerasx/0", "/cameras/"));
701 }
702}