Skip to main content

polysmelt/
keep.rs

1//! What a load keeps: [`Keep`], applied by [`Document::prune`].
2
3use 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/// Which parts of a model a load keeps. Meshes and the node hierarchy are always kept; each
13/// switch here drops one kind of data on top of that. [`Keep::default`] keeps everything.
14/// [`Keep::max_triangles`] caps how big a model a load takes at all, and [`Keep::max_points`]
15/// how many points and lines [`Document::flatten`] draws.
16///
17/// Readers skip reading what isn't kept, so a narrow `Keep` also makes a load faster: no
18/// texture files, embedded images or (without materials) material libraries and shaders are
19/// read, nor animations, skins, morph targets, cameras or lights where the format keeps them
20/// apart. What a reader did read and [`Document::prune`] then dropped leaves its buffer views
21/// and accessors behind, unreferenced.
22///
23/// Without textures, a material's factors are its own: a reader that would have found a color
24/// texture doesn't turn the base color white for it.
25///
26/// A `Keep` is built from [`Keep::ALL`] (or [`Keep::MESHES`], [`Keep::LIGHT`]) with a `with_`
27/// setter for each switch, which chain and work in `const`s:
28///
29/// ```
30/// use polysmelt::Keep;
31/// // Static meshes for an engine that animates nothing, but still skins them.
32/// let keep = Keep::ALL.with_animations(false);
33/// # assert!(keep.skins);
34/// // A 100-million-triangle scan, past the default limit.
35/// let keep = Keep::ALL.with_max_triangles(120_000_000);
36/// // A 40-million-point lidar scan, drawn as points, read on every core.
37/// const SCAN: Keep = Keep::ALL.with_max_points(40_000_000).with_threads(0);
38/// // Only the surfaces: no points or lines in the flattened mesh.
39/// let keep = Keep::ALL.with_lines_and_points(false);
40/// ```
41///
42/// New switches may come in later versions, each keeping by default what it switches, so a
43/// `Keep` can't be written out field by field.
44#[non_exhaustive]
45#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
46#[allow(clippy::struct_excessive_bools, reason = "independent switches")]
47pub struct Keep {
48    /// Animations.
49    pub animations: bool,
50    /// Skins: skeletons, their inverse bind matrices, and the joints and weights on vertices.
51    /// The joint nodes stay either way, as part of the hierarchy.
52    pub skins: bool,
53    /// Morph targets and their weights (and animation channels that set them).
54    pub morph_targets: bool,
55    /// Materials; without them every primitive takes the default material, and textures go
56    /// too.
57    pub materials: bool,
58    /// Textures, their images and samplers, and where materials use them.
59    pub textures: bool,
60    /// The images' bytes. Without them, kept textures' images are found but not read or
61    /// converted: each is a glTF image with a `uri`, and [`Document::images`] has a handle on it
62    /// that says where it is (its file, if it's in one) and reads it on request.
63    /// [`Document::embed_images`] reads them all. [`Document::prune`] leaves images as they
64    /// are: once read, they stay read. Images a reader must look into to make a texture (an OBJ's
65    /// roughness and metalness maps packed into one) are read all the same, so the textures match.
66    pub image_bytes: bool,
67    /// Cameras.
68    pub cameras: bool,
69    /// Lights (`KHR_lights_punctual`).
70    pub lights: bool,
71    /// `extras` everywhere: custom properties and each format's own details. What the file says
72    /// about itself in the keys [`SourceInfo`](crate::source::SourceInfo) reads (units, up axis,
73    /// author...) stays in `asset.extras.source`, and the document's facts stay, either way.
74    pub extras: bool,
75    /// The most triangles a load accepts, against hostile or runaway files: a model that draws
76    /// more is refused (and [`Document::flatten`] refuses to draw more). Defaults to
77    /// [`MAX_TRIANGLES`]; raise it for big scans. Values past [`TRIANGLE_CEILING`] are clamped
78    /// to it.
79    pub max_triangles: usize,
80    /// Points and lines (glTF's `POINTS`, `LINES`, `LINE_LOOP` and `LINE_STRIP` primitives) in
81    /// what [`Document::flatten`] draws: point clouds, wireframes, curves. Without them it draws
82    /// only triangles, and a model of points and lines alone flattens to nothing. The document
83    /// keeps them either way.
84    pub lines_and_points: bool,
85    /// The most points and line segments [`Document::flatten`] draws, against huge point clouds:
86    /// a model that draws more is refused (unless [`Keep::lines_and_points`] leaves them out).
87    /// Counted apart from triangles. Defaults to [`MAX_POINTS`]; raise it for big scans. Values
88    /// past [`TRIANGLE_CEILING`] are clamped to it.
89    pub max_points: usize,
90    /// Threads a reader may split its work over, where it can: OBJ text and SPZ, so far. 1, the
91    /// default, reads on the calling thread; 0 takes one per core. The model read is the same
92    /// either way. Where threads can't be had (WebAssembly without shared memory, or a
93    /// platform that refuses to start one), it reads on the calling thread.
94    pub threads: usize,
95    /// [`Keep::crease_angle`], in hundredths of a degree.
96    crease: u16,
97}
98
99impl Default for Keep {
100    fn default() -> Self {
101        Self::ALL
102    }
103}
104
105impl Keep {
106    /// Everything.
107    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    /// The meshes and what shapes or shades them (skins, morph targets, materials, textures,
125    /// extras), without animations, cameras or lights.
126    pub const MESHES: Keep = Keep {
127        animations: false,
128        cameras: false,
129        lights: false,
130        ..Keep::ALL
131    };
132
133    /// [`Keep::MESHES`] without reading the images: textures stay, as references to their
134    /// images (see [`Keep::image_bytes`]).
135    pub const LIGHT: Keep = Keep {
136        image_bytes: false,
137        ..Keep::MESHES
138    };
139
140    /// With [`Keep::animations`] set to `animations`.
141    #[must_use]
142    pub const fn with_animations(mut self, animations: bool) -> Self {
143        self.animations = animations;
144        self
145    }
146
147    /// With [`Keep::skins`] set to `skins`.
148    #[must_use]
149    pub const fn with_skins(mut self, skins: bool) -> Self {
150        self.skins = skins;
151        self
152    }
153
154    /// With [`Keep::morph_targets`] set to `morph_targets`.
155    #[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    /// With [`Keep::materials`] set to `materials`.
162    #[must_use]
163    pub const fn with_materials(mut self, materials: bool) -> Self {
164        self.materials = materials;
165        self
166    }
167
168    /// With [`Keep::textures`] set to `textures`.
169    #[must_use]
170    pub const fn with_textures(mut self, textures: bool) -> Self {
171        self.textures = textures;
172        self
173    }
174
175    /// With [`Keep::image_bytes`] set to `image_bytes`.
176    #[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    /// With [`Keep::cameras`] set to `cameras`.
183    #[must_use]
184    pub const fn with_cameras(mut self, cameras: bool) -> Self {
185        self.cameras = cameras;
186        self
187    }
188
189    /// With [`Keep::lights`] set to `lights`.
190    #[must_use]
191    pub const fn with_lights(mut self, lights: bool) -> Self {
192        self.lights = lights;
193        self
194    }
195
196    /// With [`Keep::extras`] set to `extras`.
197    #[must_use]
198    pub const fn with_extras(mut self, extras: bool) -> Self {
199        self.extras = extras;
200        self
201    }
202
203    /// With [`Keep::max_triangles`] set to `max_triangles`.
204    #[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    /// With [`Keep::lines_and_points`] set to `lines_and_points`.
211    #[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    /// With [`Keep::max_points`] set to `max_points`.
218    #[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    /// With [`Keep::threads`] set to `threads`.
225    #[must_use]
226    pub const fn with_threads(mut self, threads: usize) -> Self {
227        self.threads = threads;
228        self
229    }
230
231    /// With [`Keep::crease_angle`] set to `degrees`: from 0 to 180, and anything past either end is that end.
232    /// A value that isn't a number leaves the default, 30.
233    ///
234    /// ```
235    /// use polysmelt::Keep;
236    /// // Every face flat, as a file without normals is drawn where nothing smooths it.
237    /// const FACETED: Keep = Keep::ALL.with_crease_angle(0.0);
238    /// // Smooth across every shared vertex, whatever the edge.
239    /// let smooth = Keep::ALL.with_crease_angle(180.0);
240    /// assert_eq!((FACETED.crease_angle(), smooth.crease_angle()), (0.0, 180.0));
241    /// assert_eq!(Keep::ALL.crease_angle(), 30.0);
242    /// ```
243    #[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    /// The crease angle, in degrees, of the normals a reader makes for a file that has none and says nothing of
263    /// its own about smoothing: two faces that meet at a vertex share a normal there when they turn less than
264    /// this from each other, and the vertex is split where they turn more. 30 by default, so a box keeps its
265    /// hard edges and a finely cut curved surface is smooth; 0 makes every face flat, with normals of its own,
266    /// and 180 smooths across every vertex the file's faces share.
267    ///
268    /// A file's own normals and smoothing data always win: this is only for what has neither (an STL, a 3MF, an
269    /// OBJ with no `vn` and no `s`). A glTF file is read as it is, without normals if it has none. Set with
270    /// [`Keep::with_crease_angle`].
271    #[must_use]
272    pub const fn crease_angle(&self) -> f32 {
273        self.crease as f32 / 100.0
274    }
275
276    /// [`Keep::max_triangles`], clamped to [`TRIANGLE_CEILING`].
277    pub(crate) fn triangles(self) -> usize {
278        self.max_triangles.min(TRIANGLE_CEILING)
279    }
280
281    /// [`Keep::max_points`], clamped to [`TRIANGLE_CEILING`].
282    pub(crate) fn points(self) -> usize {
283        self.max_points.min(TRIANGLE_CEILING)
284    }
285
286    /// [`Keep::threads`]: how many to use here, at least 1. WebAssembly without shared memory
287    /// has no threads; elsewhere, a reader whose threads can't be started reads on one.
288    #[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
305/// Threads to use for a `threads` setting, at least 1: 0 takes one per core, and WebAssembly without shared memory
306/// has none to spare.
307pub(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    /// For tests: thread starts fail, as on a platform without threads.
320    pub(crate) static NO_THREADS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
321}
322
323/// `f` started on a thread of `s`; false, and `f` dropped, where no thread can be started.
324#[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/// `f` of each item, in order, spread over up to `threads` threads that each take the next item as they finish one.
346/// Each thread makes a state with `init` that `f` keeps using for the items it takes. Where no thread can be started,
347/// the calling thread does them all.
348#[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
388/// Calls `f` on each item of `obj[key]` that's an object.
389fn 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
396/// Calls `f` on every primitive.
397fn 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
401/// Removes extension `name` from `obj`, and its `extensions` if that leaves it empty.
402fn 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
411/// Removes extension `name` wherever it is.
412fn 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
423/// Removes every `key` member, at any depth.
424fn 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
435/// Removes the texture references (`...Texture` objects) in a material, its extensions'
436/// included.
437fn 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
446/// The names of every extension the JSON uses an object for.
447fn 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    /// Drops what `keep` doesn't keep. The JSON stays valid glTF: references to what went are
462    /// removed with it, and extensions no longer used are unlisted. Extensions Polysmelt doesn't
463    /// know that refer to dropped materials, textures or cameras may be left pointing at them.
464    /// [`Keep::max_triangles`] and [`Keep::threads`] play no part here. Points and lines stay in
465    /// the JSON: [`Keep::lines_and_points`] and [`Keep::max_points`] are recorded for
466    /// [`Document::flatten`] (see [`Document::set_lines_and_points`] and
467    /// [`Document::set_max_points`]).
468    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        // Without its textures a document misses none: what the reader looked for and didn't find goes, as a read
490        // without textures wouldn't have looked.
491        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        // Animation pointers (`KHR_animation_pointer`) into what goes, go with it.
508        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            // What the file says about itself isn't a custom property: its normalized keys stay.
586            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        // An animation needs a channel.
615        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        // An assumed frame rate is a guess about the animations: it goes with the last of them, as a read
626        // that keeps no animations leaves it out.
627        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
648/// Whether JSON pointer `p` starts with `prefix`, where `*` in the prefix stands for one
649/// segment.
650fn 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        // Pruning drops animations without channels, whatever it keeps: a limit alone mustn't start it.
681        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}