1use std::collections::BTreeSet;
4use std::sync::atomic::{AtomicUsize, Ordering};
5use std::sync::{Mutex, PoisonError};
6
7use serde_json::{Map, Value};
8
9use crate::document::Document;
10use crate::mesh::{MAX_POINTS, MAX_TRIANGLES, TRIANGLE_CEILING};
11
12#[non_exhaustive]
45#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
46#[allow(clippy::struct_excessive_bools, reason = "independent switches")]
47pub struct Keep {
48 pub animations: bool,
50 pub skins: bool,
53 pub morph_targets: bool,
55 pub materials: bool,
58 pub textures: bool,
60 pub image_bytes: bool,
67 pub cameras: bool,
69 pub lights: bool,
71 pub extras: bool,
75 pub max_triangles: usize,
80 pub lines_and_points: bool,
85 pub max_points: usize,
90 pub threads: usize,
95 crease: u16,
97}
98
99impl Default for Keep {
100 fn default() -> Self {
101 Self::ALL
102 }
103}
104
105impl Keep {
106 pub const ALL: Keep = Keep {
108 animations: true,
109 skins: true,
110 morph_targets: true,
111 materials: true,
112 textures: true,
113 image_bytes: true,
114 cameras: true,
115 lights: true,
116 extras: true,
117 max_triangles: MAX_TRIANGLES,
118 lines_and_points: true,
119 max_points: MAX_POINTS,
120 threads: 1,
121 crease: 3000,
122 };
123
124 pub const MESHES: Keep = Keep {
127 animations: false,
128 cameras: false,
129 lights: false,
130 ..Keep::ALL
131 };
132
133 pub const LIGHT: Keep = Keep {
136 image_bytes: false,
137 ..Keep::MESHES
138 };
139
140 #[must_use]
142 pub const fn with_animations(mut self, animations: bool) -> Self {
143 self.animations = animations;
144 self
145 }
146
147 #[must_use]
149 pub const fn with_skins(mut self, skins: bool) -> Self {
150 self.skins = skins;
151 self
152 }
153
154 #[must_use]
156 pub const fn with_morph_targets(mut self, morph_targets: bool) -> Self {
157 self.morph_targets = morph_targets;
158 self
159 }
160
161 #[must_use]
163 pub const fn with_materials(mut self, materials: bool) -> Self {
164 self.materials = materials;
165 self
166 }
167
168 #[must_use]
170 pub const fn with_textures(mut self, textures: bool) -> Self {
171 self.textures = textures;
172 self
173 }
174
175 #[must_use]
177 pub const fn with_image_bytes(mut self, image_bytes: bool) -> Self {
178 self.image_bytes = image_bytes;
179 self
180 }
181
182 #[must_use]
184 pub const fn with_cameras(mut self, cameras: bool) -> Self {
185 self.cameras = cameras;
186 self
187 }
188
189 #[must_use]
191 pub const fn with_lights(mut self, lights: bool) -> Self {
192 self.lights = lights;
193 self
194 }
195
196 #[must_use]
198 pub const fn with_extras(mut self, extras: bool) -> Self {
199 self.extras = extras;
200 self
201 }
202
203 #[must_use]
205 pub const fn with_max_triangles(mut self, max_triangles: usize) -> Self {
206 self.max_triangles = max_triangles;
207 self
208 }
209
210 #[must_use]
212 pub const fn with_lines_and_points(mut self, lines_and_points: bool) -> Self {
213 self.lines_and_points = lines_and_points;
214 self
215 }
216
217 #[must_use]
219 pub const fn with_max_points(mut self, max_points: usize) -> Self {
220 self.max_points = max_points;
221 self
222 }
223
224 #[must_use]
226 pub const fn with_threads(mut self, threads: usize) -> Self {
227 self.threads = threads;
228 self
229 }
230
231 #[must_use]
244 #[allow(
245 clippy::cast_possible_truncation,
246 clippy::cast_sign_loss,
247 reason = "between 0 and 18000 once clamped"
248 )]
249 pub const fn with_crease_angle(mut self, degrees: f32) -> Self {
250 self.crease = if degrees.is_nan() {
251 3000
252 } else if degrees <= 0.0 {
253 0
254 } else if degrees >= 180.0 {
255 18000
256 } else {
257 (degrees * 100.0 + 0.5) as u16
258 };
259 self
260 }
261
262 #[must_use]
272 pub const fn crease_angle(&self) -> f32 {
273 self.crease as f32 / 100.0
274 }
275
276 pub(crate) fn triangles(self) -> usize {
278 self.max_triangles.min(TRIANGLE_CEILING)
279 }
280
281 pub(crate) fn points(self) -> usize {
283 self.max_points.min(TRIANGLE_CEILING)
284 }
285
286 #[cfg_attr(
289 not(any(
290 feature = "obj",
291 feature = "spz",
292 feature = "las",
293 feature = "pcd",
294 feature = "xyz",
295 feature = "e57",
296 feature = "ac3d"
297 )),
298 allow(dead_code, reason = "only the OBJ and SPZ readers take threads")
299 )]
300 pub(crate) fn thread_count(self) -> usize {
301 thread_count(self.threads)
302 }
303}
304
305pub(crate) fn thread_count(threads: usize) -> usize {
308 if cfg!(all(target_family = "wasm", not(target_feature = "atomics"))) {
309 1
310 } else if threads == 0 {
311 std::thread::available_parallelism().map_or(1, std::num::NonZero::get)
312 } else {
313 threads
314 }
315}
316
317#[cfg(test)]
318thread_local! {
319 pub(crate) static NO_THREADS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
321}
322
323#[cfg_attr(
325 not(any(
326 feature = "obj",
327 feature = "spz",
328 feature = "las",
329 feature = "pcd",
330 feature = "xyz",
331 feature = "e57",
332 feature = "ac3d",
333 feature = "fbx"
334 )),
335 allow(dead_code, reason = "only some readers, and the FBX writer, take threads")
336)]
337pub(crate) fn spawn<'s>(s: &'s std::thread::Scope<'s, '_>, f: impl FnOnce() + Send + 's) -> bool {
338 #[cfg(test)]
339 if NO_THREADS.get() {
340 return false;
341 }
342 std::thread::Builder::new().spawn_scoped(s, f).is_ok()
343}
344
345#[cfg_attr(
349 not(any(feature = "ac3d", feature = "fbx")),
350 allow(dead_code, reason = "only the AC3D reader and the FBX writer share work this way")
351)]
352pub(crate) fn par_map_with<T: Sync, S, R: Send>(
353 items: &[T],
354 threads: usize,
355 init: impl Fn() -> S + Sync,
356 f: impl Fn(&mut S, &T) -> R + Sync,
357) -> Vec<R> {
358 if threads <= 1 || items.len() <= 1 {
359 let mut state = init();
360 return items.iter().map(|t| f(&mut state, t)).collect();
361 }
362 let next = AtomicUsize::new(0);
363 let done: Mutex<Vec<Option<R>>> = Mutex::new((0..items.len()).map(|_| None).collect());
364 let run = || {
365 let mut state = init();
366 loop {
367 let k = next.fetch_add(1, Ordering::Relaxed);
368 let Some(item) = items.get(k) else { break };
369 let r = f(&mut state, item);
370 done.lock().unwrap_or_else(PoisonError::into_inner)[k] = Some(r);
371 }
372 };
373 std::thread::scope(|s| {
374 for _ in 1..threads.min(items.len()) {
375 if !spawn(s, run) {
376 break;
377 }
378 }
379 run();
380 });
381 done.into_inner()
382 .unwrap_or_else(PoisonError::into_inner)
383 .into_iter()
384 .flatten()
385 .collect()
386}
387
388fn each(obj: &mut Map<String, Value>, key: &str, mut f: impl FnMut(&mut Map<String, Value>)) {
390 let items = obj.get_mut(key).and_then(Value::as_array_mut);
391 for item in items.into_iter().flatten().filter_map(Value::as_object_mut) {
392 f(item);
393 }
394}
395
396fn primitives(json: &mut Map<String, Value>, mut f: impl FnMut(&mut Map<String, Value>)) {
398 each(json, "meshes", |m| each(m, "primitives", &mut f));
399}
400
401fn remove_extension(obj: &mut Map<String, Value>, name: &str) {
403 if let Some(exts) = obj.get_mut("extensions").and_then(Value::as_object_mut) {
404 exts.remove(name);
405 if exts.is_empty() {
406 obj.remove("extensions");
407 }
408 }
409}
410
411fn remove_extension_everywhere(v: &mut Value, name: &str) {
413 match v {
414 Value::Object(obj) => {
415 remove_extension(obj, name);
416 obj.values_mut().for_each(|v| remove_extension_everywhere(v, name));
417 }
418 Value::Array(a) => a.iter_mut().for_each(|v| remove_extension_everywhere(v, name)),
419 _ => {}
420 }
421}
422
423fn remove_key_everywhere(v: &mut Value, key: &str) {
425 match v {
426 Value::Object(obj) => {
427 obj.remove(key);
428 obj.values_mut().for_each(|v| remove_key_everywhere(v, key));
429 }
430 Value::Array(a) => a.iter_mut().for_each(|v| remove_key_everywhere(v, key)),
431 _ => {}
432 }
433}
434
435fn remove_textures(obj: &mut Map<String, Value>) {
438 obj.retain(|k, v| !(k.ends_with("Texture") && v.is_object()));
439 for v in obj.values_mut() {
440 if let Value::Object(o) = v {
441 remove_textures(o);
442 }
443 }
444}
445
446fn extensions_present(v: &Value, out: &mut BTreeSet<String>) {
448 match v {
449 Value::Object(obj) => {
450 if let Some(exts) = obj.get("extensions").and_then(Value::as_object) {
451 out.extend(exts.keys().cloned());
452 }
453 obj.values().for_each(|v| extensions_present(v, out));
454 }
455 Value::Array(a) => a.iter().for_each(|v| extensions_present(v, out)),
456 _ => {}
457 }
458}
459
460impl Document {
461 pub fn prune(&mut self, keep: Keep) {
469 self.lines_and_points = keep.lines_and_points;
470 self.max_points = keep.points();
471 if (Keep {
472 image_bytes: true,
473 max_triangles: Keep::ALL.max_triangles,
474 lines_and_points: true,
475 max_points: Keep::ALL.max_points,
476 threads: Keep::ALL.threads,
477 ..keep
478 }) == Keep::ALL
479 {
480 return;
481 }
482 let missed = if keep.textures && keep.materials {
483 None
484 } else {
485 self.missed.take()
486 };
487 let mut before = BTreeSet::new();
488 let mut root = Value::Object(std::mem::take(self.json_mut()));
489 if let Some(missed) = missed
492 && let Some(source) = root.pointer_mut("/asset/extras/source").and_then(Value::as_object_mut)
493 {
494 let (missed, counted) = *missed;
495 if counted {
496 source.remove("droppedTextures");
497 }
498 if let Some(Value::Array(files)) = source.get_mut("missingFiles") {
499 files.retain(|f| !f.as_str().is_some_and(|f| missed.files.iter().any(|m| m == f)));
500 if files.is_empty() {
501 source.remove("missingFiles");
502 }
503 }
504 }
505 extensions_present(&root, &mut before);
506 let Value::Object(json) = &mut root else { unreachable!() };
507 let mut dead: Vec<&str> = Vec::new();
509 if !keep.animations {
510 json.remove("animations");
511 }
512 if !keep.cameras {
513 json.remove("cameras");
514 each(json, "nodes", |n| {
515 n.remove("camera");
516 });
517 dead.push("/cameras/");
518 }
519 if !keep.lights {
520 remove_extension_everywhere(&mut root, "KHR_lights_punctual");
521 dead.push("/extensions/KHR_lights_punctual/");
522 }
523 let Value::Object(json) = &mut root else { unreachable!() };
524 if !keep.skins {
525 json.remove("skins");
526 each(json, "nodes", |n| {
527 n.remove("skin");
528 });
529 primitives(json, |p| {
530 let skinning = |k: &String| k.starts_with("JOINTS_") || k.starts_with("WEIGHTS_");
531 if let Some(a) = p.get_mut("attributes").and_then(Value::as_object_mut) {
532 a.retain(|k, _| !skinning(k));
533 }
534 let draco = p
535 .get_mut("extensions")
536 .and_then(|e| e.get_mut("KHR_draco_mesh_compression"))
537 .and_then(|d| d.get_mut("attributes"))
538 .and_then(Value::as_object_mut);
539 if let Some(a) = draco {
540 a.retain(|k, _| !skinning(k));
541 }
542 });
543 }
544 if !keep.morph_targets {
545 primitives(json, |p| {
546 p.remove("targets");
547 });
548 each(json, "meshes", |m| {
549 m.remove("weights");
550 if let Some(x) = m.get_mut("extras").and_then(Value::as_object_mut) {
551 x.remove("targetNames");
552 }
553 });
554 each(json, "nodes", |n| {
555 n.remove("weights");
556 });
557 each(json, "animations", |a| {
558 if let Some(ch) = a.get_mut("channels").and_then(Value::as_array_mut) {
559 ch.retain(|c| c.pointer("/target/path").and_then(Value::as_str) != Some("weights"));
560 }
561 });
562 dead.extend(["/meshes/*/weights", "/nodes/*/weights"]);
563 }
564 let textures = keep.textures && keep.materials;
565 if !keep.materials {
566 json.remove("materials");
567 primitives(json, |p| {
568 p.remove("material");
569 });
570 dead.push("/materials/");
571 }
572 if !keep.materials {
573 remove_extension_everywhere(&mut root, "KHR_materials_variants");
574 }
575 let Value::Object(json) = &mut root else { unreachable!() };
576 if !textures {
577 for key in ["textures", "images", "samplers"] {
578 json.remove(key);
579 }
580 each(json, "materials", remove_textures);
581 dead.push("/textures/");
582 self.refs.clear();
583 }
584 if !keep.extras {
585 let info: Option<Map<String, Value>> = root
587 .pointer("/asset/extras/source")
588 .and_then(Value::as_object)
589 .map(|s| {
590 s.iter()
591 .filter(|(k, _)| crate::source::KEYS.contains(&k.as_str()))
592 .map(|(k, v)| (k.clone(), v.clone()))
593 .collect()
594 })
595 .filter(|m: &Map<String, Value>| !m.is_empty());
596 remove_key_everywhere(&mut root, "extras");
597 if let (Some(info), Some(asset)) = (info, root.get_mut("asset").and_then(Value::as_object_mut)) {
598 asset.insert("extras".into(), serde_json::json!({ "source": info }));
599 }
600 }
601 let Value::Object(json) = &mut root else { unreachable!() };
602 if !dead.is_empty() {
603 each(json, "animations", |a| {
604 if let Some(ch) = a.get_mut("channels").and_then(Value::as_array_mut) {
605 ch.retain(|c| {
606 let pointer = c
607 .pointer("/target/extensions/KHR_animation_pointer/pointer")
608 .and_then(Value::as_str);
609 !pointer.is_some_and(|p| dead.iter().any(|d| matches_pointer(p, d)))
610 });
611 }
612 });
613 }
614 if let Some(anims) = json.get_mut("animations").and_then(Value::as_array_mut) {
616 anims.retain(|a| {
617 a.get("channels")
618 .and_then(Value::as_array)
619 .is_some_and(|c| !c.is_empty())
620 });
621 if anims.is_empty() {
622 json.remove("animations");
623 }
624 }
625 if !keep.animations
628 && let Some(Value::Object(source)) = json.get_mut("asset").and_then(|a| a.pointer_mut("/extras/source"))
629 {
630 crate::source::drop_assumed_frame_rate(source);
631 }
632 let mut after = BTreeSet::new();
633 extensions_present(&root, &mut after);
634 let Value::Object(json) = &mut root else { unreachable!() };
635 for key in ["extensionsUsed", "extensionsRequired"] {
636 if let Some(list) = json.get_mut(key).and_then(Value::as_array_mut) {
637 list.retain(|e| e.as_str().is_none_or(|e| !before.contains(e) || after.contains(e)));
638 if list.is_empty() {
639 json.remove(key);
640 }
641 }
642 }
643 let Value::Object(json) = root else { unreachable!() };
644 *self.json_mut() = json;
645 }
646}
647
648fn matches_pointer(p: &str, prefix: &str) -> bool {
651 let mut segs = p.split('/');
652 let pre: Vec<&str> = prefix.trim_end_matches('/').split('/').collect();
653 pre.iter()
654 .all(|want| segs.next().is_some_and(|s| *want == "*" || s == *want))
655}
656
657#[cfg(test)]
658mod tests {
659 use serde_json::json;
660
661 use super::*;
662
663 fn doc(v: Value) -> Document {
664 let Value::Object(json) = v else { unreachable!() };
665 let mut d = Document::empty(Map::new());
666 *d.json_mut() = json;
667 d
668 }
669
670 #[test]
671 fn keeps_everything_by_default() {
672 let v = json!({ "asset": { "version": "2.0" }, "animations": [{ "channels": [{}] }], "extras": { "a": 1 } });
673 let mut d = doc(v.clone());
674 d.prune(Keep::default());
675 assert_eq!(Value::Object(d.json().clone()), v);
676 }
677
678 #[test]
679 fn a_triangle_limit_alone_prunes_nothing() {
680 let v = json!({ "asset": { "version": "2.0" }, "animations": [{ "channels": [] }] });
682 let mut d = doc(v.clone());
683 d.prune(Keep {
684 max_triangles: 10,
685 image_bytes: false,
686 ..Keep::ALL
687 });
688 assert_eq!(Value::Object(d.json().clone()), v);
689 let mut d = doc(v);
690 d.prune(Keep {
691 extras: false,
692 ..Keep::ALL
693 });
694 assert!(!d.json().contains_key("animations"));
695 }
696
697 #[test]
698 fn point_settings_prune_nothing_but_reach_flatten() {
699 let v = json!({ "asset": { "version": "2.0" }, "animations": [{ "channels": [] }] });
700 let mut d = doc(v.clone());
701 d.prune(Keep {
702 lines_and_points: false,
703 max_points: usize::MAX,
704 ..Keep::ALL
705 });
706 assert_eq!(Value::Object(d.json().clone()), v);
707 assert!(!d.lines_and_points());
708 assert_eq!(d.max_points(), TRIANGLE_CEILING);
709 d.prune(Keep::LIGHT);
710 assert!(d.lines_and_points());
711 assert_eq!(d.max_points(), MAX_POINTS);
712 }
713
714 #[test]
715 fn the_triangle_limit_is_clamped() {
716 assert_eq!(Keep::ALL.triangles(), MAX_TRIANGLES);
717 assert_eq!(Keep::LIGHT.max_triangles, MAX_TRIANGLES);
718 let keep = |max_triangles| Keep {
719 max_triangles,
720 ..Keep::ALL
721 };
722 assert_eq!(keep(12_000_000).triangles(), 12_000_000);
723 assert_eq!(keep(usize::MAX).triangles(), TRIANGLE_CEILING);
724 }
725
726 #[test]
727 fn drops_animations_but_keeps_skins() {
728 let mut d = doc(json!({
729 "asset": { "version": "2.0" },
730 "nodes": [{ "mesh": 0, "skin": 0 }, { "camera": 0 }],
731 "skins": [{ "joints": [1] }],
732 "cameras": [{ "type": "perspective" }],
733 "meshes": [{ "primitives": [{ "attributes": { "POSITION": 0, "JOINTS_0": 1, "WEIGHTS_0": 2 } }] }],
734 "animations": [{ "channels": [{ "sampler": 0, "target": { "node": 1, "path": "rotation" } }] }],
735 "extensions": { "KHR_lights_punctual": { "lights": [{ "type": "point" }] } },
736 "extensionsUsed": ["KHR_lights_punctual", "KHR_mesh_quantization"],
737 }));
738 d.prune(Keep::MESHES);
739 assert_eq!(
740 Value::Object(d.json().clone()),
741 json!({
742 "asset": { "version": "2.0" },
743 "nodes": [{ "mesh": 0, "skin": 0 }, {}],
744 "skins": [{ "joints": [1] }],
745 "meshes": [{ "primitives": [{ "attributes": { "POSITION": 0, "JOINTS_0": 1, "WEIGHTS_0": 2 } }] }],
746 "extensionsUsed": ["KHR_mesh_quantization"],
747 })
748 );
749 }
750
751 #[test]
752 fn drops_skins_morphs_and_textures() {
753 let mut d = doc(json!({
754 "asset": { "version": "2.0" },
755 "nodes": [{ "mesh": 0, "skin": 0, "weights": [0.5] }],
756 "skins": [{ "joints": [0] }],
757 "meshes": [{
758 "weights": [0.0],
759 "extras": { "targetNames": ["smile"], "keep": true },
760 "primitives": [{ "attributes": { "POSITION": 0, "JOINTS_0": 1 }, "targets": [{ "POSITION": 2 }], "material": 0 }],
761 }],
762 "materials": [{
763 "pbrMetallicRoughness": { "baseColorTexture": { "index": 0 }, "baseColorFactor": [1, 1, 1, 1] },
764 "extensions": { "KHR_materials_clearcoat": { "clearcoatTexture": { "index": 0 }, "clearcoatFactor": 1 } },
765 }],
766 "textures": [{ "source": 0 }],
767 "images": [{ "uri": "a.png" }],
768 "animations": [
769 { "channels": [{ "sampler": 0, "target": { "node": 0, "path": "weights" } }] },
770 { "channels": [{ "sampler": 0, "target": { "node": 0, "path": "translation" } }] },
771 ],
772 "extensionsUsed": ["KHR_materials_clearcoat"],
773 }));
774 d.prune(Keep {
775 skins: false,
776 morph_targets: false,
777 textures: false,
778 ..Keep::ALL
779 });
780 assert_eq!(
781 Value::Object(d.json().clone()),
782 json!({
783 "asset": { "version": "2.0" },
784 "nodes": [{ "mesh": 0 }],
785 "meshes": [{ "extras": { "keep": true }, "primitives": [{ "attributes": { "POSITION": 0 }, "material": 0 }] }],
786 "materials": [{
787 "pbrMetallicRoughness": { "baseColorFactor": [1, 1, 1, 1] },
788 "extensions": { "KHR_materials_clearcoat": { "clearcoatFactor": 1 } },
789 }],
790 "animations": [{ "channels": [{ "sampler": 0, "target": { "node": 0, "path": "translation" } }] }],
791 "extensionsUsed": ["KHR_materials_clearcoat"],
792 })
793 );
794 }
795
796 #[test]
797 fn drops_extras_and_pointer_channels() {
798 let mut d = doc(json!({
799 "asset": { "version": "2.0", "extras": 1 },
800 "materials": [{ "extras": { "x": 1 } }],
801 "animations": [{ "channels": [
802 { "sampler": 0, "target": { "path": "pointer", "extensions": { "KHR_animation_pointer": { "pointer": "/materials/0/emissiveFactor" } } } },
803 { "sampler": 0, "target": { "path": "pointer", "extensions": { "KHR_animation_pointer": { "pointer": "/nodes/0/translation" } } } },
804 ] }],
805 }));
806 d.prune(Keep {
807 materials: false,
808 extras: false,
809 ..Keep::ALL
810 });
811 assert_eq!(
812 Value::Object(d.json().clone()),
813 json!({
814 "asset": { "version": "2.0" },
815 "animations": [{ "channels": [
816 { "sampler": 0, "target": { "path": "pointer", "extensions": { "KHR_animation_pointer": { "pointer": "/nodes/0/translation" } } } },
817 ] }],
818 })
819 );
820 }
821
822 #[test]
823 fn pointer_prefixes() {
824 assert!(matches_pointer("/meshes/3/weights", "/meshes/*/weights"));
825 assert!(matches_pointer("/meshes/3/weights/1", "/meshes/*/weights"));
826 assert!(!matches_pointer("/meshes/3/primitives", "/meshes/*/weights"));
827 assert!(matches_pointer("/cameras/0/perspective/yfov", "/cameras/"));
828 assert!(!matches_pointer("/camerasx/0", "/cameras/"));
829 }
830}