primase-core 0.2.0

primase core: the world store, core components, frames, the pass manager and gates
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
//! One asset read by itself (`core.asset`): a root entity naming what the asset is made of, and the passes that work
//! by asset: `select-assets` (keep some assets of a read world), `partition-by-asset` (one output part per asset) and
//! `place-assets` (place an asset a source did not place).
//!
//! A reader asked for one asset (a model, a character, a prop and its parts) spawns its entities as it reads any
//! world and a root holding [`Asset`]: each member with its [`Role`]. The members are references, so the asset's
//! closure ([`World::closure`]) is everything it needs; the asset's source identity is the root's `core.source`.
//! Optional members (clips, alternative parts) are members too: a selection pass prunes the ones a program does not
//! want, rewriting the root's list before it despawns them. An asset as a source authors it has no placement unless
//! the source places its parts (a prefab's renderers); a program that wants one drawn places it (`place-assets`).

use std::collections::{BTreeMap, BTreeSet};

use serde::Serialize;
use serde_json::Value;

use crate::convert::{PartitionGroup, PartitionPlan};
use crate::pass::{Given, OptionSpec, Options, Pass, PassLog, PassSpec};
use crate::{
    Component, Entity, Instance, JsonError, Mesh, MeshFile, Name, Resource, RigInstance, Skeleton, Skin,
    SkinInstance, Source, Transform, World,
};

/// What a member is to its asset.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize)]
pub enum Role {
    /// Something it draws: a prototype (with its mesh or mesh file), or a placement the source authors in the asset's
    /// own space.
    Part,
    /// A skeleton its parts bind to (`core.skeleton`).
    Rig,
    /// A clip it comes with. A member without `core.clip` is listed, not yet loaded/lowered:
    /// `core.clip_key` identifies it, `core.name` labels it and optional `core.clip_length`
    /// states a known length. Its reader descriptor remains on the same entity through load.
    Clip,
    /// A part drawn instead of another or not at all (an outfit's alternative), as the source's state says.
    Alternative,
}

/// `core.asset` (see the module documentation).
#[derive(Clone, Debug, Default, PartialEq, Serialize)]
pub struct Asset {
    pub members: Vec<(Entity, Role)>,
}

impl Component for Asset {
    const NAME: &'static str = "core.asset";
    const GEOMETRY: crate::Geometry = crate::Geometry::None;
    fn to_json(&self) -> Result<Option<Value>, JsonError> {
        crate::json::to_value(self).map(Some)
    }
    fn references(&self, out: &mut Vec<Entity>) {
        out.extend(self.members.iter().map(|(e, _)| *e));
    }
    /// Each member once and not the root; each what its role says, in core's form or still in its source's: a rig a
    /// `core.skeleton`, a clip a `core.clip`, a part or an alternative a prototype (a mesh or a mesh file) or a
    /// placement; or, still in its source's form, a member holding a component outside core (a reader's model,
    /// skeleton or clip as the source stores it, which a pass lowers) and no core form of another role (a clip member
    /// that is in core a mesh is no clip, whatever else it holds).
    fn verify(&self, e: Entity, w: &World) -> Result<(), String> {
        let names = w.component_names();
        let in_source_form = |m: Entity| {
            names
                .iter()
                .any(|n| !n.starts_with("core.") && w.entity_has_named(m, n))
        };
        let mut seen = BTreeSet::new();
        for &(m, role) in &self.members {
            if m == e || !seen.insert(m) {
                return Err(format!("member {m:?} is the root or listed twice"));
            }
            // each role's core form
            let rig = w.has::<Skeleton>(m);
            let clip = w.has::<crate::Clip>(m);
            let part = w.has::<Mesh>(m) || w.has::<MeshFile>(m) || w.has::<Instance>(m);
            let (own, other) = match role {
                Role::Rig => (rig, clip || part),
                Role::Clip => (clip, rig || part),
                Role::Part | Role::Alternative => (part, rig || clip),
            };
            let fits = own || (!other && in_source_form(m));
            if !fits {
                return Err(format!("member {m:?} is not what its role {role:?} says"));
            }
        }
        Ok(())
    }
}

/// `place-assets` (no options: at the world's origin): every asset whose parts nothing places is placed, once, at the
/// origin, as its source authors it:
/// - each `Rig` member gets a rig (`core.rig_instance` and `core.transform`) of its own;
/// - each `Part` prototype a placement (`core.instance`, `core.transform`), with a `core.skin_instance` when its mesh
///   is skinned to one of the asset's rigs (its first binding to that rig's skeleton);
/// - `Alternative` members are not placed (choosing one is a selection: counted), and a part the source already
///   places (a placement member, or a prototype something places) is left as it is; so is a rig: a skeleton that
///   already has one keeps it, and parts placed now are skinned to it. Run again, it places nothing.
///
/// The placed entities are content of their own ([`PassLog::place`]).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct PlaceAssets;

/// `place-assets`' declaration ([`crate::pass::PassRegistry::add`]): no options.
pub const PLACE_ASSETS: PassSpec = PassSpec {
    name: "place-assets",
    options: &[],
    make: |_| Ok(Box::new(PlaceAssets)),
};

impl Pass for PlaceAssets {
    fn name(&self) -> &'static str {
        "place-assets"
    }
    /// A part of a conversion may hold no asset (the content `partition-by-asset` puts outside them): nothing to place.
    fn may_lack_inputs(&self) -> bool {
        true
    }
    fn requires(&self) -> &[&'static str] {
        &[Asset::NAME]
    }
    fn provides(&self) -> &[&'static str] {
        &[
            Instance::NAME,
            Transform::NAME,
            RigInstance::NAME,
            SkinInstance::NAME,
        ]
    }
    fn run(&self, w: &mut World, log: &mut PassLog) -> Result<(), String> {
        // what is placed already, and what this run places, as it goes: a part or a rig is placed once
        let mut placed: BTreeSet<Entity> = w.iter::<Instance>().map(|(_, i)| i.prototype).collect();
        let mut rigged: BTreeMap<Entity, Entity> = BTreeMap::new();
        for (rig, r) in w.iter::<RigInstance>() {
            rigged.entry(r.skeleton).or_insert(rig);
        }
        let assets: Vec<(Entity, Asset)> = w.iter::<Asset>().map(|(e, a)| (e, a.clone())).collect();
        for (root, asset) in assets {
            let mut rigs: Vec<(Entity, Entity)> = Vec::new();
            for &(m, role) in &asset.members {
                if role != Role::Rig {
                    continue;
                }
                if let Some(&rig) = rigged.get(&m) {
                    log.count("rigs already placed, left as they are", 1);
                    rigs.push((m, rig));
                    continue;
                }
                let rig = w.spawn();
                w.insert(rig, RigInstance { skeleton: m });
                w.insert(rig, Transform::IDENTITY);
                log.place_from(rig, root);
                rigged.insert(m, rig);
                rigs.push((m, rig));
            }
            for &(m, role) in &asset.members {
                match role {
                    Role::Alternative => log.count("alternative parts not placed (a selection chooses)", 1),
                    Role::Part if w.has::<Instance>(m) || placed.contains(&m) => {
                        log.count("parts the source places, left as they are", 1);
                    }
                    Role::Part => {
                        let p = w.spawn();
                        w.insert(
                            p,
                            Instance {
                                prototype: m,
                                variant: 0,
                            },
                        );
                        w.insert(p, Transform::IDENTITY);
                        let binding = w.get::<Skin>(m).and_then(|s| {
                            s.bindings.iter().find_map(|b| {
                                rigs.iter()
                                    .find(|(skel, _)| *skel == b.skeleton)
                                    .map(|&(_, rig)| (rig, b.id))
                            })
                        });
                        if let Some((rig, binding)) = binding {
                            w.insert(p, SkinInstance { rig, binding });
                            log.count("skinned parts placed with their rig", 1);
                        }
                        log.place_from(p, root);
                        log.count("parts placed", 1);
                        placed.insert(m);
                    }
                    Role::Rig | Role::Clip => {}
                }
            }
        }
        Ok(())
    }
}

/// What `select-assets` matches an asset's root by.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AssetField {
    /// Its source identity (`core.source`: `chr/c1010`).
    Key,
    /// Its name (`core.name`).
    Name,
}

impl AssetField {
    fn option(self) -> &'static str {
        match self {
            AssetField::Key => "keys",
            AssetField::Name => "names",
        }
    }

    /// The root's value of this field, if it has one.
    fn of(self, w: &World, root: Entity) -> Option<&str> {
        match self {
            AssetField::Key => w.get::<Source>(root).map(|s| s.0.as_str()),
            AssetField::Name => w.get::<Name>(root).map(|n| n.0.as_str()),
        }
    }
}

/// `select-assets{keys=K;K...}` or `select-assets{names=N;N...}` (one of the two, required): the assets whose roots'
/// `core.source` (or `core.name`) is one of the values are kept with everything they reach ([`World::closure`]);
/// every other entity is despawned, counted as left out (other assets, loose content, and authored placements of a
/// kept asset's parts, which reference the asset rather than belong to it: a program places what it extracted,
/// `place-assets`, and recentres it, `translate-world`). A value matching no asset is an error, naming the assets
/// there are. Every asset a value matches is kept. It runs on a planning world (a selection, before anything loads),
/// so what it leaves out is never loaded.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SelectAssets {
    pub field: AssetField,
    /// The values, in the order given, each once.
    pub values: Vec<String>,
}

/// `select-assets`' declaration ([`crate::pass::PassRegistry::add`]): `keys` or `names`, one of them.
pub const SELECT_ASSETS: PassSpec = PassSpec {
    name: "select-assets",
    options: &[
        OptionSpec::one_of(
            "assets",
            "keys",
            "example",
            "the assets' keys, `;` between, each once",
        ),
        OptionSpec::one_of(
            "assets",
            "names",
            "example",
            "the assets' names, `;` between, each once",
        ),
    ],
    make: select_assets,
};

fn select_assets(g: &Given) -> Result<Box<dyn Pass>, String> {
    let (k, field, v) = match (g.optional("keys"), g.optional("names")) {
        (Some(v), _) => ("keys", AssetField::Key, v),
        (None, Some(v)) => ("names", AssetField::Name, v),
        (None, None) => unreachable!("the declaration's check gives one of keys and names"),
    };
    let mut values: Vec<String> = Vec::new();
    for value in v.split(';').map(str::trim) {
        if value.is_empty() {
            return Err(format!("{k}={v}: an empty value"));
        }
        if values.iter().any(|x| x == value) {
            return Err(format!("{k}={v}: {value} twice"));
        }
        values.push(value.to_owned());
    }
    Ok(Box::new(SelectAssets { field, values }))
}

impl Pass for SelectAssets {
    fn name(&self) -> &'static str {
        "select-assets"
    }
    fn options(&self) -> Options {
        Options::from([(self.field.option().to_owned(), self.values.join(";"))])
    }
    fn requires(&self) -> &[&'static str] {
        &[Asset::NAME]
    }
    fn despawns_entities(&self) -> bool {
        true
    }
    fn run(&self, w: &mut World, log: &mut PassLog) -> Result<(), String> {
        keep_assets(w, self.field, &self.values, log)
    }
}

/// What `select-assets` does, for a pass that keeps assets it finds named elsewhere (what a read was asked for): the
/// assets whose roots' `field` is one of `values` kept with everything they reach, every other entity despawned and
/// counted as left out; a value matching no asset refused, naming the assets there are.
pub fn keep_assets(
    w: &mut World,
    field: AssetField,
    values: &[String],
    log: &mut PassLog,
) -> Result<(), String> {
    let roots: Vec<Entity> = w.iter::<Asset>().map(|(e, _)| e).collect();
    let mut selected = BTreeSet::new();
    for value in values {
        let matched: Vec<Entity> = roots
            .iter()
            .copied()
            .filter(|&r| field.of(w, r) == Some(value.as_str()))
            .collect();
        if matched.is_empty() {
            let mut there: Vec<&str> = roots.iter().filter_map(|&r| field.of(w, r)).collect();
            there.sort_unstable();
            let shown = there.iter().take(20).copied().collect::<Vec<_>>().join(", ");
            let more = there.len().saturating_sub(20);
            return Err(format!(
                "no asset whose {} is {value} (the world's: {shown}{})",
                match field {
                    AssetField::Key => "core.source",
                    AssetField::Name => "core.name",
                },
                if more > 0 {
                    format!(" and {more} more")
                } else {
                    String::new()
                }
            ));
        }
        selected.extend(matched);
    }
    let keep = w.closure(selected.iter().copied());
    let gone: Vec<Entity> = w.entities().filter(|e| !keep.contains(e)).collect();
    log.count("assets selected", selected.len() as u64);
    log.count("assets left out", (roots.len() - selected.len()) as u64);
    for e in gone {
        crate::ledger::despawn(w, e, log, "not in a selected asset");
    }
    Ok(())
}

/// `partition-by-asset` (no options): a [`PartitionPlan`] of one part per asset, so a conversion writes each asset
/// on its own (`convert_parts` with `PlannedParts`). Each asset root nothing references is a group of its own, in
/// entity order, keyed by its `core.source` (else its `core.name`, else `asset <index>`), with no context: the part
/// is the asset's closure, and what its passes place from the root (`place-assets` run in the part's passes) is its
/// own. Other independent content (loose placements, and placements a selection made, which reference an asset's
/// parts rather than belong to it: place assets in the part's passes, not the selection) is one more group,
/// `outside assets`, counted, written with what it reaches. An asset another asset references is written with that
/// one.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct PartitionByAsset;

/// `partition-by-asset`'s declaration ([`crate::pass::PassRegistry::add`]): no options.
pub const PARTITION_BY_ASSET: PassSpec = PassSpec {
    name: "partition-by-asset",
    options: &[],
    make: |_| Ok(Box::new(PartitionByAsset)),
};

impl Pass for PartitionByAsset {
    fn name(&self) -> &'static str {
        "partition-by-asset"
    }
    fn requires(&self) -> &[&'static str] {
        &[Asset::NAME]
    }
    fn provides(&self) -> &[&'static str] {
        &[PartitionPlan::NAME]
    }
    fn modifies(&self) -> &[&'static str] {
        &[PartitionPlan::NAME]
    }
    fn run(&self, w: &mut World, log: &mut PassLog) -> Result<(), String> {
        // independent content: what nothing refers to (entities with no component are nothing)
        let names = w.component_names();
        let independent: Vec<Entity> = w
            .unreferenced()
            .into_iter()
            .filter(|&e| names.iter().any(|n| w.entity_has_named(e, n)))
            .collect();
        let (assets, rest): (Vec<Entity>, Vec<Entity>) =
            independent.into_iter().partition(|&e| w.has::<Asset>(e));
        let groups: Vec<PartitionGroup> = assets
            .iter()
            .map(|&root| PartitionGroup {
                key: AssetField::Key
                    .of(w, root)
                    .or_else(|| AssetField::Name.of(w, root))
                    .map_or_else(|| format!("asset {}", root.index()), str::to_owned),
                roots: BTreeSet::from([root]),
                context: BTreeSet::new(),
                area: None,
            })
            .collect();
        let mut groups = groups;
        log.count("assets, each a part", assets.len() as u64);
        if !rest.is_empty() {
            log.count("content outside any asset, in its own part", rest.len() as u64);
            groups.push(PartitionGroup {
                key: "outside assets".into(),
                roots: rest.into_iter().collect(),
                context: BTreeSet::new(),
                area: None,
            });
        }
        // a part is named by its key: two assets of one source or name (or one named as the rest) can't be told apart
        let mut keys = BTreeSet::new();
        if let Some(g) = groups.iter().find(|g| !keys.insert(g.key.as_str())) {
            return Err(format!(
                "two parts would be keyed {:?}: assets share a source or a name (or one is named as the content outside \
                 assets); give them distinct ones",
                g.key
            ));
        }
        w.insert_resource(PartitionPlan {
            by: "partition-by-asset".into(),
            groups,
        });
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::pass::{PassManager, PassRegistry, RunReport};
    use crate::{
        Binding, BindingId, Deformation, Influences, Joint, JointId, Primitive, Rest, Semantic, Slot, Stream,
    };
    use crate::{Topology, WeightRule};

    /// An asset of a skeleton, a skinned prototype, a static prototype and an alternative: (world, root, [skinned,
    /// static, alternative], skeleton).
    fn world() -> (World, Entity, [Entity; 3], Entity) {
        let mut w = World::new();
        let skeleton = w.spawn();
        w.insert(
            skeleton,
            Skeleton {
                joints: vec![Joint {
                    id: JointId(0),
                    name: "root".into(),
                    parent: None,
                    rest: Rest::Affine(Transform::IDENTITY),
                }],
            },
        );
        let mesh = || {
            Mesh::new(vec![Primitive {
                topology: Topology::Points,
                streams: [(Semantic::Position, Stream::F32x3(vec![[0.0; 3]]))].into(),
                indices: None,
                material: None,
            }])
        };
        let parts = [w.spawn(), w.spawn(), w.spawn()];
        for &p in &parts {
            w.insert(p, mesh());
        }
        w.insert(
            parts[0],
            Skin {
                influences: vec![Some(Influences::Whole { slot: 0 })],
                weights: WeightRule::SumsToOne,
                bindings: vec![Binding {
                    id: BindingId(2),
                    skeleton,
                    palettes: vec![Some(vec![Slot {
                        joint: JointId(0),
                        inverse_bind: Transform::IDENTITY,
                    }])],
                    deformation: Deformation::Linear,
                }],
            },
        );
        let root = w.spawn();
        w.insert(
            root,
            Asset {
                members: vec![
                    (skeleton, Role::Rig),
                    (parts[0], Role::Part),
                    (parts[1], Role::Part),
                    (parts[2], Role::Alternative),
                ],
            },
        );
        (w, root, parts, skeleton)
    }

    #[test]
    fn an_asset_reaches_its_members_and_verifies() {
        let (mut w, root, parts, skeleton) = world();
        assert_eq!(w.verify_components(), vec![]);
        assert!(
            w.closure([root])
                .is_superset(&[skeleton, parts[0], parts[1], parts[2]].into())
        );
        w.get_mut::<Asset>(root)
            .unwrap()
            .members
            .push((parts[0], Role::Part));
        assert!(
            w.verify_components()
                .iter()
                .any(|(_, _, m)| m.contains("listed twice"))
        );
        w.get_mut::<Asset>(root).unwrap().members.pop();
        w.get_mut::<Asset>(root).unwrap().members[0].1 = Role::Clip;
        assert!(
            w.verify_components()
                .iter()
                .any(|(_, _, m)| m.contains("not what its role"))
        );
    }

    /// A member still in its source's form (a reader's model before a pass lowers it to a mesh) fits its role; one
    /// holding only core components that are not its role's does not.
    #[test]
    fn a_member_in_its_sources_form_fits_its_role() {
        let (mut w, root, parts, _) = world();
        w.remove::<Mesh>(parts[1]);
        w.insert(parts[1], Name("model".into()));
        assert!(
            w.verify_components()
                .iter()
                .any(|(_, _, m)| m.contains("not what its role Part says"))
        );
        w.insert_opaque(
            parts[1],
            "source.model",
            crate::Opaque {
                version: 1,
                data: crate::OpaqueData::Bytes(vec![1, 2, 3]),
            },
        )
        .unwrap();
        assert_eq!(w.verify_components(), vec![]);
        assert!(w.closure([root]).contains(&parts[1]));
        // in its source's form, but in core another role's: a clip member that is a mesh is no clip
        let clip_member = parts[0];
        w.get_mut::<Asset>(root)
            .unwrap()
            .members
            .iter_mut()
            .find(|(m, _)| *m == clip_member)
            .unwrap()
            .1 = Role::Clip;
        w.insert_opaque(
            clip_member,
            "source.clip",
            crate::Opaque {
                version: 1,
                data: crate::OpaqueData::Bytes(vec![4]),
            },
        )
        .unwrap();
        assert!(
            w.verify_components()
                .iter()
                .any(|(_, _, m)| m.contains("not what its role Clip says")),
            "{:?}",
            w.verify_components()
        );
    }

    fn registry() -> PassManager {
        let mut r = PassRegistry::new();
        crate::register(&mut r);
        PassManager::new(r).with_pass_checks(true)
    }

    /// Two assets (`a`/`A` and `b`/`B`, one part each, both drawn with one material) and a loose placement of `b`'s
    /// part: (world, [root a, part a, root b, part b, material, placement]).
    fn two_assets() -> (World, [Entity; 6]) {
        let mut w = World::new();
        let material = w.spawn();
        w.insert(material, Name("m".into()));
        let mut part = || {
            let p = w.spawn();
            w.insert(
                p,
                Mesh::new(vec![Primitive {
                    topology: Topology::Points,
                    streams: [(Semantic::Position, Stream::F32x3(vec![[0.0; 3]]))].into(),
                    indices: None,
                    material: Some(material),
                }]),
            );
            p
        };
        let (pa, pb) = (part(), part());
        let mut root = |key: &str, name: &str, p: Entity| {
            let r = w.spawn();
            w.insert(r, Source(key.into()));
            w.insert(r, Name(name.into()));
            w.insert(
                r,
                Asset {
                    members: vec![(p, Role::Part)],
                },
            );
            r
        };
        let (ra, rb) = (root("a", "A", pa), root("b", "B", pb));
        let placement = w.spawn();
        w.insert(
            placement,
            Instance {
                prototype: pb,
                variant: 0,
            },
        );
        w.insert(placement, Transform::IDENTITY);
        (w, [ra, pa, rb, pb, material, placement])
    }

    /// Selecting keeps the chosen assets' closure (a material shared with a left-out asset too) and leaves out the
    /// rest, the placement of a left-out part with it; by key or by name.
    #[test]
    fn select_assets_keeps_what_the_chosen_assets_reach() {
        let m = registry();
        for (pipeline, kept) in [
            ("select-assets{keys=a}", [0, 1, 4]),
            ("select-assets{names=B}", [2, 3, 4]),
        ] {
            let (mut w, e) = two_assets();
            let mut report = RunReport::default();
            m.run(&mut w, &m.registry.parse(pipeline).unwrap(), &mut report)
                .unwrap();
            let alive: BTreeSet<Entity> = w.entities().collect();
            assert_eq!(alive, kept.map(|i| e[i]).into(), "{pipeline}");
            assert_eq!(w.verify_components(), vec![], "{pipeline}");
            let log = &report.steps[0].log;
            assert_eq!(
                (log.counts["assets selected"], log.counts["assets left out"]),
                (1, 1)
            );
        }
        // both, and the placement of b's part goes with it
        let (mut w, e) = two_assets();
        let mut report = RunReport::default();
        m.run(
            &mut w,
            &m.registry.parse("select-assets{keys=b;a}").unwrap(),
            &mut report,
        )
        .unwrap();
        assert_eq!(
            w.entities().collect::<BTreeSet<_>>(),
            e[..5].iter().copied().collect()
        );
    }

    #[test]
    fn select_assets_refuses_a_value_no_asset_has_and_bad_options() {
        let m = registry();
        let (mut w, _) = two_assets();
        let err = m
            .run(
                &mut w,
                &m.registry.parse("select-assets{keys=a;c}").unwrap(),
                &mut RunReport::default(),
            )
            .unwrap_err()
            .to_string();
        assert!(
            err.contains("no asset whose core.source is c (the world's: a, b)"),
            "{err}"
        );
        for (bad, why) in [
            ("select-assets", "one of keys or names is required"),
            (
                "select-assets{keys=a,names=A}",
                "only one of keys or names may be given",
            ),
            ("select-assets{keys=a;;b}", "an empty value"),
            ("select-assets{keys=a;a}", "a twice"),
            (
                "select-assets{key=a}",
                "unknown option key (select-assets takes keys, names)",
            ),
        ] {
            let err = m.registry.parse(bad).unwrap_err().to_string();
            assert!(err.contains(why), "{bad}: {err}");
        }
        // printed as parsed
        let p = m.registry.parse("select-assets{names=B;A}").unwrap();
        assert_eq!(p.to_string(), "select-assets{names=B;A}");
    }

    /// One part per asset, keyed by its source (else its name), and the loose placement in a part of its own.
    #[test]
    fn partition_by_asset_plans_a_part_per_asset() {
        let m = registry();
        let (mut w, e) = two_assets();
        w.remove::<Source>(e[2]);
        let mut report = RunReport::default();
        m.run(
            &mut w,
            &m.registry.parse("partition-by-asset").unwrap(),
            &mut report,
        )
        .unwrap();
        let plan = w.resource::<PartitionPlan>().unwrap();
        assert_eq!(plan.by, "partition-by-asset");
        let groups: Vec<(&str, Vec<Entity>)> = plan
            .groups
            .iter()
            .map(|g| (g.key.as_str(), g.roots.iter().copied().collect()))
            .collect();
        assert_eq!(
            groups,
            [
                ("a", vec![e[0]]),
                ("B", vec![e[2]]),
                ("outside assets", vec![e[5]])
            ]
        );
        assert!(
            plan.groups
                .iter()
                .all(|g| g.context.is_empty() && g.area.is_none())
        );
        let log = &report.steps[0].log;
        assert_eq!(log.counts["assets, each a part"], 2);
        assert_eq!(log.counts["content outside any asset, in its own part"], 1);
    }

    /// Two assets keyed alike (the same source) would be two parts of one name: refused, naming the key.
    #[test]
    fn partition_by_asset_refuses_two_parts_of_one_key() {
        let m = registry();
        let (mut w, e) = two_assets();
        w.insert(e[2], Source("a".into()));
        let err = m
            .run(
                &mut w,
                &m.registry.parse("partition-by-asset").unwrap(),
                &mut RunReport::default(),
            )
            .unwrap_err();
        assert!(err.to_string().contains("keyed \"a\""), "{err}");
        assert!(w.resource::<PartitionPlan>().is_none());
    }

    /// Placing: one rig, a placement per part (the skinned one with its skin instance on that rig), the alternative
    /// not placed; a part the source already places is left alone.
    #[test]
    fn place_assets_places_rigs_and_parts() {
        let (mut w, _, parts, skeleton) = world();
        let mut r = PassRegistry::new();
        r.add(&PLACE_ASSETS);
        let m = PassManager::new(r).with_pass_checks(true);
        let mut report = RunReport::default();
        m.run(&mut w, &m.registry.parse("place-assets").unwrap(), &mut report)
            .unwrap();
        let rigs: Vec<_> = w.iter::<RigInstance>().collect();
        assert_eq!(rigs.len(), 1);
        assert_eq!(rigs[0].1.skeleton, skeleton);
        let placed: Vec<Entity> = w.iter::<Instance>().map(|(_, i)| i.prototype).collect();
        assert_eq!(placed, [parts[0], parts[1]]);
        let skinned: Vec<_> = w.iter::<SkinInstance>().collect();
        assert_eq!(skinned.len(), 1);
        assert_eq!(
            (skinned[0].1.rig, skinned[0].1.binding),
            (rigs[0].0, BindingId(2))
        );
        assert_eq!(w.verify_components(), vec![]);
        let log = &report.steps[0].log;
        assert_eq!(
            log.counts["alternative parts not placed (a selection chooses)"],
            1
        );
        assert_eq!(log.placed.len(), 3);
        // placing again: every part already placed
        let mut again = RunReport::default();
        m.run(&mut w, &m.registry.parse("place-assets").unwrap(), &mut again)
            .unwrap();
        assert_eq!(
            again.steps[0].log.counts["parts the source places, left as they are"],
            2
        );
        // nor a rig: the skeleton keeps the one it has
        assert_eq!(w.iter::<RigInstance>().count(), 1);
        assert_eq!(
            again.steps[0].log.counts["rigs already placed, left as they are"],
            1
        );
        assert!(again.steps[0].log.placed.is_empty());
    }
}