bevy_replique 0.3.0

Bevy plugin for Replique, a pure rust dialogue manager
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
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
//! Answering the `has` of a dialogue.
//!
//! Asked of a name rather than of a dictionary, `has` is a question about the
//! game: `[if Alice has Angry]` asks whether the entity the dialogue calls
//! `Alice` holds the component it calls `Angry`. Both names have to be given
//! to the plugin, since neither means anything to Bevy.
//!
//! **A subject is an entity with a name.** [`RepliqueSubject`] is the
//! component that gives it one:
//!
//! ```
//! # use bevy::prelude::*;
//! # use bevy_replique::prelude::*;
//! # let mut world = World::new();
//! world.spawn(RepliqueSubject::new("Alice"));
//! ```
//!
//! **A feature is a component with a name.**
//! [`register_replique_feature`](DialogueFeatureAppExt::register_replique_feature)
//! gives it one:
//!
//! ```
//! # use bevy::prelude::*;
//! # use bevy_replique::prelude::*;
//! #[derive(Component)]
//! struct Angry;
//!
//! # let mut app = App::new();
//! app.register_replique_feature::<Angry>("Angry");
//! ```
//!
//! From there `Alice has Angry` is `true` exactly while that entity holds an
//! `Angry`. Only the presence of the component is looked at.
//!
//! A name the plugin was never given is a mistake in the dialogue, not a
//! `false`. An unknown subject or an unknown feature stops the dialogue with
//! an error, so that a typo does not quietly send it down the `[else]`.
//!
//! # The value of a feature
//!
//! A feature registered with
//! [`register_replique_feature_value`](DialogueFeatureAppExt::register_replique_feature_value)
//! can also be read: `Alice.Mana` is the component of the entity `Alice`, as
//! [`IntoValue`] writes it.
//!
//! ```
//! # use bevy::prelude::*;
//! # use bevy_replique::prelude::*;
//! #[derive(Component, Clone, RepliqueValue)]
//! struct Mana(f64);
//!
//! # let mut app = App::new();
//! // `[if Alice has Mana and Alice.Mana > 10.0]`
//! app.register_replique_feature_value::<Mana>("Mana");
//! ```
//!
//! Reading a feature its subject does not hold stops the dialogue with an
//! error, so ask with `has` first. So does reading one that was registered
//! without a value.
//!
//! # The same name in two dialogues
//!
//! A subject is visible to every dialogue unless it says otherwise. One that
//! is [`only_for`](RepliqueSubject::only_for) some runners is seen by those
//! alone, which lets two dialogues running side by side each have their own
//! `Guard`:
//!
//! ```
//! # use bevy::prelude::*;
//! # use bevy_replique::prelude::*;
//! # let mut world = World::new();
//! # let (north_gate, south_gate) = (world.spawn_empty().id(), world.spawn_empty().id());
//! world.spawn(RepliqueSubject::new("Guard").only_for(north_gate));
//! world.spawn(RepliqueSubject::new("Guard").only_for(south_gate));
//! ```
//!
//! A subject scoped to the runner that is asking comes before one visible to
//! all, so a dialogue can also stand in its own `Alice` for the usual one.
//! Two subjects of the same name left at the same level are ambiguous, and
//! asking about them is an error.

use std::sync::Arc;

use bevy::{
    app::App,
    ecs::{
        component::{Component, ComponentId},
        entity::{Entity, MapEntities},
        lifecycle::Remove,
        observer::On,
        resource::Resource,
        system::Query,
        world::{EntityRef, World},
    },
    log::warn,
    platform::collections::HashMap,
};
use replique::{dialogue::Value, host::HostError};

use crate::{call::args::IntoValue, runner::DialogueRunner};

/// The name a dialogue knows an entity by.
///
/// `Alice` in `[if Alice has Angry]` is the entity holding
/// `RepliqueSubject::new("Alice")`. The name is the one the dialogue writes,
/// case included.
///
/// An entity has one name. See the [module](self) for how the same name can
/// stand for different entities in different dialogues.
#[derive(Component, Clone, Debug, PartialEq, Eq)]
pub struct RepliqueSubject {
    name: String,
    #[entities]
    scope: SubjectScope,
}

impl RepliqueSubject {
    /// A subject every dialogue can see.
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            scope: SubjectScope::All,
        }
    }

    /// Restricts the subject to the dialogue of `runner`. Called again, it
    /// adds a runner to those that already see it.
    pub fn only_for(mut self, runner: Entity) -> Self {
        self.show_to(runner);
        self
    }

    /// Same as [`only_for`](Self::only_for), on a subject already spawned.
    pub fn show_to(&mut self, runner: Entity) {
        match &mut self.scope {
            SubjectScope::All => self.scope = SubjectScope::Only(vec![runner]),
            SubjectScope::Only(runners) => {
                if !runners.contains(&runner) {
                    runners.push(runner);
                }
            }
        }
    }

    /// Takes the subject away from the dialogue of `runner`.
    ///
    /// Only a scoped subject can be hidden: one visible to all stays so. A
    /// subject hidden from its last runner is visible to none, and does not
    /// go back to being visible to all.
    pub fn hide_from(&mut self, runner: Entity) {
        if let SubjectScope::Only(runners) = &mut self.scope {
            runners.retain(|seen_by| *seen_by != runner);
        }
    }

    pub fn name(&self) -> &str {
        &self.name
    }

    pub fn scope(&self) -> &SubjectScope {
        &self.scope
    }
}

/// Visibility of a [`RepliqueSubject`] to the existing [`DialogueRunner`].
#[derive(MapEntities, Clone, Debug, PartialEq, Eq)]
pub enum SubjectScope {
    /// Visible to all runners.
    All,
    /// Visible only to this runners.
    Only(#[entities] Vec<Entity>),
}

/// Reads the value of a feature off an entity, `None` when the entity does not hold it.
type FeatureReader = Arc<dyn Fn(EntityRef) -> Option<Value> + Send + Sync>;

/// Indentify a feature in the World
#[derive(Clone)]
pub(crate) struct Feature {
    id: ComponentId,
    /// `None` for a feature registered without a value.
    read: Option<FeatureReader>,
}

impl Feature {
    fn component_id(&self) -> ComponentId {
        self.id
    }
}

/// The components a dialogue can query.
#[derive(Resource, Default)]
pub(crate) struct DialogueFeatureRegistry {
    features: HashMap<String, Feature>,
}

/// Registers features on an [`App`].
pub trait DialogueFeatureAppExt {
    /// Lets dialogues ask whether a subject holds the component `C`, under
    /// `name`: after `register_replique_feature::<Angry>("Angry")`,
    /// `Alice has Angry` is `true` while the entity named `Alice` holds `Angry`.
    ///
    /// The name is the one the dialogue writes, case included, and does not
    /// have to be the name of the type. A name registered twice keeps the last
    /// component it was given.
    ///
    /// ```
    /// # use bevy::prelude::*;
    /// # use bevy_replique::prelude::*;
    /// #[derive(Component)]
    /// struct Mana(f32);
    ///
    /// # let mut app = App::new();
    /// // `[if Alice has magic]`
    /// app.register_replique_feature::<Mana>("magic");
    /// ```
    fn register_replique_feature<C: Component>(&mut self, name: impl Into<String>) -> &mut Self;

    /// Same as [`register_replique_feature`](Self::register_replique_feature),
    /// for a component dialogues can also read the value: `Alice.Mana` is the
    /// component of the entity named `Alice`, as [`IntoValue`] writes it.
    ///
    /// ```
    /// # use bevy::prelude::*;
    /// # use bevy_replique::prelude::*;
    /// #[derive(Component, Clone, RepliqueValue)]
    /// struct Mana(f64);
    ///
    /// # let mut app = App::new();
    /// // `[if Alice has Mana and Alice.Mana > 10.0]`
    /// app.register_replique_feature_value::<Mana>("Mana");
    /// ```
    ///
    /// Reading the feature of a subject that does not hold it is an error:
    /// `has` is how a dialogue asks first.
    fn register_replique_feature_value<C>(&mut self, name: impl Into<String>) -> &mut Self
    where
        C: Component + Clone + IntoValue;
}

impl DialogueFeatureAppExt for App {
    fn register_replique_feature<C: Component>(&mut self, name: impl Into<String>) -> &mut Self {
        register::<C>(self, name.into(), None);
        self
    }

    fn register_replique_feature_value<C>(&mut self, name: impl Into<String>) -> &mut Self
    where
        C: Component + Clone + IntoValue,
    {
        let read: FeatureReader =
            Arc::new(|entity: EntityRef| entity.get::<C>().cloned().map(IntoValue::into_value));

        register::<C>(self, name.into(), Some(read));
        self
    }
}

/// Puts the component `C` in the registry under `name`, with what reads its
/// value when it has one.
fn register<C: Component>(app: &mut App, name: String, read: Option<FeatureReader>) {
    let world = app.world_mut();
    let id = world.register_component::<C>();

    let mut registry = world.get_resource_or_init::<DialogueFeatureRegistry>();
    if let Some(previous) = registry.features.insert(name.clone(), Feature { id, read })
        && previous.component_id() != id
    {
        warn!("The feature {name} was already registered for another component.");
    }
}

/// Whether the entity `runner` knows as `subject` holds the component registered as `feature`.
pub(crate) fn has_feature(
    world: &mut World,
    runner: Entity,
    subject: &str,
    feature: &str,
) -> Result<bool, HostError> {
    let id = world
        .get_resource::<DialogueFeatureRegistry>()
        .and_then(|registry| registry.features.get(feature).cloned())
        .ok_or_else(|| HostError::UnknownFeature(feature.to_owned()))?;

    let entity = resolve_subject(world, runner, subject)?;

    Ok(world.entity(entity).contains_id(id.component_id()))
}

/// The value of the component registered as `feature`, on the entity `runner`
/// knows as `subject`.
pub(crate) fn feature(
    world: &mut World,
    runner: Entity,
    subject: &str,
    feature: &str,
) -> Result<Value, HostError> {
    let registered = world
        .get_resource::<DialogueFeatureRegistry>()
        .and_then(|registry| registry.features.get(feature).cloned())
        .ok_or_else(|| HostError::UnknownFeature(feature.to_owned()))?;

    let entity = resolve_subject(world, runner, subject)?;

    let read = registered.read.ok_or_else(|| HostError::Failed {
        name: feature.to_owned(),
        message: "this feature was registered without a value to read".to_owned(),
    })?;

    read(world.entity(entity)).ok_or_else(|| HostError::FeatureNotOnSubject {
        feature: feature.to_owned(),
        subject: subject.to_owned(),
    })
}

/// The entity `runner` knows as `name`.
///
/// The subjects scoped to `runner` are looked at first, then the ones visible
/// to all. A level holding several of them is an error rather than a pick: the
/// order a query walks entities in is not something a dialogue should depend
/// on.
fn resolve_subject(world: &mut World, runner: Entity, name: &str) -> Result<Entity, HostError> {
    let mut scoped = vec![];
    let mut global = vec![];

    let mut subjects = world.query::<(Entity, &RepliqueSubject)>();
    for (entity, subject) in subjects.iter(world) {
        if subject.name != name {
            continue;
        }

        match &subject.scope {
            SubjectScope::All => global.push(entity),
            SubjectScope::Only(runners) if runners.contains(&runner) => scoped.push(entity),
            SubjectScope::Only(_) => {}
        }
    }

    let candidates = if scoped.is_empty() { global } else { scoped };

    match candidates.as_slice() {
        [] => Err(HostError::UnknownSubject(name.to_owned())),
        [entity] => Ok(*entity),
        several => Err(HostError::Failed {
            name: name.to_owned(),
            message: format!(
                "{} subjects of that name are visible to this dialogue",
                several.len()
            ),
        }),
    }
}

/// Takes a runner that is going away out of the scope of every subject.
///
/// A subject left with no runner stays scoped, and so visible to none: turning
/// it into one visible to all would hand a dialogue an `Alice` that was meant
/// for another.
pub(crate) fn forget_runner(
    removed: On<Remove<DialogueRunner>>,
    mut subjects: Query<&mut RepliqueSubject>,
) {
    let runner = removed.entity;

    for mut subject in &mut subjects {
        let listed = matches!(
            &subject.scope,
            SubjectScope::Only(runners) if runners.contains(&runner)
        );

        // Checked first so that only the subjects that change are marked as changed.
        if listed {
            subject.hide_from(runner);
        }
    }
}

#[cfg(test)]
mod tests {
    use bevy::{
        MinimalPlugins,
        asset::{AssetPlugin, Assets, Handle},
        ecs::{entity::EntityHashMap, message::Messages},
    };
    use replique::{RepliqueFile, parser::diagnostic::Color};

    use super::*;
    use crate::{
        asset::RepliqueDialogue,
        message::{DialogueLine, StartDialogue},
        plugin::RepliquePlugin,
    };

    #[derive(Component)]
    struct Angry;

    #[derive(Component)]
    struct Mana(#[allow(unused)] f32);

    /// A feature with a value to read.
    #[derive(Component, Clone)]
    struct Gold(i64);

    impl IntoValue for Gold {
        fn into_value(self) -> Value {
            Value::Int(self.0)
        }
    }

    fn app() -> App {
        let mut app = App::new();
        app.add_plugins((MinimalPlugins, AssetPlugin::default(), RepliquePlugin));
        app.register_replique_feature::<Angry>("Angry")
            .register_replique_feature::<Mana>("Mana")
            .register_replique_feature_value::<Gold>("Gold");
        app
    }

    /// An entity standing for a runner: resolving a subject only needs its id.
    fn runner(app: &mut App) -> Entity {
        app.world_mut().spawn_empty().id()
    }

    /// What `has` answered, in a shape that compares: [`HostError`] does not.
    #[derive(Debug, PartialEq)]
    enum Answer {
        Yes,
        No,
        UnknownSubject(String),
        UnknownFeature(String),
        Ambiguous(String),
    }

    fn has(app: &mut App, runner: Entity, subject: &str, feature: &str) -> Answer {
        match has_feature(app.world_mut(), runner, subject, feature) {
            Ok(true) => Answer::Yes,
            Ok(false) => Answer::No,
            Err(HostError::UnknownSubject(name)) => Answer::UnknownSubject(name),
            Err(HostError::UnknownFeature(name)) => Answer::UnknownFeature(name),
            Err(HostError::Failed { name, .. }) => Answer::Ambiguous(name),
            Err(other) => panic!("unexpected error: {other}"),
        }
    }

    fn scope_of(app: &App, subject: Entity) -> SubjectScope {
        app.world()
            .get::<RepliqueSubject>(subject)
            .expect("a subject")
            .scope()
            .clone()
    }

    #[test]
    fn a_subject_has_the_features_it_holds() {
        let mut app = app();
        let runner = runner(&mut app);
        app.world_mut()
            .spawn((RepliqueSubject::new("Alice"), Angry));
        app.world_mut().spawn(RepliqueSubject::new("Bob"));

        assert_eq!(has(&mut app, runner, "Alice", "Angry"), Answer::Yes);
        assert_eq!(has(&mut app, runner, "Alice", "Mana"), Answer::No);
        assert_eq!(has(&mut app, runner, "Bob", "Angry"), Answer::No);
    }

    #[test]
    fn a_feature_is_there_whatever_it_holds() {
        let mut app = app();
        let runner = runner(&mut app);
        app.world_mut()
            .spawn((RepliqueSubject::new("Alice"), Mana(0.0)));

        assert_eq!(has(&mut app, runner, "Alice", "Mana"), Answer::Yes);
    }

    #[test]
    fn a_feature_with_a_value_gives_what_its_component_holds() {
        let mut app = app();
        let runner = runner(&mut app);
        let alice = app
            .world_mut()
            .spawn((RepliqueSubject::new("Alice"), Gold(12)))
            .id();

        assert_eq!(has(&mut app, runner, "Alice", "Gold"), Answer::Yes);
        assert_eq!(
            feature(app.world_mut(), runner, "Alice", "Gold").unwrap(),
            Value::Int(12)
        );

        // Read off the world each time, so it follows the component.
        app.world_mut().entity_mut(alice).insert(Gold(3));
        assert_eq!(
            feature(app.world_mut(), runner, "Alice", "Gold").unwrap(),
            Value::Int(3)
        );
    }

    #[test]
    fn error_on_a_value_that_cannot_be_read() {
        let mut app = app();
        let runner = runner(&mut app);
        app.world_mut()
            .spawn((RepliqueSubject::new("Alice"), Angry));

        // The subject does not hold it.
        assert!(matches!(
            feature(app.world_mut(), runner, "Alice", "Gold"),
            Err(HostError::FeatureNotOnSubject { feature, subject })
                if feature == "Gold" && subject == "Alice"
        ));
        // Registered without a value, held or not.
        assert!(matches!(
            feature(app.world_mut(), runner, "Alice", "Angry"),
            Err(HostError::Failed { name, .. }) if name == "Angry"
        ));
        assert!(matches!(
            feature(app.world_mut(), runner, "Alice", "Sleepy"),
            Err(HostError::UnknownFeature(name)) if name == "Sleepy"
        ));
        assert!(matches!(
            feature(app.world_mut(), runner, "Bob", "Gold"),
            Err(HostError::UnknownSubject(name)) if name == "Bob"
        ));
    }

    #[test]
    fn a_feature_follows_the_component_as_it_comes_and_goes() {
        let mut app = app();
        let runner = runner(&mut app);
        let alice = app.world_mut().spawn(RepliqueSubject::new("Alice")).id();

        assert_eq!(has(&mut app, runner, "Alice", "Angry"), Answer::No);

        app.world_mut().entity_mut(alice).insert(Angry);
        assert_eq!(has(&mut app, runner, "Alice", "Angry"), Answer::Yes);

        app.world_mut().entity_mut(alice).remove::<Angry>();
        assert_eq!(has(&mut app, runner, "Alice", "Angry"), Answer::No);
    }

    #[test]
    fn a_feature_is_known_by_the_name_it_was_registered_under() {
        let mut app = app();
        app.register_replique_feature::<Angry>("furious");
        let runner = runner(&mut app);
        app.world_mut()
            .spawn((RepliqueSubject::new("Alice"), Angry));

        assert_eq!(has(&mut app, runner, "Alice", "furious"), Answer::Yes);
        assert_eq!(
            has(&mut app, runner, "Alice", "angry"),
            Answer::UnknownFeature("angry".into())
        );
    }

    #[test]
    fn a_name_registered_twice_keeps_the_last_component() {
        let mut app = app();
        app.register_replique_feature::<Mana>("Angry");
        let runner = runner(&mut app);
        app.world_mut()
            .spawn((RepliqueSubject::new("Alice"), Angry));

        assert_eq!(has(&mut app, runner, "Alice", "Angry"), Answer::No);
    }

    #[test]
    fn error_on_a_feature_that_was_never_registered() {
        let mut app = app();
        let runner = runner(&mut app);
        app.world_mut().spawn(RepliqueSubject::new("Alice"));

        assert_eq!(
            has(&mut app, runner, "Alice", "Sleepy"),
            Answer::UnknownFeature("Sleepy".into())
        );
    }

    #[test]
    fn error_on_a_subject_no_entity_is_named_after() {
        let mut app = app();
        let runner = runner(&mut app);
        app.world_mut().spawn(RepliqueSubject::new("Alice"));

        assert_eq!(
            has(&mut app, runner, "alice", "Angry"),
            Answer::UnknownSubject("alice".into())
        );
    }

    #[test]
    fn a_subject_that_was_despawned_is_unknown() {
        let mut app = app();
        let runner = runner(&mut app);
        let alice = app.world_mut().spawn(RepliqueSubject::new("Alice")).id();

        app.world_mut().despawn(alice);

        assert_eq!(
            has(&mut app, runner, "Alice", "Angry"),
            Answer::UnknownSubject("Alice".into())
        );
    }

    #[test]
    fn a_scoped_subject_is_seen_by_its_runners_only() {
        let mut app = app();
        let (north, south, east) = (runner(&mut app), runner(&mut app), runner(&mut app));
        app.world_mut().spawn((
            RepliqueSubject::new("Guard")
                .only_for(north)
                .only_for(south),
            Angry,
        ));

        assert_eq!(has(&mut app, north, "Guard", "Angry"), Answer::Yes);
        assert_eq!(has(&mut app, south, "Guard", "Angry"), Answer::Yes);
        assert_eq!(
            has(&mut app, east, "Guard", "Angry"),
            Answer::UnknownSubject("Guard".into())
        );
    }

    #[test]
    fn two_runners_can_each_have_their_own_subject_of_the_same_name() {
        let mut app = app();
        let (north, south) = (runner(&mut app), runner(&mut app));
        app.world_mut()
            .spawn((RepliqueSubject::new("Guard").only_for(north), Angry));
        app.world_mut()
            .spawn(RepliqueSubject::new("Guard").only_for(south));

        assert_eq!(has(&mut app, north, "Guard", "Angry"), Answer::Yes);
        assert_eq!(has(&mut app, south, "Guard", "Angry"), Answer::No);
    }

    #[test]
    fn a_scoped_subject_comes_before_the_one_visible_to_all() {
        let mut app = app();
        let (north, south) = (runner(&mut app), runner(&mut app));
        app.world_mut().spawn(RepliqueSubject::new("Alice"));
        app.world_mut()
            .spawn((RepliqueSubject::new("Alice").only_for(north), Angry));

        assert_eq!(has(&mut app, north, "Alice", "Angry"), Answer::Yes);
        assert_eq!(has(&mut app, south, "Alice", "Angry"), Answer::No);
    }

    #[test]
    fn error_on_two_subjects_of_the_same_name_at_the_same_level() {
        let mut app = app();
        let north = runner(&mut app);
        app.world_mut().spawn(RepliqueSubject::new("Alice"));
        app.world_mut().spawn(RepliqueSubject::new("Alice"));
        app.world_mut()
            .spawn(RepliqueSubject::new("Guard").only_for(north));
        app.world_mut()
            .spawn(RepliqueSubject::new("Guard").only_for(north));

        for name in ["Alice", "Guard"] {
            assert_eq!(
                has(&mut app, north, name, "Angry"),
                Answer::Ambiguous(name.into())
            );
        }
    }

    /// The feature is checked first, so that the error names the word that is
    /// wrong whichever subject it was asked of.
    #[test]
    fn an_unknown_feature_is_reported_before_an_unknown_subject() {
        let mut app = app();
        let runner = runner(&mut app);

        assert_eq!(
            has(&mut app, runner, "Nobody", "Sleepy"),
            Answer::UnknownFeature("Sleepy".into())
        );
    }

    #[test]
    fn show_to_and_hide_from_edit_the_scope() {
        let mut world = World::new();
        let (north, south) = (world.spawn_empty().id(), world.spawn_empty().id());
        let mut subject = RepliqueSubject::new("Guard");
        assert_eq!(subject.scope(), &SubjectScope::All);

        subject.hide_from(north);
        assert_eq!(subject.scope(), &SubjectScope::All);

        subject.show_to(north);
        subject.show_to(north);
        subject.show_to(south);
        assert_eq!(subject.scope(), &SubjectScope::Only(vec![north, south]));

        subject.hide_from(north);
        subject.hide_from(south);
        assert_eq!(subject.scope(), &SubjectScope::Only(vec![]));
    }

    #[test]
    fn a_runner_that_is_despawned_leaves_the_scope_of_its_subjects() {
        let mut app = app();
        let (north, south) = {
            let world = app.world_mut();
            (
                world.spawn(DialogueRunner::new(Handle::default())).id(),
                world.spawn(DialogueRunner::new(Handle::default())).id(),
            )
        };
        let guard = app
            .world_mut()
            .spawn(
                RepliqueSubject::new("Guard")
                    .only_for(north)
                    .only_for(south),
            )
            .id();
        let alice = app.world_mut().spawn(RepliqueSubject::new("Alice")).id();

        app.world_mut().despawn(north);

        assert_eq!(scope_of(&app, guard), SubjectScope::Only(vec![south]));
        assert_eq!(scope_of(&app, alice), SubjectScope::All);
    }

    #[test]
    fn a_subject_left_with_no_runner_is_visible_to_none() {
        let mut app = app();
        let north = app
            .world_mut()
            .spawn(DialogueRunner::new(Handle::default()))
            .id();
        let south = runner(&mut app);
        let guard = app
            .world_mut()
            .spawn(RepliqueSubject::new("Guard").only_for(north))
            .id();

        app.world_mut().entity_mut(north).remove::<DialogueRunner>();

        assert_eq!(scope_of(&app, guard), SubjectScope::Only(vec![]));
        assert_eq!(
            has(&mut app, south, "Guard", "Angry"),
            Answer::UnknownSubject("Guard".into())
        );
    }

    #[test]
    fn the_runners_of_a_scope_are_remapped_with_the_entities() {
        let mut world = World::new();
        let (old, new) = (world.spawn_empty().id(), world.spawn_empty().id());
        let mut map = EntityHashMap::from_iter([(old, new)]);
        let mut subject = RepliqueSubject::new("Guard").only_for(old);

        <RepliqueSubject as Component>::map_entities(&mut subject, &mut map);

        assert_eq!(subject.scope(), &SubjectScope::Only(vec![new]));
    }

    /// A dialogue asset built from source, without going through the loader.
    fn add_dialogue(app: &mut App, src: &str) -> Handle<RepliqueDialogue> {
        let file = RepliqueFile::from_source(src);
        assert!(
            !file.has_errors(),
            "{}",
            file.render_diagnostics(Color::Never)
        );

        app.world_mut()
            .resource_mut::<Assets<RepliqueDialogue>>()
            .add(RepliqueDialogue::new(file.dialogue.expect("a dialogue")))
    }

    /// Starts `dialogue` on a new runner and gives the lines of that frame.
    fn first_lines(app: &mut App, dialogue: Handle<RepliqueDialogue>) -> Vec<String> {
        let runner = app.world_mut().spawn(DialogueRunner::new(dialogue)).id();
        start(app, runner)
    }

    fn start(app: &mut App, runner: Entity) -> Vec<String> {
        app.world_mut().write_message(StartDialogue {
            runner,
            node: "start".into(),
        });
        app.update();

        app.world()
            .resource::<Messages<DialogueLine>>()
            .iter_current_update_messages()
            .filter(|line| line.token.runner() == runner)
            .map(|line| line.text.clone())
            .collect()
    }

    const MOOD: &str = ":= start
[if Alice has Angry]
    Alice: Furieuse.
[else]
    Alice: Calme.
---
";

    #[test]
    fn a_dialogue_branches_on_the_components_of_a_subject() {
        let mut app = app();
        let dialogue = add_dialogue(&mut app, MOOD);
        let alice = app.world_mut().spawn(RepliqueSubject::new("Alice")).id();

        assert_eq!(first_lines(&mut app, dialogue.clone()), ["Calme."]);

        app.world_mut().entity_mut(alice).insert(Angry);
        assert_eq!(first_lines(&mut app, dialogue), ["Furieuse."]);
    }

    #[test]
    fn a_dialogue_reads_the_value_of_a_feature() {
        let mut app = app();
        let dialogue = add_dialogue(
            &mut app,
            ":= start
[if Alice has Gold and Alice.Gold >= 10]
    Alice: Riche de [Alice.Gold] pièces.
[else]
    Alice: Pauvre.
---
",
        );
        let alice = app.world_mut().spawn(RepliqueSubject::new("Alice")).id();

        // Without the component, the `and` stops before the value is read.
        assert_eq!(first_lines(&mut app, dialogue.clone()), ["Pauvre."]);

        app.world_mut().entity_mut(alice).insert(Gold(3));
        assert_eq!(first_lines(&mut app, dialogue.clone()), ["Pauvre."]);

        app.world_mut().entity_mut(alice).insert(Gold(12));
        assert_eq!(first_lines(&mut app, dialogue), ["Riche de 12 pièces."]);
    }

    #[test]
    fn a_dialogue_reads_the_subject_scoped_to_its_own_runner() {
        let mut app = app();
        let dialogue = add_dialogue(&mut app, MOOD);
        let (north, south) = {
            let world = app.world_mut();
            (
                world.spawn(DialogueRunner::new(dialogue.clone())).id(),
                world.spawn(DialogueRunner::new(dialogue)).id(),
            )
        };
        app.world_mut()
            .spawn((RepliqueSubject::new("Alice").only_for(north), Angry));
        app.world_mut()
            .spawn(RepliqueSubject::new("Alice").only_for(south));

        assert_eq!(start(&mut app, north), ["Furieuse."]);
        assert_eq!(start(&mut app, south), ["Calme."]);
    }

    /// The error is logged and the dialogue goes nowhere: neither branch is
    /// played on a name the game does not know.
    #[test]
    fn a_dialogue_stops_on_a_subject_it_cannot_find() {
        let mut app = app();
        let dialogue = add_dialogue(&mut app, MOOD);

        assert!(first_lines(&mut app, dialogue).is_empty());
    }
}