Skip to main content

polysmelt/
keep.rs

1//! What a load keeps: [`Keep`], applied by [`Document::prune`].
2
3use 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/// Which parts of a model a load keeps. Meshes and the node hierarchy are always kept; each
11/// switch here drops one kind of data on top of that. [`Keep::default`] keeps everything.
12/// [`Keep::max_triangles`] caps how big a model a load takes at all, and [`Keep::max_points`]
13/// how many points and lines [`Document::flatten`] draws.
14///
15/// Readers skip reading what isn't kept, so a narrow `Keep` also makes a load faster: no
16/// texture files, embedded images or (without materials) material libraries and shaders are
17/// read, nor animations, skins, morph targets, cameras or lights where the format keeps them
18/// apart. What a reader did read and [`Document::prune`] then dropped leaves its buffer views
19/// and accessors behind, unreferenced.
20///
21/// Without textures, a material's factors are its own: a reader that would have found a color
22/// texture doesn't turn the base color white for it.
23///
24/// A `Keep` is built from [`Keep::ALL`] (or [`Keep::MESHES`], [`Keep::LIGHT`]) with a `with_`
25/// setter for each switch, which chain and work in `const`s:
26///
27/// ```
28/// use polysmelt::Keep;
29/// // Static meshes for an engine that animates nothing, but still skins them.
30/// let keep = Keep::ALL.with_animations(false);
31/// # assert!(keep.skins);
32/// // A 100-million-triangle scan, past the default limit.
33/// let keep = Keep::ALL.with_max_triangles(120_000_000);
34/// // A 40-million-point lidar scan, drawn as points, read on every core.
35/// const SCAN: Keep = Keep::ALL.with_max_points(40_000_000).with_threads(0);
36/// // Only the surfaces: no points or lines in the flattened mesh.
37/// let keep = Keep::ALL.with_lines_and_points(false);
38/// ```
39///
40/// New switches may come in later versions, each keeping by default what it switches, so a
41/// `Keep` can't be written out field by field.
42#[non_exhaustive]
43#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
44#[allow(clippy::struct_excessive_bools, reason = "independent switches")]
45pub struct Keep {
46    /// Animations.
47    pub animations: bool,
48    /// Skins: skeletons, their inverse bind matrices, and the joints and weights on vertices.
49    /// The joint nodes stay either way, as part of the hierarchy.
50    pub skins: bool,
51    /// Morph targets and their weights (and animation channels that set them).
52    pub morph_targets: bool,
53    /// Materials; without them every primitive takes the default material, and textures go
54    /// too.
55    pub materials: bool,
56    /// Textures, their images and samplers, and where materials use them.
57    pub textures: bool,
58    /// The images' bytes. Without them, kept textures' images are found but not read or
59    /// converted: each is a glTF image with a `uri`, and [`Document::images`] has a handle on it
60    /// that says where it is (its file, if it's in one) and reads it on request.
61    /// [`Document::embed_images`] reads them all. [`Document::prune`] leaves images as they
62    /// are: once read, they stay read. Images a reader must look into to make a texture (an OBJ's
63    /// roughness and metalness maps packed into one) are read all the same, so the textures match.
64    pub image_bytes: bool,
65    /// Cameras.
66    pub cameras: bool,
67    /// Lights (`KHR_lights_punctual`).
68    pub lights: bool,
69    /// `extras` everywhere: custom properties and each format's own details. What the file says
70    /// about itself in the keys [`SourceInfo`](crate::source::SourceInfo) reads (units, up axis,
71    /// author...) stays in `asset.extras.source`, and the document's facts stay, either way.
72    pub extras: bool,
73    /// The most triangles a load accepts, against hostile or runaway files: a model that draws
74    /// more is refused (and [`Document::flatten`] refuses to draw more). Defaults to
75    /// [`MAX_TRIANGLES`]; raise it for big scans. Values past [`TRIANGLE_CEILING`] are clamped
76    /// to it.
77    pub max_triangles: usize,
78    /// Points and lines (glTF's `POINTS`, `LINES`, `LINE_LOOP` and `LINE_STRIP` primitives) in
79    /// what [`Document::flatten`] draws: point clouds, wireframes, curves. Without them it draws
80    /// only triangles, and a model of points and lines alone flattens to nothing. The document
81    /// keeps them either way.
82    pub lines_and_points: bool,
83    /// The most points and line segments [`Document::flatten`] draws, against huge point clouds:
84    /// a model that draws more is refused (unless [`Keep::lines_and_points`] leaves them out).
85    /// Counted apart from triangles. Defaults to [`MAX_POINTS`]; raise it for big scans. Values
86    /// past [`TRIANGLE_CEILING`] are clamped to it.
87    pub max_points: usize,
88    /// Threads a reader may split its work over, where it can: OBJ text and SPZ, so far. 1, the
89    /// default, reads on the calling thread; 0 takes one per core. The model read is the same
90    /// either way. Where threads can't be had (WebAssembly without shared memory, or a
91    /// platform that refuses to start one), it reads on the calling thread.
92    pub threads: usize,
93}
94
95impl Default for Keep {
96    fn default() -> Self {
97        Self::ALL
98    }
99}
100
101impl Keep {
102    /// Everything.
103    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    /// The meshes and what shapes or shades them (skins, morph targets, materials, textures,
120    /// extras), without animations, cameras or lights.
121    pub const MESHES: Keep = Keep {
122        animations: false,
123        cameras: false,
124        lights: false,
125        ..Keep::ALL
126    };
127
128    /// [`Keep::MESHES`] without reading the images: textures stay, as references to their
129    /// images (see [`Keep::image_bytes`]).
130    pub const LIGHT: Keep = Keep {
131        image_bytes: false,
132        ..Keep::MESHES
133    };
134
135    /// With [`Keep::animations`] set to `animations`.
136    #[must_use]
137    pub const fn with_animations(mut self, animations: bool) -> Self {
138        self.animations = animations;
139        self
140    }
141
142    /// With [`Keep::skins`] set to `skins`.
143    #[must_use]
144    pub const fn with_skins(mut self, skins: bool) -> Self {
145        self.skins = skins;
146        self
147    }
148
149    /// With [`Keep::morph_targets`] set to `morph_targets`.
150    #[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    /// With [`Keep::materials`] set to `materials`.
157    #[must_use]
158    pub const fn with_materials(mut self, materials: bool) -> Self {
159        self.materials = materials;
160        self
161    }
162
163    /// With [`Keep::textures`] set to `textures`.
164    #[must_use]
165    pub const fn with_textures(mut self, textures: bool) -> Self {
166        self.textures = textures;
167        self
168    }
169
170    /// With [`Keep::image_bytes`] set to `image_bytes`.
171    #[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    /// With [`Keep::cameras`] set to `cameras`.
178    #[must_use]
179    pub const fn with_cameras(mut self, cameras: bool) -> Self {
180        self.cameras = cameras;
181        self
182    }
183
184    /// With [`Keep::lights`] set to `lights`.
185    #[must_use]
186    pub const fn with_lights(mut self, lights: bool) -> Self {
187        self.lights = lights;
188        self
189    }
190
191    /// With [`Keep::extras`] set to `extras`.
192    #[must_use]
193    pub const fn with_extras(mut self, extras: bool) -> Self {
194        self.extras = extras;
195        self
196    }
197
198    /// With [`Keep::max_triangles`] set to `max_triangles`.
199    #[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    /// With [`Keep::lines_and_points`] set to `lines_and_points`.
206    #[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    /// With [`Keep::max_points`] set to `max_points`.
213    #[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    /// With [`Keep::threads`] set to `threads`.
220    #[must_use]
221    pub const fn with_threads(mut self, threads: usize) -> Self {
222        self.threads = threads;
223        self
224    }
225
226    /// [`Keep::max_triangles`], clamped to [`TRIANGLE_CEILING`].
227    pub(crate) fn triangles(self) -> usize {
228        self.max_triangles.min(TRIANGLE_CEILING)
229    }
230
231    /// [`Keep::max_points`], clamped to [`TRIANGLE_CEILING`].
232    pub(crate) fn points(self) -> usize {
233        self.max_points.min(TRIANGLE_CEILING)
234    }
235
236    /// [`Keep::threads`]: how many to use here, at least 1. WebAssembly without shared memory
237    /// has no threads; elsewhere, a reader whose threads can't be started reads on one.
238    #[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    /// For tests: thread starts fail, as on a platform without threads.
264    pub(crate) static NO_THREADS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
265}
266
267/// `f` started on a thread of `s`; false, and `f` dropped, where no thread can be started.
268#[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
288/// Calls `f` on each item of `obj[key]` that's an object.
289fn 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
296/// Calls `f` on every primitive.
297fn 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
301/// Removes extension `name` from `obj`, and its `extensions` if that leaves it empty.
302fn 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
311/// Removes extension `name` wherever it is.
312fn 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
323/// Removes every `key` member, at any depth.
324fn 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
335/// Removes the texture references (`...Texture` objects) in a material, its extensions'
336/// included.
337fn 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
346/// The names of every extension the JSON uses an object for.
347fn 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    /// Drops what `keep` doesn't keep. The JSON stays valid glTF: references to what went are
362    /// removed with it, and extensions no longer used are unlisted. Extensions Polysmelt doesn't
363    /// know that refer to dropped materials, textures or cameras may be left pointing at them.
364    /// [`Keep::max_triangles`] and [`Keep::threads`] play no part here. Points and lines stay in
365    /// the JSON: [`Keep::lines_and_points`] and [`Keep::max_points`] are recorded for
366    /// [`Document::flatten`] (see [`Document::set_lines_and_points`] and
367    /// [`Document::set_max_points`]).
368    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        // Animation pointers (`KHR_animation_pointer`) into what goes, go with it.
387        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            // What the file says about itself isn't a custom property: its normalized keys stay.
465            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        // An animation needs a channel.
494        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
520/// Whether JSON pointer `p` starts with `prefix`, where `*` in the prefix stands for one
521/// segment.
522fn 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        // Pruning drops animations without channels, whatever it keeps: a limit alone mustn't start it.
553        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}