oxeon 0.0.5

Rust-like scripting language for modding Bevy games, compiled to sandboxed WebAssembly.
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
use std::time::{Duration, Instant};

use bevy_app::{App, TaskPoolPlugin};
use bevy_asset::{AssetPlugin, AssetServer, Assets, Handle, LoadState};
use bevy_ecs::prelude::*;
use bevy_reflect::Reflect;
use bevy_time::{TimePlugin, TimeUpdateStrategy};
use bevy_transform::components::Transform;
use oxeon::prelude::*;

#[derive(Component, Reflect, Debug)]
#[reflect(Component)]
struct Health(f32);

#[derive(Resource, Reflect, Default, Debug, PartialEq)]
#[reflect(Resource)]
struct Score {
    changed: u32,
    added: u32,
}

#[derive(Message, Reflect, Clone)]
struct Hit {
    damage: f32,
}

#[derive(Message, Reflect, Clone, Debug, PartialEq)]
struct Scored {
    total: u32,
}

#[derive(Component, Reflect)]
#[reflect(Component)]
struct Regen {
    per_sec: f32,
}

/// A headless game where each frame lasts 100 ms.
fn game(assets: &str) -> App {
    let mut app = App::new();
    app.add_plugins((
        TaskPoolPlugin::default(),
        TimePlugin,
        AssetPlugin {
            file_path: assets.into(),
            ..Default::default()
        },
        OxeonPlugin::default(),
    ))
    .expose_to_mods::<Health>()
    .expose_to_mods::<Regen>()
    .expose_to_mods::<Score>()
    .expose_to_mods::<Transform>()
    .init_resource::<Score>()
    .add_message::<Hit>()
    .add_message::<Scored>()
    .expose_message_to_mods::<Hit>()
    .expose_message_to_mods::<Scored>()
    .insert_resource(TimeUpdateStrategy::ManualDuration(Duration::from_millis(
        100,
    )));
    app.finish();
    app.cleanup();
    app
}

fn load(app: &mut App, path: &str) -> Handle<OxeonSource> {
    let handle = app
        .world()
        .resource::<AssetServer>()
        .load::<OxeonSource>(path.to_owned());
    app.world_mut().spawn(OxeonMod(handle.clone()));
    let deadline = Instant::now() + Duration::from_secs(10);
    loop {
        app.update();
        match app.world().resource::<AssetServer>().load_state(&handle) {
            LoadState::Loaded => break,
            LoadState::Failed(err) => panic!("mod failed to load: {err}"),
            _ if Instant::now() > deadline => panic!("timed out loading mod"),
            _ => std::thread::sleep(Duration::from_millis(5)),
        }
    }
    // The frame after loading compiles the mod and runs it once.
    app.update();
    handle
}

fn health(app: &App, entity: Entity) -> f32 {
    app.world()
        .get::<Health>(entity)
        .expect("entity has health")
        .0
}

#[test]
fn loads_example_mod_source() {
    let mut app = game("../../examples");
    let handle = load(&mut app, "mods/regen.ox");
    let sources = app.world().resource::<Assets<OxeonSource>>();
    assert!(
        sources
            .get(&handle)
            .expect("asset is loaded")
            .source
            .contains("fn regen")
    );
}

#[test]
fn mod_systems_change_game_components() {
    let mut app = game("tests");
    let regenerating = app
        .world_mut()
        .spawn((Health(10.0), Regen { per_sec: 2.0 }))
        .id();
    let plain = app.world_mut().spawn(Health(5.0)).id();
    load(&mut app, "mods/regen.ox");

    let before = health(&app, regenerating);
    assert!(before > 10.0, "the mod ran: {before}");
    for frame in 1..=5 {
        app.update();
        let now = health(&app, regenerating);
        let expected = before + 2.0 * 0.1 * frame as f32;
        assert!(
            (now - expected).abs() < 1e-4,
            "frame {frame}: {now}, expected {expected}"
        );
    }
    assert_eq!(
        health(&app, plain),
        5.0,
        "entities without `Regen` aren't matched"
    );
}

#[test]
fn a_mod_that_never_returns_is_disabled() {
    let mut app = game("tests");
    let entity = app.world_mut().spawn(Health(1.0)).id();
    load(&mut app, "mods/spin.ox");
    // The failed call never wrote back, and the game keeps running.
    assert_eq!(health(&app, entity), 1.0);
    for _ in 0..3 {
        app.update();
    }
    assert_eq!(health(&app, entity), 1.0);
}

#[test]
fn a_mod_with_errors_does_not_run() {
    let mut app = game("tests");
    let entity = app.world_mut().spawn(Health(1.0)).id();
    load(&mut app, "mods/broken.ox");
    app.update();
    assert_eq!(health(&app, entity), 1.0);
}

#[test]
fn mods_use_enums_and_match() {
    let mut app = game("tests");
    let weak = app.world_mut().spawn(Health(1.0)).id();
    let strong = app.world_mut().spawn(Health(200.0)).id();
    load(&mut app, "mods/tiers.ox");
    // Low jumps to 5, Mid doubles until High, which leaves it alone below
    // its cap. How many frames ran during loading varies, so check the
    // path rather than exact frames.
    let path = [5.0, 10.0, 20.0, 40.0, 80.0];
    let mut seen = vec![health(&app, weak)];
    for _ in 0..6 {
        app.update();
        seen.push(health(&app, weak));
    }
    assert!(seen.iter().all(|h| path.contains(h)), "{seen:?}");
    assert!(
        seen.windows(2).all(|w| w[1] == w[0] * 2.0 || w[1] == w[0]),
        "{seen:?}"
    );
    assert_eq!(seen.last(), Some(&80.0));
    assert_eq!(health(&app, strong), 100.0, "High caps at 100");
}

#[test]
fn mods_use_option_from_the_prelude() {
    let mut app = game("tests");
    let low = app.world_mut().spawn(Health(3.0)).id();
    let high = app.world_mut().spawn(Health(50.0)).id();
    load(&mut app, "mods/option.ox");
    app.update();
    assert_eq!(health(&app, low), 10.0);
    assert_eq!(health(&app, high), 50.0);
}

#[test]
fn mods_spawn_filter_and_despawn() {
    let mut app = game("tests");
    let doomed = app.world_mut().spawn(Health(4.0)).id();
    let protected = app
        .world_mut()
        .spawn((Health(4.0), Regen { per_sec: 0.0 }))
        .id();
    load(&mut app, "mods/commands.ox");
    for _ in 0..6 {
        app.update();
    }
    // `poison` only touches entities without `Regen`; `reap` despawned the
    // ones it brought to zero, including the mod's own `Health(2.0)`.
    assert!(app.world().get_entity(doomed).is_err(), "despawned");
    assert_eq!(health(&app, protected), 4.0);
    let mut q = app.world_mut().query::<(&Health, Option<&Regen>)>();
    let mut seen: Vec<(f32, Option<f32>)> = q
        .iter(app.world())
        .map(|(h, r)| (h.0, r.map(|r| r.per_sec)))
        .collect();
    seen.sort_by(|a, b| a.partial_cmp(b).unwrap());
    // The test's protected entity, and the two the mod spawned with `Regen`
    // (one through `insert`).
    assert_eq!(seen, [(1.0, Some(5.0)), (3.0, Some(0.0)), (4.0, Some(0.0))]);
}

#[test]
fn mods_use_resources_and_change_filters() {
    let mut app = game("tests");
    let ticking = app
        .world_mut()
        .spawn((Health(1.0), Regen { per_sec: 0.0 }))
        .id();
    app.world_mut().spawn(Health(1.0));
    load(&mut app, "mods/changes.ox");
    let start = app.world().resource::<Score>().changed;
    let added = app.world().resource::<Score>().added;
    assert_eq!(added, 2, "both entities count as added on the first run");
    // Each frame `touch` changes only the entity with `Regen`; the other is
    // left alone, so it doesn't count as changed again.
    for _ in 0..3 {
        app.update();
    }
    assert_eq!(app.world().resource::<Score>().changed, start + 3);
    // A new entity is added (and changed) once.
    app.world_mut().spawn(Health(5.0));
    app.update();
    let score = app.world().resource::<Score>();
    assert_eq!(
        *score,
        Score {
            changed: start + 5,
            added: 3
        }
    );
    // `Res<Score>` was read: the mod copied `added` into `Regen`.
    assert_eq!(app.world().get::<Regen>(ticking).unwrap().per_sec, 3.0);
}

#[test]
fn mods_define_their_own_components() {
    let mut app = game("tests");
    let entity = app.world_mut().spawn(Health(10.0)).id();
    load(&mut app, "mods/poison.ox");
    for _ in 0..6 {
        app.update();
    }
    // Infected once (it then has `Poisoned`, so `Without<Poisoned>` skips
    // it), then three frames of poison.
    assert_eq!(health(&app, entity), 7.0);
    // The mod's component is a real component on the entity (its name,
    // `mods/poison.ox::Poisoned`, needs Bevy's `debug` feature to show).
    assert_eq!(app.world().inspect_entity(entity).unwrap().count(), 2);
}

#[test]
fn writes_the_bindings_file_for_editors() {
    let dir = std::env::temp_dir().join(format!("oxeon-bindings-{}", std::process::id()));
    std::fs::create_dir_all(&dir).unwrap();
    let path = dir.join("oxeon-bindings.ox");
    let mut app = App::new();
    app.add_plugins((
        TaskPoolPlugin::default(),
        TimePlugin,
        AssetPlugin::default(),
        OxeonPlugin {
            bindings_file: Some(path.clone()),
            ..Default::default()
        },
    ))
    .expose_to_mods::<Health>()
    .expose_to_mods::<Regen>();
    app.finish();
    let text = std::fs::read_to_string(&path).expect("written");
    assert!(text.contains("pub struct Health(pub f32);"), "{text}");
    assert!(
        text.contains("pub struct Regen {\n    pub per_sec: f32,\n}"),
        "{text}"
    );
    // Only the game's types (editors add Bevy's), and valid Oxeon.
    assert!(!text.contains("struct Commands"), "{text}");
    assert!(oxeon_compiler::compile(&text).is_ok(), "{text}");
    std::fs::remove_dir_all(&dir).ok();
}

#[test]
fn mods_use_components_whose_fields_are_structs() {
    let mut app = game("tests");
    let rust_side = app
        .world_mut()
        .spawn(Transform::from_xyz(5.0, 0.0, 0.0))
        .id();
    load(&mut app, "mods/moves.ox");
    for _ in 0..3 {
        app.update();
    }
    let mut q = app.world_mut().query::<(Entity, &Transform)>();
    let all: Vec<(Entity, Transform)> = q.iter(app.world()).map(|(e, t)| (e, *t)).collect();
    assert_eq!(all.len(), 2, "the game's entity and the mod's");
    let (_, game_t) = all.iter().find(|(e, _)| *e == rust_side).unwrap();
    // `drift` ran in each update after loading, 100 ms each: +1 per frame.
    assert!(game_t.translation.x > 5.5, "{game_t:?}");
    assert_eq!((game_t.translation.y, game_t.scale.y), (0.0, 2.0));
    let (_, mod_t) = all.iter().find(|(e, _)| *e != rust_side).unwrap();
    assert_eq!((mod_t.translation.y, mod_t.translation.z), (2.0, 3.0));
    assert_eq!(mod_t.scale.y, 2.0);
    // `rotate_z(0.5)` once a frame (including the first, whose time delta
    // is 0), the same as Bevy's to float precision.
    let angle = 2.0 * game_t.rotation.z.atan2(game_t.rotation.w);
    let frames = (angle / 0.5).round() as usize;
    assert!(frames >= 2, "{angle}");
    let mut expected = Transform::IDENTITY;
    for _ in 0..frames {
        expected.rotate_z(0.5);
    }
    assert!(
        game_t.rotation.abs_diff_eq(expected.rotation, 1e-6),
        "{:?} vs {:?}",
        game_t.rotation,
        expected.rotation
    );
}

#[test]
fn transform_bindings_declare_its_field_types() {
    let app = game("tests");
    let bindings = app.world().resource::<oxeon::OxeonBindings>();
    let text = &bindings.declarations;
    assert!(text.contains("#[derive(Clone, Copy, Debug)]\npub struct Transform {\n    pub translation: Vec3,\n    pub rotation: Quat,\n    pub scale: Vec3,\n}"), "{text}");
    assert!(
        text.contains("pub fn rotate_z(&mut self, angle: f32)"),
        "{text}"
    );
    // `Vec3` and `Quat` are Bevy's math types, in the prelude with their
    // methods: not declared again.
    assert!(!text.contains("pub struct Vec3"), "{text}");
    assert!(bindings.prelude.contains("pub struct Vec3"));
}

#[test]
fn mods_read_and_send_messages() {
    let mut app = game("tests");
    let target = app.world_mut().spawn(Health(5.0)).id();
    load(&mut app, "mods/messages.ox");
    assert_eq!(health(&app, target), 5.0, "no hits yet");

    app.world_mut().write_message(Hit { damage: 2.0 });
    app.update();
    assert_eq!(health(&app, target), 3.0, "each hit is read once");
    app.update();
    assert_eq!(health(&app, target), 3.0);

    // A killing hit: the mod's own `Killed` message reaches its `score`
    // system, which reports back with the game's `Scored`.
    app.world_mut().write_message(Hit { damage: 4.0 });
    app.update();
    assert_eq!(health(&app, target), -1.0);
    assert_eq!(app.world().resource::<Score>().added, 10);
    let scored: Vec<Scored> = app
        .world_mut()
        .resource_mut::<Messages<Scored>>()
        .drain()
        .collect();
    assert_eq!(scored, [Scored { total: 10 }]);
}

#[test]
fn each_call_gets_a_fresh_heap() {
    let mut app = game("tests");
    app.world_mut().spawn(Health(3.0));
    app.world_mut().spawn(Health(42.0));
    load(&mut app, "mods/lists.ox");
    let before = app.world().resource::<Score>().added;
    // ~1 MiB per frame: 100 frames would pass the 64 MiB limit if the heap
    // weren't reset between calls (and a heap over the host's data would
    // garble the score).
    for _ in 0..100 {
        app.update();
    }
    let score = app.world().resource::<Score>();
    assert_eq!(score.changed, 42 + 100000);
    assert_eq!(score.added, before + 100, "the mod ran every frame");
}

/// Runs frames until the game reports on a mod (a source sent in one frame
/// is compiled in the next), and returns the reports.
fn next_reports(app: &mut App) -> Vec<ModReport> {
    for _ in 0..5 {
        app.update();
        let reports: Vec<ModReport> = app
            .world_mut()
            .resource_mut::<bevy_ecs::message::Messages<ModReport>>()
            .drain()
            .collect();
        if !reports.is_empty() {
            return reports;
        }
    }
    panic!("no report after 5 frames");
}

fn load_source(app: &mut App, source: &str) {
    app.world_mut().write_message(LoadModSource {
        name: "playground/heal.ox".to_owned(),
        source: source.to_owned(),
    });
}

/// Mods given as text (as a playground's editor does): loaded, replaced,
/// kept when the new text doesn't compile, disabled when they fail, and
/// unloaded, each with a report.
#[test]
fn mods_load_from_source_text_and_report() {
    let mut app = game("tests");
    let e = app.world_mut().spawn(Health(0.0)).id();
    let healing = |amount: &str| {
        format!(
            "fn heal(mut q: Query<&mut Health>) {{ for mut h in &mut q {{ h.0 += {amount}; }} }}\n\
             pub fn plugin(app: &mut App) {{ app.add_systems(Update, heal); }}"
        )
    };
    load_source(&mut app, &healing("1.0"));
    assert_eq!(
        next_reports(&mut app),
        [ModReport::Loaded {
            name: "playground/heal.ox".to_owned(),
            systems: vec!["heal".to_owned()],
        }]
    );
    let after_load = health(&app, e);
    app.update();
    assert_eq!(health(&app, e), after_load + 1.0);

    // A new version replaces it.
    load_source(&mut app, &healing("100.0"));
    assert!(matches!(
        &next_reports(&mut app)[..],
        [ModReport::Loaded { .. }]
    ));
    let replaced = health(&app, e);
    app.update();
    assert_eq!(health(&app, e), replaced + 100.0);

    // One that doesn't compile: the previous version keeps running.
    load_source(
        &mut app,
        "fn heal(q: Query<&mut Health>) { let x: u32 = 1.5; }",
    );
    match &next_reports(&mut app)[..] {
        [
            ModReport::CompileFailed {
                name,
                errors,
                kept_previous,
            },
        ] => {
            assert_eq!(name, "playground/heal.ox");
            assert!(errors[0].contains("mismatched types"), "{errors:?}");
            assert!(kept_previous);
        }
        other => panic!("{other:?}"),
    }
    let kept = health(&app, e);
    app.update();
    assert_eq!(health(&app, e), kept + 100.0);

    // One that runs forever: disabled, with the reason.
    load_source(
        &mut app,
        "fn heal(mut q: Query<&mut Health>) { loop {} }\n\
         pub fn plugin(app: &mut App) { app.add_systems(Update, heal); }",
    );
    let mut seen = next_reports(&mut app);
    if !seen.iter().any(|r| matches!(r, ModReport::Disabled { .. })) {
        seen.extend(next_reports(&mut app));
    }
    assert!(
        seen.iter()
            .any(|r| matches!(r, ModReport::Disabled { system, error, .. }
            if system == "heal" && error.contains("fuel"))),
        "{seen:?}"
    );

    // Unloaded: nothing runs any more.
    load_source(&mut app, &healing("1.0"));
    next_reports(&mut app);
    app.world_mut().write_message(UnloadMod {
        name: "playground/heal.ox".to_owned(),
    });
    for _ in 0..3 {
        app.update();
    }
    let unloaded = health(&app, e);
    app.update();
    app.update();
    assert_eq!(health(&app, e), unloaded);
}

fn drain_logs(app: &mut App) -> Vec<(LogLevel, String)> {
    app.world_mut()
        .resource_mut::<bevy_ecs::message::Messages<ModLog>>()
        .drain()
        .map(|l| (l.level, l.text))
        .collect()
}

/// `info!`, `println!` and the rest reach the game as `ModLog`s, filled in
/// on the host; what a failing system logged before failing too.
#[test]
fn mods_log_messages() {
    let mut app = game("tests");
    app.world_mut().spawn(Health(2.5));
    app.world_mut()
        .spawn((Health(7.0), Transform::from_xyz(1.0, 2.0, 3.0)));
    load_source(
        &mut app,
        r#"
        #[derive(Debug, Clone, Copy)]
        struct Pair { a: u8, b: (bool, char) }

        fn report(q: Query<&Health>, t: Query<&Transform>) {
            let n = 3;
            for h in &q {
                info!("health {:.1}, {h:?}", h.0);
            }
            for t in &t {
                warn!("at {} / {:?}", t.translation, t.translation);
            }
            let p = Pair { a: 7, b: (true, 'x') };
            println!("{p:?} {n:>4} {:#x} {:+.2e}", 255u32, 1500.0f64);
            debug!("{:#?}", p);
            error!("{{literal}} {0} {0}", n);
            if n == 3 {
                panic!("stop");
            }
        }
        pub fn plugin(app: &mut App) { app.add_systems(Update, report); }
        "#,
    );
    let reports = next_reports(&mut app);
    assert!(
        matches!(
            &reports[..],
            [ModReport::Loaded { .. }, ModReport::Disabled { .. }]
        ),
        "{reports:?}"
    );
    let mut logs = drain_logs(&mut app);
    logs.sort_by_key(|(level, _)| *level as u8);
    assert_eq!(
        logs,
        [
            (
                LogLevel::Debug,
                "Pair {\n    a: 7,\n    b: (\n        true,\n        'x',\n    ),\n}".to_owned()
            ),
            (LogLevel::Info, "health 2.5, Health(2.5)".to_owned()),
            (LogLevel::Info, "health 7.0, Health(7.0)".to_owned()),
            (
                LogLevel::Warn,
                "at [1, 2, 3] / Vec3(1.0, 2.0, 3.0)".to_owned()
            ),
            (LogLevel::Error, "{literal} 3 3".to_owned()),
            (
                LogLevel::Print,
                "Pair { a: 7, b: (true, 'x') }    3 0xff +1.50e3".to_owned()
            ),
        ]
    );
}

/// Entities print as Bevy prints them, including ones the system spawned.
#[test]
fn mods_log_entities_like_bevy() {
    let mut app = game("tests");
    app.world_mut().spawn_empty();
    let e = app.world_mut().spawn(Regen { per_sec: 1.0 }).id();
    load_source(
        &mut app,
        r#"
        fn report(mut commands: Commands, q: Query<(Entity, &Regen)>) {
            for (e, _) in &q {
                info!("{e:?} {:>6}|", e);
                let new = commands.spawn(Health(1.0)).id();
                info!("spawned {new}");
            }
        }
        pub fn plugin(app: &mut App) { app.add_systems(Startup, report); }
        "#,
    );
    next_reports(&mut app);
    let logs = drain_logs(&mut app);
    let spawned = app
        .world_mut()
        .query_filtered::<Entity, With<Health>>()
        .single(app.world())
        .unwrap();
    assert_eq!(
        logs,
        [
            (LogLevel::Info, format!("{e:?} {e:>6}|")),
            (LogLevel::Info, format!("spawned {spawned}")),
        ]
    );
}

/// A mod's own resources: added in `plugin` with `init_resource` (zeros)
/// or `insert_resource`, used with `Res`/`ResMut`, kept across a reload
/// when `init_resource` adds them, and removed with the mod.
#[test]
fn mods_define_their_own_resources() {
    let mut app = game("tests");
    let mod_source = |extra: &str| {
        format!(
            r#"
            #[derive(Resource, Default)]
            struct Counter {{ ticks: u32, total: f32 }}

            #[derive(Resource)]
            struct Settings {{ step: f32, on: bool }}

            fn count(mut c: ResMut<Counter>, s: Res<Settings>) {{
                if s.on {{
                    c.ticks += 1;
                    c.total += s.step;
                }}
                info!("{{}} {{}}", c.ticks, c.total);
            }}

            pub fn plugin(app: &mut App) {{
                app.init_resource::<Counter>()
                    .insert_resource(Settings {{ step: {extra}, on: true }})
                    .add_systems(Update, count);
            }}
            "#
        )
    };
    load_source(&mut app, &mod_source("0.5"));
    let reports = next_reports(&mut app);
    assert!(
        matches!(&reports[..], [ModReport::Loaded { .. }]),
        "{reports:?}"
    );
    drain_logs(&mut app);
    app.update();
    app.update();
    let logs = drain_logs(&mut app);
    let last = &logs.last().expect("it logged").1;
    assert!(last.ends_with(" 1.5") && last.starts_with("3 "), "{logs:?}");

    // A reload keeps the counter (`init_resource`) and replaces the
    // settings (`insert_resource`).
    load_source(&mut app, &mod_source("10.0"));
    next_reports(&mut app);
    let logs = drain_logs(&mut app);
    assert_eq!(logs.last().map(|l| l.1.as_str()), Some("5 12"), "{logs:?}");

    // Removing the mod removes its resources.
    app.world_mut().write_message(UnloadMod {
        name: "playground/heal.ox".to_owned(),
    });
    for _ in 0..3 {
        app.update();
    }
    let left = app
        .world_mut()
        .query::<bevy_ecs::world::EntityRef>()
        .iter(app.world())
        .filter(|e| {
            e.archetype().components().iter().any(|c| {
                app.world()
                    .components()
                    .get_name(*c)
                    .is_some_and(|n| n.ends_with("(resource)"))
            })
        })
        .count();
    assert_eq!(left, 0);
}

#[test]
fn mod_resources_must_be_added_first() {
    let mut app = game("tests");
    load_source(
        &mut app,
        r#"
        #[derive(Resource)]
        struct Lost { n: u32 }
        fn use_it(l: Res<Lost>) {}
        pub fn plugin(app: &mut App) { app.add_systems(Update, use_it); }
        "#,
    );
    let reports = next_reports(&mut app);
    match &reports[..] {
        [ModReport::Loaded { .. }, ModReport::Disabled { error, .. }] => {
            assert!(error.contains("app.init_resource::<Lost>()"), "{error}")
        }
        r => panic!("{r:?}"),
    }
}

#[test]
fn mod_resources_need_their_derives() {
    let mut app = game("tests");
    load_source(
        &mut app,
        r#"
        struct Plain { n: u32 }
        #[derive(Resource)]
        struct NoDefault { n: u32 }
        pub fn plugin(app: &mut App) {
            app.insert_resource(Plain { n: 1 }).init_resource::<NoDefault>();
        }
        "#,
    );
    match &next_reports(&mut app)[..] {
        [ModReport::CompileFailed { errors, .. }] => {
            let text = errors.join("\n");
            assert!(text.contains("`Plain` isn't a resource"), "{text}");
            assert!(
                text.contains("`NoDefault` doesn't implement `Default`"),
                "{text}"
            );
        }
        r => panic!("{r:?}"),
    }
}

/// `rand::random` and friends: in range, and the same for the same seed.
#[test]
fn mods_get_random_numbers() {
    let rolls = |seed: u64| {
        let mut app = App::new();
        app.add_plugins((
            TaskPoolPlugin::default(),
            TimePlugin,
            AssetPlugin::default(),
            OxeonPlugin {
                runtime: oxeon_runtime::RuntimeConfig {
                    random_seed: Some(seed),
                    ..Default::default()
                },
                ..Default::default()
            },
        ));
        app.finish();
        app.cleanup();
        load_source(
            &mut app,
            r#"
            fn roll() {
                let d: u8 = rand::random_range(1..=6);
                let x = rand::random_range(-2.0..2.0f32);
                let unit: f64 = rand::random();
                let big: u64 = rand::random();
                println!("{d} {x} {unit} {big} {}", rand::random_bool(0.5));
            }
            pub fn plugin(app: &mut App) { app.add_systems(Update, roll); }
            "#,
        );
        // Every line from the first roll on, however many frames loading
        // takes: the same seed gives the same lines.
        let mut lines = Vec::new();
        for _ in 0..100 {
            app.update();
            lines.extend(drain_logs(&mut app).into_iter().map(|(_, text)| text));
            if lines.len() >= 12 {
                break;
            }
        }
        lines.truncate(12);
        lines
    };
    let a = rolls(1);
    assert_eq!(a.len(), 12, "{a:?}");
    for line in &a {
        let parts: Vec<&str> = line.split(' ').collect();
        let d: u8 = parts[0].parse().unwrap();
        let x: f32 = parts[1].parse().unwrap();
        let unit: f64 = parts[2].parse().unwrap();
        assert!((1..=6).contains(&d) && (-2.0..2.0).contains(&x) && (0.0..1.0).contains(&unit));
    }
    assert_eq!(a, rolls(1), "the same seed gives the same numbers");
    assert_ne!(a, rolls(2));
}