ponko 0.0.1

A fast 2D game engine for simulating millions of things: ECS on all cores, hot reload, an in-game inspector, AI-agent control, and a C++ API.
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
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
//! [`Game`]: window creation and the main loop.

use std::time::Duration;
use web_time::Instant;

use glam::Vec2;

use ponko_ecs::World;

#[cfg(feature = "window")]
mod window;

use crate::control::{self, Control};
use crate::ctx::{Ctx, SystemTiming};
use crate::ecs::draw_sprites;
use crate::sheet::animate_sprites;
use crate::spatial::rebuild_spatial_grid;
use crate::tilemap::draw_tilemaps;
use crate::time::{Clock, DEFAULT_FIXED_HZ, FrameTiming};

/// Trackpads report scrolling in pixels; this many logical pixels count as one
/// wheel "notch" so `mouse_wheel()` means roughly the same on every device.
const PIXELS_PER_SCROLL_LINE: f32 = 20.0;

/// How often to check whether a hidden/minimized window is visible again.
const OCCLUDED_POLL: Duration = Duration::from_millis(100);

/// A game: a window plus the loop that drives your code.
///
/// ```no_run
/// use ponko::*;
///
/// Game::new("My Game", 800, 600).run(|ctx| {
///     // Setup: runs once, after the window exists.
///     let crab = ctx.load_texture("crab.png");
///     let mut pos = vec2(400.0, 300.0);
///
///     // Returned closure: runs every frame.
///     move |ctx: &mut Ctx| {
///         if ctx.key_down(Key::Right) { pos.x += 200.0 * ctx.dt(); }
///         if ctx.key_pressed(Key::Escape) { ctx.quit(); }
///         ctx.draw(&crab, pos);
///     }
/// });
/// ```
///
/// With the ECS, the game is entities plus systems:
///
/// ```no_run
/// use ponko::*;
///
/// struct Vel(Vec2);
///
/// fn movement(ctx: &mut Ctx) {
///     let dt = ctx.dt();
///     ctx.world.query::<(&mut Transform2D, &Vel)>().for_each(|(t, v)| t.position += v.0 * dt);
/// }
///
/// Game::new("Crabs", 800, 600).sim_system(movement).run(|ctx| {
///     let crab = ctx.load_texture("crab.png");
///     ctx.world.spawn((Transform2D::at(vec2(100.0, 100.0)), Sprite::new(crab), Vel(vec2(50.0, 0.0))));
/// });
/// ```
#[must_use = "a Game does nothing until `.run()` or `.run_headless()`"]
pub struct Game {
    title: String,
    width: u32,
    height: u32,
    fixed_hz: u32,
    /// `fixed_hz` was called: `physics3d` keeps that rate.
    fixed_hz_set: bool,
    seed: u64,
    vsync: bool,
    /// Samples per pixel of the 3D frame (see `msaa`).
    msaa: u32,
    fullscreen: bool,
    sim_systems: Vec<System>,
    systems: Vec<System>,
    late_systems: Vec<System>,
    /// Built-in drawing; runs after every other system so it sees final positions.
    draw_systems: Vec<System>,
    /// Cell size from `spatial_grid`, applied to `ctx.spatial` when the game starts.
    spatial_cell: Option<f32>,
    /// Gravity from `physics`, applied to `ctx.physics` when the game starts.
    #[cfg(feature = "physics")]
    gravity: Option<Vec2>,
    /// Gravity from `physics3d`, applied to `ctx.physics3d` when the game starts.
    #[cfg(feature = "physics3d")]
    gravity3d: Option<crate::Vec3>,
    /// The lockstep session from `lockstep`, moved into `ctx.net` at start.
    net: Option<crate::Net>,
    /// Open the control endpoint (also on with `CRABBY_CONTROL=1`).
    control: bool,
    /// Reload asset and data files when they change (`CRABBY_HOT_RELOAD` overrides).
    hot_reload: bool,
    inspector: bool,
}

type SystemFn = Box<dyn FnMut(&mut Ctx)>;

/// A system: a named function that runs over the world.
struct System {
    name: &'static str,
    run: SystemFn,
    /// Simulation systems only: run on ticks where `tick % every == phase`.
    every: u32,
    phase: u32,
    /// Unique per system: its read position for events.
    id: u32,
}

/// Ids for [`System::id`]; 0 means "outside any system".
fn next_system_id() -> u32 {
    use std::sync::atomic::{AtomicU32, Ordering};
    static NEXT: AtomicU32 = AtomicU32::new(1);
    NEXT.fetch_add(1, Ordering::Relaxed)
}

/// This frame's timing: the clock at the current sim speed (0 while
/// paused), plus any single steps requested with `ctx.step()`.
fn frame_timing(clock: &mut Clock, ctx: &mut Ctx, frame_dt: f64) -> FrameTiming {
    let mut timing = clock.advance(frame_dt, ctx.effective_sim_speed());
    timing.fixed_steps += ctx.take_pending_steps();
    timing
}

fn end_timings(ctx: &mut Ctx) {
    for t in &mut ctx.timings {
        t.avg_ms += (t.last_ms - t.avg_ms) * 0.05;
    }
}

/// Runs one system, applies its commands, and records how long both took.
#[inline]
fn run_one(s: &mut System, ctx: &mut Ctx, timing_index: usize) {
    #[cfg(feature = "profiling")]
    puffin::profile_scope!("system", s.name);
    let allocs_before = ctx.perf.on.then(crate::alloc_counts);
    let start = Instant::now();
    ctx.system_index = timing_index;
    ctx.events.reader = s.id;
    (s.run)(ctx);
    ctx.events.reader = 0;
    ctx.apply_commands();
    ctx.timings[timing_index].last_ms += start.elapsed().as_secs_f32() * 1000.0;
    if let Some(before) = allocs_before {
        let made = crate::alloc_counts().count.saturating_sub(before.count);
        ctx.perf.add_system_allocs(timing_index, made);
    }
}

impl System {
    fn new<F: FnMut(&mut Ctx) + 'static>(f: F) -> Self {
        System {
            name: std::any::type_name::<F>(),
            run: hot(f),
            every: 1,
            phase: 0,
            id: next_system_id(),
        }
    }
}

/// Boxes system `f`. With the `hotpatch` feature, each call goes through
/// subsecond's jump table, so a patched version of the system (and of what
/// it calls) runs from the next call on.
#[cfg(not(feature = "hotpatch"))]
fn hot<F: FnMut(&mut Ctx) + 'static>(f: F) -> SystemFn {
    Box::new(f)
}

#[cfg(feature = "hotpatch")]
fn hot<F: FnMut(&mut Ctx) + 'static>(mut f: F) -> SystemFn {
    /// Calls the system. A zero-sized function item, instantiated in the
    /// game's crate, so subsecond finds its patched version in the jump
    /// table (a pointer-sized `&mut F` would be taken for a fn pointer).
    fn call<F: FnMut(&mut Ctx)>(f: &mut F, ctx: &mut Ctx) {
        f(ctx);
    }
    Box::new(move |ctx: &mut Ctx| {
        // A patch that changed code "above" this system (in its caller)
        // can't run in place; skip this call, the next one is current.
        let _ = subsecond::HotFn::current(call::<F>).try_call((&mut f, ctx));
    })
}

/// With the `hotpatch` feature: connects to `dx serve --hotpatch` (when the
/// game was started by it) so patches are applied as they arrive.
fn connect_hotpatch() {
    #[cfg(feature = "hotpatch")]
    {
        static ONCE: std::sync::Once = std::sync::Once::new();
        ONCE.call_once(|| {
            // stdout: `dx` shows stderr lines as errors.
            subsecond::register_handler(std::sync::Arc::new(|| println!("ponko: code patched")));
            dioxus_devtools::connect_subsecond();
        });
    }
}

/// What `setup` may return: nothing, or a closure to run every frame.
///
/// Implemented for `()` and for every `FnMut(&mut Ctx)`.
pub trait SetupResult {
    #[doc(hidden)]
    fn into_frame_fn(self) -> Option<SystemFn>;
}

impl SetupResult for () {
    fn into_frame_fn(self) -> Option<SystemFn> {
        None
    }
}

impl<F: FnMut(&mut Ctx) + 'static> SetupResult for F {
    fn into_frame_fn(self) -> Option<SystemFn> {
        Some(Box::new(self))
    }
}

impl Game {
    /// Describes a game window with a title and size in (logical) pixels.
    ///
    /// Nothing opens until you call [`run`](Self::run).
    ///
    /// ```no_run
    /// # use ponko::*;
    /// Game::new("Space Crab", 1280, 720).run(|_| |_: &mut Ctx| {});
    /// ```
    pub fn new(title: impl Into<String>, width: u32, height: u32) -> Self {
        Self {
            title: title.into(),
            width,
            height,
            fixed_hz: DEFAULT_FIXED_HZ,
            fixed_hz_set: false,
            seed: crate::random::DEFAULT_SEED,
            vsync: true,
            msaa: 4,
            fullscreen: false,
            sim_systems: Vec::new(),
            systems: Vec::new(),
            late_systems: Vec::new(),
            draw_systems: vec![
                System::new(animate_sprites),
                System::new(draw_tilemaps),
                System::new(draw_sprites),
            ],
            spatial_cell: None,
            #[cfg(feature = "physics")]
            gravity: None,
            #[cfg(feature = "physics3d")]
            gravity3d: None,
            net: None,
            control: control::env_flag(control::ENV_CONTROL),
            hot_reload: cfg!(debug_assertions),
            inspector: cfg!(debug_assertions),
        }
    }

    /// Plays over the network in deterministic lockstep: `net` from
    /// [`Net::host`](crate::Net::host), [`Net::join`](crate::Net::join) or
    /// [`Net::loopback`](crate::Net::loopback). Ticks then run only once
    /// every player's input for them is in, and the setup and simulation
    /// systems must be deterministic (same seed, no wall clock, no frame
    /// systems changing the world). Without it, `ctx.net` is offline.
    ///
    /// ```
    /// use ponko::*;
    /// use std::thread;
    ///
    /// // Two players in one process; over the network it's Net::host / Net::join.
    /// let games: Vec<_> = Net::loopback(2)
    ///     .into_iter()
    ///     .map(|net| thread::spawn(move || {
    ///         let world = Game::new("t", 1, 1).lockstep(net).run_headless(30, |_| {});
    ///         world.len()
    ///     }))
    ///     .collect();
    /// for g in games {
    ///     assert_eq!(g.join().unwrap(), 0);
    /// }
    /// ```
    pub fn lockstep(mut self, net: crate::Net) -> Self {
        self.net = Some(net);
        self
    }

    /// Adds a per-frame system after automatic animation and before drawing.
    /// Runs in registration order, with frame dt and ordinary system timings.
    /// Like frame systems, it does not run in `run_headless`.
    ///
    /// ```no_run
    /// use ponko::*;
    /// Game::new("Pose", 800, 600).late_system(|ctx| { let _ = ctx.dt(); }).run(|_| {});
    /// ```
    pub fn late_system<F: FnMut(&mut Ctx) + 'static>(mut self, system: F) -> Self {
        self.late_systems.push(System::new(system));
        self
    }

    /// Adds a simulation system: it runs at the fixed rate
    /// ([`fixed_hz`](Self::fixed_hz), default 60 per second), zero or more
    /// times per frame, and `ctx.dt()` inside it is the fixed step.
    /// Put game logic here so it behaves the same at any frame rate.
    ///
    /// Systems run in the order they were added.
    ///
    /// ```no_run
    /// # use ponko::*;
    /// fn gravity(ctx: &mut Ctx) { /* ... */ }
    /// fn movement(ctx: &mut Ctx) { /* ... */ }
    ///
    /// Game::new("Sim", 800, 600).sim_system(gravity).sim_system(movement).run(|_| {});
    /// ```
    pub fn sim_system<F: FnMut(&mut Ctx) + 'static>(mut self, system: F) -> Self {
        self.sim_systems.push(System::new(system));
        self
    }

    /// Adds a simulation system that runs only every `ticks`-th tick, for
    /// work that doesn't need the full rate: AI that thinks a few times a
    /// second, slow growth, pathfinding, statistics. Inside it, `ctx.dt()`
    /// is `ticks` fixed steps, so rates stay right.
    ///
    /// Systems added with the same interval are spread over different ticks,
    /// so their cost doesn't land on the same frame.
    ///
    /// ```
    /// use ponko::*;
    ///
    /// struct Hunger(f32);
    ///
    /// fn get_hungry(ctx: &mut Ctx) {
    ///     let dt = ctx.dt(); // 10 ticks' worth of time
    ///     ctx.world.query::<&mut Hunger>().for_each(|h| h.0 += 1.0 * dt);
    /// }
    ///
    /// // 60 ticks at 60 Hz: runs 6 times, 1/6 s each.
    /// let mut world = Game::new("t", 1, 1)
    ///     .sim_system_every(10, get_hungry)
    ///     .run_headless(60, |ctx| { ctx.world.spawn((Hunger(0.0),)); });
    /// let h = world.query::<&Hunger>().iter().next().unwrap().0;
    /// assert!((h - 1.0).abs() < 1e-4);
    /// ```
    ///
    /// # Panics
    /// If `ticks` is 0.
    #[track_caller]
    pub fn sim_system_every<F: FnMut(&mut Ctx) + 'static>(self, ticks: u32, system: F) -> Self {
        assert!(
            ticks > 0,
            "Game::sim_system_every: the interval must be at least 1 tick"
        );
        self.push_sim_system(System::new(system), ticks)
    }

    fn push_sim_system(mut self, mut s: System, ticks: u32) -> Self {
        let same = self.sim_systems.iter().filter(|s| s.every == ticks).count() as u32;
        s.every = ticks;
        s.phase = same % ticks;
        self.sim_systems.push(s);
        self
    }

    /// For language bindings (the C API): `sim_system_every` with a name for
    /// timings and tools, since all foreign systems share one Rust type.
    #[doc(hidden)]
    #[track_caller]
    pub fn named_sim_system(self, name: &'static str, ticks: u32, system: impl FnMut(&mut Ctx) + 'static) -> Self {
        assert!(
            ticks > 0,
            "Game::named_sim_system: the interval must be at least 1 tick"
        );
        let mut s = System::new(system);
        s.name = name;
        self.push_sim_system(s, ticks)
    }

    /// For language bindings (the C API): `late_system` with a name.
    #[doc(hidden)]
    pub fn named_late_system(mut self, name: &'static str, system: impl FnMut(&mut Ctx) + 'static) -> Self {
        let mut s = System::new(system);
        s.name = name;
        self.late_systems.push(s);
        self
    }

    /// For language bindings (the C API): `system` with a name.
    #[doc(hidden)]
    pub fn named_system(mut self, name: &'static str, system: impl FnMut(&mut Ctx) + 'static) -> Self {
        let mut s = System::new(system);
        s.name = name;
        self.systems.push(s);
        self
    }

    /// For language bindings (the C API): removes every system named `name`
    /// (Rust systems are named by their path, e.g. `ponko::ecs::draw_sprites`).
    /// Returns how many were removed.
    #[doc(hidden)]
    pub fn remove_named_system(&mut self, name: &str) -> usize {
        let before = self.sim_systems.len() + self.systems.len() + self.late_systems.len() + self.draw_systems.len();
        self.sim_systems.retain(|s| s.name != name);
        self.systems.retain(|s| s.name != name);
        self.late_systems.retain(|s| s.name != name);
        self.draw_systems.retain(|s| s.name != name);
        before - (self.sim_systems.len() + self.systems.len() + self.late_systems.len() + self.draw_systems.len())
    }

    /// Turns on 2D physics (feature `physics`): every entity with a
    /// [`RigidBody`](crate::RigidBody), a [`Collider`](crate::Collider) and a
    /// [`Transform2D`](crate::Transform2D) is simulated each tick, pulled by
    /// `gravity` (pixels/s²; y is down). Collisions arrive as
    /// [`CollisionStarted`](crate::CollisionStarted) events; `ctx.physics`
    /// casts rays and finds overlaps.
    ///
    /// The step is the built-in [`step_physics`](crate::step_physics) sim
    /// system, removable or reorderable like any other. It runs after the
    /// systems added before this call.
    ///
    /// ```
    /// use ponko::*;
    /// let mut world = Game::new("Drop", 800, 600)
    ///     .physics(vec2(0.0, 980.0))
    ///     .run_headless(60, |ctx| {
    ///         ctx.world.spawn((Transform2D::at(vec2(0.0, 0.0)), RigidBody::dynamic(), Collider::circle(8.0)));
    ///     });
    /// // One second of free fall: about 490 pixels down.
    /// let y = world.query::<&Transform2D>().iter().next().unwrap().position.y;
    /// assert!((y - 490.0).abs() < 10.0, "{y}");
    /// ```
    #[cfg(feature = "physics")]
    pub fn physics(mut self, gravity: Vec2) -> Self {
        self.gravity = Some(gravity);
        let name = std::any::type_name_of_val(&crate::step_physics);
        if !self.sim_systems.iter().any(|s| s.name == name) {
            self.sim_systems.push(System::new(crate::step_physics));
        }
        self
    }

    /// Turns on 3D physics (feature `physics3d`): every entity with a
    /// [`RigidBody3D`](crate::RigidBody3D), a [`Collider3D`](crate::Collider3D)
    /// and a [`Transform3D`](crate::Transform3D) is simulated each tick, and
    /// every [`Character3D`](crate::Character3D) walks, pulled by `gravity`
    /// (m/s²; +Y is up, so `vec3(0.0, -9.81, 0.0)`). Collisions arrive as
    /// [`CollisionStarted`](crate::CollisionStarted) events; `ctx.physics3d`
    /// casts rays and shapes and finds overlaps.
    ///
    /// The simulation runs at [`PHYSICS3D_HZ`](crate::PHYSICS3D_HZ) (50)
    /// ticks per second unless [`fixed_hz`](Self::fixed_hz) chose a rate;
    /// in a window, moving bodies are drawn blended between ticks
    /// ([`interpolate_physics3d`](crate::interpolate_physics3d), the first
    /// frame system). The step is the built-in
    /// [`step_physics3d`](crate::step_physics3d) sim system, removable or
    /// reorderable like any other. It runs after the systems added before
    /// this call.
    ///
    /// ```
    /// use ponko::*;
    /// let mut world = Game::new("Drop", 800, 600)
    ///     .physics3d(vec3(0.0, -9.81, 0.0))
    ///     .run_headless(50, |ctx| {
    ///         ctx.world.spawn((Transform3D::at(vec3(0.0, 10.0, 0.0)), RigidBody3D::dynamic(), Collider3D::sphere(0.5)));
    ///     });
    /// // One second of free fall: about 4.9 m down.
    /// let y = world.query::<&Transform3D>().iter().next().unwrap().position.y;
    /// assert!((y - 5.1).abs() < 0.2, "{y}");
    /// ```
    #[cfg(feature = "physics3d")]
    pub fn physics3d(mut self, gravity: crate::Vec3) -> Self {
        self.gravity3d = Some(gravity);
        if !self.fixed_hz_set {
            self.fixed_hz = crate::PHYSICS3D_HZ;
        }
        let name = std::any::type_name_of_val(&crate::step_physics3d);
        if !self.sim_systems.iter().any(|s| s.name == name) {
            self.sim_systems.push(System::new(crate::step_physics3d));
        }
        let name = std::any::type_name_of_val(&crate::interpolate_physics3d);
        if !self.systems.iter().any(|s| s.name == name) {
            self.systems.insert(0, System::new(crate::interpolate_physics3d));
        }
        self
    }

    /// Turns on the built-in [`SpatialGrid`](crate::SpatialGrid) with square
    /// cells of `cell_size` world units: at the start of every simulation
    /// tick, all entities with a [`Transform2D`](crate::Transform2D) are
    /// indexed into `ctx.spatial` for radius, rectangle and nearest queries.
    ///
    /// Choose a cell size near your usual query radius. The rebuild is the
    /// built-in [`rebuild_spatial_grid`] system, removable like any other.
    ///
    /// # Panics
    /// If `cell_size` isn't a positive, finite number.
    #[track_caller]
    pub fn spatial_grid(mut self, cell_size: f32) -> Self {
        self.spatial_cell = Some(crate::SpatialGrid::new(cell_size).cell_size());
        let name = std::any::type_name_of_val(&rebuild_spatial_grid);
        if !self.sim_systems.iter().any(|s| s.name == name) {
            self.sim_systems.insert(0, System::new(rebuild_spatial_grid));
        }
        self
    }

    /// Adds a frame system: it runs once per rendered frame, after the
    /// simulation systems. Use it for input, camera and drawing.
    ///
    /// ```no_run
    /// # use ponko::*;
    /// fn quit_on_escape(ctx: &mut Ctx) {
    ///     if ctx.key_pressed(Key::Escape) { ctx.quit(); }
    /// }
    ///
    /// Game::new("Sim", 800, 600).system(quit_on_escape).run(|_| {});
    /// ```
    pub fn system<F: FnMut(&mut Ctx) + 'static>(mut self, system: F) -> Self {
        self.systems.push(System::new(system));
        self
    }

    /// Removes a system that was added before, including the built-in
    /// [`draw_sprites`]. Pass the same function you added.
    ///
    /// # Panics
    /// If no such system was added.
    ///
    /// ```no_run
    /// # use ponko::*;
    /// // A headless-style simulation that draws nothing by itself.
    /// Game::new("Sim", 800, 600).remove_system(draw_sprites).run(|_| {});
    /// ```
    #[track_caller]
    pub fn remove_system<F: FnMut(&mut Ctx) + 'static>(mut self, system: F) -> Self {
        drop(system);
        let name = std::any::type_name::<F>();
        let count = |g: &Game| g.sim_systems.len() + g.systems.len() + g.late_systems.len() + g.draw_systems.len();
        let before = count(&self);
        self.sim_systems.retain(|s| s.name != name);
        self.systems.retain(|s| s.name != name);
        self.late_systems.retain(|s| s.name != name);
        self.draw_systems.retain(|s| s.name != name);
        assert_ne!(
            before,
            count(&self),
            "Game::remove_system: no system `{name}` was added"
        );
        self
    }

    /// Opens the control endpoint, so tools such as the `ponko-mcp` agent
    /// bridge can inspect and drive this game while it runs: list and edit
    /// entities (through [reflection](crate::WorldReflect)), pause, step,
    /// change speed, read system timings.
    ///
    /// It listens on `127.0.0.1` only, and every request must carry a random
    /// token written to the instance registry (`~/.crabby/instances`),
    /// which only your user can read. Off by default; setting the
    /// environment variable `CRABBY_CONTROL=1` turns it on without code
    /// changes, and `CRABBY_START_PAUSED=1` starts the simulation paused.
    ///
    /// ```no_run
    /// # use ponko::*;
    /// Game::new("Colony", 1280, 720).control_endpoint(true).run(|_| {});
    /// ```
    pub fn control_endpoint(mut self, on: bool) -> Self {
        self.control = on;
        self
    }

    /// Reload textures, fonts, sounds and data files ([`Ctx::load_resource`])
    /// from `assets/` when their files change, under the same handles: save an
    /// image or a JSON file in your editor and the running game shows it
    /// within a quarter of a second. On by default in debug builds, off in
    /// release builds; `CRABBY_HOT_RELOAD=1` or `0` overrides both.
    ///
    /// A file is checked a few times a second (one `stat` per loaded
    /// texture). An image that changed size isn't reloaded (sprites store
    /// their texture's size): restart the game for that.
    /// [`Ctx::reloaded_textures`] lists what was reloaded this frame.
    ///
    /// ```no_run
    /// # use ponko::*;
    /// Game::new("Art test", 1280, 720).hot_reload(true).run(|ctx| {
    ///     let crab = ctx.load_texture("crab.png"); // edit crab.png while it runs
    ///     ctx.world.spawn((Transform2D::at(vec2(640.0, 360.0)), Sprite::new(crab)));
    /// });
    /// ```
    pub fn hot_reload(mut self, on: bool) -> Self {
        self.hot_reload = on;
        self
    }

    /// Turns the runtime inspector on or off: an overlay that the backquote
    /// key (`` ` ``, left of 1) opens and closes,
    /// showing every entity and its components (reflected ones editable),
    /// reflected resources, system times, and pause / step / speed controls.
    /// Its "Pick" button selects the unit you click next.
    ///
    /// On by default in debug builds, off in release builds. The
    /// environment variable `CRABBY_INSPECTOR=1` (or `0`) overrides this, and
    /// `CRABBY_INSPECTOR=open` also starts the game with it open.
    /// Needs the `inspector` cargo feature (on by default); without it, this
    /// does nothing. While closed it costs nothing.
    ///
    /// ```no_run
    /// # use ponko::*;
    /// // Ship a release build with the inspector, for playtesters.
    /// Game::new("Playtest", 1280, 720).inspector(true).run(|ctx| {
    ///     let _ = ctx;
    /// });
    /// ```
    pub fn inspector(mut self, on: bool) -> Self {
        self.inspector = on;
        self
    }

    /// Starts the control endpoint if it's enabled, and applies `CRABBY_START_PAUSED`.
    fn start_control(&self, ctx: &mut Ctx, headless: bool) -> Option<Control> {
        if control::env_flag(control::ENV_START_PAUSED) {
            ctx.pause();
        }
        if !self.control {
            return None;
        }
        if cfg!(target_arch = "wasm32") {
            eprintln!("ponko: the control endpoint isn't available in web builds");
            return None;
        }
        match Control::start(&self.title, headless) {
            Ok(c) => {
                ctx.control_addr = Some(c.addr());
                Some(c)
            }
            Err(e) => {
                eprintln!("ponko: could not open the control endpoint: {e}");
                None
            }
        }
    }

    /// Sets the seed for [`Ctx::random`]. Same seed, same simulation: runs
    /// are reproducible by default ([`DEFAULT_SEED`](crate::DEFAULT_SEED)).
    /// For a different world each run, seed from the clock.
    ///
    /// ```no_run
    /// # use ponko::*;
    /// let seed = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_secs();
    /// Game::new("Roguelike", 800, 600).seed(seed).run(|_| {});
    /// ```
    pub fn seed(mut self, seed: u64) -> Self {
        self.seed = seed;
        self
    }

    /// Sets how many fixed updates run per second (default 60).
    /// See [`Ctx::fixed_steps`].
    ///
    /// # Panics
    /// If `hz` is 0.
    ///
    /// ```no_run
    /// # use ponko::*;
    /// Game::new("Physics", 800, 600).fixed_hz(120).run(|_| |_: &mut Ctx| {});
    /// ```
    pub fn fixed_hz(mut self, hz: u32) -> Self {
        assert!(hz > 0, "Game::fixed_hz: the rate must be at least 1 Hz");
        self.fixed_hz = hz;
        self.fixed_hz_set = true;
        self
    }

    /// Turns vsync on (default) or off. With vsync the game runs at the
    /// display's refresh rate with no tearing; turn it off to measure how fast
    /// the game *could* run.
    ///
    /// ```no_run
    /// # use ponko::*;
    /// Game::new("Benchmark", 800, 600).vsync(false).run(|_| |_: &mut Ctx| {});
    /// ```
    pub fn vsync(mut self, on: bool) -> Self {
        self.vsync = on;
        self
    }

    /// How many samples per pixel the 3D frame takes to smooth its edges:
    /// 4 (default) or 2. 2 costs about a third less GPU time on a large
    /// screen, with a little more stair-stepping on thin edges. GPUs that
    /// can't take 2 everywhere (WebGL2, some mobile ones) keep 4.
    ///
    /// ```no_run
    /// # use ponko::*;
    /// Game::new("Open world", 1280, 720).msaa(2).run(|_| |_: &mut Ctx| {});
    /// ```
    ///
    /// # Panics
    ///
    /// If `samples` is not 2 or 4.
    pub fn msaa(mut self, samples: u32) -> Self {
        assert!(
            matches!(samples, 2 | 4),
            "the 3D frame takes 2 or 4 samples per pixel, not {samples}"
        );
        self.msaa = samples;
        self
    }

    /// Fills the screen with the game instead of opening a window (off by
    /// default). On macOS, windowed games are shown at most once per display
    /// refresh even with vsync off; fullscreen ones aren't. Web builds
    /// ignore it.
    ///
    /// ```no_run
    /// # use ponko::*;
    /// Game::new("Benchmark", 1280, 720).fullscreen(true).vsync(false).run(|_| |_: &mut Ctx| {});
    /// ```
    pub fn fullscreen(mut self, on: bool) -> Self {
        self.fullscreen = on;
        self
    }

    /// One frame of game logic: simulation systems `fixed_steps` times, then
    /// frame systems, then built-in drawing. Commands are applied after every system.
    fn run_systems(&mut self, ctx: &mut Ctx, fixed_steps: u32) {
        ctx.update_retained_ui();
        self.begin_timings(ctx);
        ctx.set_in_sim(true);
        for _ in 0..fixed_steps {
            // Lockstep: a tick waits for everyone's input; the frame goes on.
            if !ctx.net.ready(ctx.sim_tick()) {
                break;
            }
            self.run_sim_tick(ctx);
        }
        ctx.set_in_sim(false);
        let n_sim = self.sim_systems.len();
        let n_frame = self.systems.len();
        for (i, s) in self.systems.iter_mut().enumerate() {
            run_one(s, ctx, n_sim + i);
        }
        #[cfg(feature = "3d")]
        ctx.update_animators();
        #[cfg(feature = "3d")]
        ctx.update_particles();
        for (i, s) in self.late_systems.iter_mut().enumerate() {
            run_one(s, ctx, n_sim + n_frame + i);
        }
        for (i, s) in self.draw_systems.iter_mut().enumerate() {
            run_one(s, ctx, n_sim + n_frame + self.late_systems.len() + i);
        }
        // Positional sound follows where everything ended up this frame.
        #[cfg(feature = "3d")]
        crate::audio::update_audio3d(ctx);
        end_timings(ctx);
    }

    /// One simulation tick: every sim system once, then the tick counter.
    fn run_sim_tick(&mut self, ctx: &mut Ctx) {
        let tick = ctx.sim_tick();
        for (i, s) in self.sim_systems.iter_mut().enumerate() {
            if tick % u64::from(s.every) != u64::from(s.phase) {
                continue;
            }
            ctx.set_sim_steps(s.every);
            run_one(s, ctx, i);
        }
        ctx.set_sim_steps(1);
        ctx.net.end_tick(&ctx.world, tick);
        ctx.advance_tick();
    }

    /// Makes sure there's one timing slot per system, and zeroes this frame's times.
    fn begin_timings(&self, ctx: &mut Ctx) {
        if ctx.timings.len()
            != self.sim_systems.len() + self.systems.len() + self.late_systems.len() + self.draw_systems.len()
        {
            ctx.timings = (self.sim_systems.iter().map(|s| (s, true)))
                .chain(
                    self.systems
                        .iter()
                        .chain(&self.late_systems)
                        .chain(&self.draw_systems)
                        .map(|s| (s, false)),
                )
                .map(|(s, sim)| SystemTiming {
                    name: s.name,
                    sim,
                    last_ms: 0.0,
                    avg_ms: 0.0,
                })
                .collect();
        }
        for t in &mut ctx.timings {
            t.last_ms = 0.0;
        }
        ctx.sync_profiling();
        ctx.perf.begin_frame(ctx.timings.len());
        ctx.events.keep_ticks = self.sim_systems.iter().map(|s| s.every).max().unwrap_or(1);
    }

    /// Runs the simulation without a window or GPU, as fast as possible, and
    /// returns the world when done. For dedicated servers, batch runs,
    /// benchmarks, and testing game logic in plain `cargo test`.
    ///
    /// `setup` runs once, then `ticks` simulation ticks run (fewer if a
    /// system calls `ctx.quit()`). Only **simulation systems** run: frame
    /// systems, the closure returned by `setup`, and drawing need frames, and
    /// there are none. Sim speed is ignored, and so is pause unless the
    /// [control endpoint](Self::control_endpoint) is on: then a paused game
    /// waits for tools to step or resume it. Textures still load (for their
    /// sizes), but nothing is uploaded to a GPU.
    ///
    /// ```
    /// use ponko::*;
    ///
    /// struct Pos(f32);
    ///
    /// fn fall(ctx: &mut Ctx) {
    ///     let dt = ctx.dt();
    ///     ctx.world.query::<&mut Pos>().for_each(|p| p.0 -= 10.0 * dt);
    /// }
    ///
    /// let mut world = Game::new("test", 800, 600)
    ///     .sim_system(fall)
    ///     .run_headless(60, |ctx| {
    ///         ctx.world.spawn((Pos(100.0),));
    ///     });
    ///
    /// // One simulated second at 10 units/s.
    /// let y = world.query::<&Pos>().iter().next().unwrap().0;
    /// assert!((y - 90.0).abs() < 1e-3);
    /// ```
    pub fn run_headless<S, U>(self, ticks: u64, setup: S) -> World
    where
        S: FnOnce(&mut Ctx) -> U,
        U: SetupResult,
    {
        self.run_headless_inner(ticks, None, setup).0
    }

    /// Like [`run_headless`](Self::run_headless), but times everything and
    /// returns a [`PerfReport`](crate::PerfReport) next to the world: where
    /// the time goes (systems, [`profile_scope!`](crate::profile_scope)
    /// scopes), allocations, the slowest ticks, and warnings with advice.
    /// The first `warmup` ticks run but aren't measured (caches fill, buffers
    /// grow); the report covers the next `ticks` ticks (at most the last
    /// 50,000). Call it from a test or a CI job; see [`PerfReport::assert_within`](crate::PerfReport::assert_within).
    ///
    /// Counting allocations needs [`CountingAllocator`](crate::CountingAllocator)
    /// as the global allocator.
    ///
    /// ```
    /// use ponko::*;
    ///
    /// fn movement(ctx: &mut Ctx) {
    ///     profile_scope!("movement/integrate");
    ///     ctx.world.query::<&mut Transform2D>().for_each(|t| t.position.x += 1.0);
    /// }
    ///
    /// let (_world, report) = Game::new("bench", 1, 1)
    ///     .sim_system(movement)
    ///     .profile_headless(10, 100, |ctx| {
    ///         for _ in 0..1000 {
    ///             ctx.world.spawn((Transform2D::default(),));
    ///         }
    ///     });
    /// assert_eq!((report.frames, report.entities), (100, 1000));
    /// // Timings vary between machines: keep limits generous.
    /// report.assert_within(&Budget::new().frame_p99_ms(100.0));
    /// ```
    pub fn profile_headless<S, U>(self, warmup: u64, ticks: u64, setup: S) -> (World, crate::PerfReport)
    where
        S: FnOnce(&mut Ctx) -> U,
        U: SetupResult,
    {
        let (world, report) = self.run_headless_inner(ticks, Some(warmup), setup);
        (world, report.unwrap_or_default())
    }

    fn run_headless_inner<S, U>(
        mut self,
        ticks: u64,
        warmup: Option<u64>,
        setup: S,
    ) -> (World, Option<crate::PerfReport>)
    where
        S: FnOnce(&mut Ctx) -> U,
        U: SetupResult,
    {
        connect_hotpatch();
        let fixed_dt = Clock::new(self.fixed_hz).fixed_dt();
        let mut ctx = Ctx::new(fixed_dt, Vec2::new(self.width as f32, self.height as f32));
        ctx.seed = self.seed;
        ctx.headless = true;
        ctx.watcher.on = crate::hot_reload::enabled(self.hot_reload);
        if let Some(cell) = self.spatial_cell {
            ctx.spatial = crate::SpatialGrid::new(cell);
        }
        #[cfg(feature = "physics")]
        if let Some(gravity) = self.gravity {
            crate::physics::start(&mut ctx, gravity);
        }
        #[cfg(feature = "physics3d")]
        if let Some(gravity) = self.gravity3d {
            crate::physics3d::start(&mut ctx, gravity);
        }
        let control = self.start_control(&mut ctx, true);
        if let Some(net) = self.net.take() {
            ctx.net = net;
        }
        ctx.net.begin(ctx.seed);
        drop(setup(&mut ctx).into_frame_fn()); // no frames, so no frame closure
        ctx.apply_commands();
        ctx.discard_draws();

        let timing = FrameTiming {
            dt: fixed_dt as f32,
            fixed_steps: 1,
            alpha: 0.0,
        };
        if warmup.is_some() {
            ctx.perf.collector = crate::perf_report::Collector::new(crate::perf_report::HEADLESS_HISTORY);
            ctx.set_profiling(true);
        }
        let total = ticks + warmup.unwrap_or(0);
        let mut ran = 0;
        while ran < total && !ctx.quit_requested() {
            if let Some(control) = &control {
                control.poll(&mut ctx);
                if ctx.quit_requested() {
                    break;
                }
                // A paused game runs only the ticks tools ask for.
                if ctx.is_paused() && !ctx.take_one_step() {
                    control.wait(&mut ctx, Duration::from_millis(50));
                    continue;
                }
            }
            if !ctx.net.ready(ctx.sim_tick()) {
                if !ctx.net.wait() {
                    break;
                }
                continue;
            }
            ran += 1;
            let tick_start = Instant::now();
            ctx.begin_frame(timing);
            ctx.reload_changed_assets();
            self.begin_timings(&mut ctx);
            ctx.set_in_sim(true);
            self.run_sim_tick(&mut ctx);
            ctx.set_in_sim(false);
            end_timings(&mut ctx);
            ctx.discard_draws();
            ctx.input.end_frame();
            if ctx.perf.on {
                ctx.end_perf_frame(tick_start.elapsed().as_secs_f32() * 1000.0);
                if warmup == Some(ran) {
                    ctx.perf.collector.clear();
                }
            }
        }
        let report = warmup.map(|_| ctx.perf_report());
        (std::mem::take(&mut ctx.world), report)
    }

    /// Opens the window and runs the game until it is closed.
    ///
    /// `setup` runs once, after the window exists. It can spawn entities into
    /// `ctx.world`, and it can return a closure that runs every frame (after
    /// the systems). Variables created in `setup` and moved into that closure
    /// are your game state; no structs or traits required.
    ///
    /// Each frame runs: simulation systems (`ctx.fixed_steps()` times), then
    /// frame systems, then the closure from `setup`, then the built-in
    /// [`draw_sprites`], then rendering.
    ///
    /// ```no_run
    /// # use ponko::*;
    /// Game::new("Counter", 800, 600).run(|_ctx| {
    ///     let mut clicks = 0;
    ///     move |ctx: &mut Ctx| {
    ///         if ctx.mouse_pressed(MouseButton::Left) {
    ///             clicks += 1;
    ///             println!("clicks: {clicks}");
    ///         }
    ///     }
    /// });
    /// ```
    ///
    /// # Panics
    /// If the operating system refuses to create the event loop or window,
    /// or no usable GPU is found, and always when the `window` feature is
    /// off.
    pub fn run<S, U>(self, setup: S)
    where
        S: FnOnce(&mut Ctx) -> U,
        U: SetupResult,
    {
        #[cfg(feature = "window")]
        window::run(self, setup);
        #[cfg(not(feature = "window"))]
        {
            drop((self, setup));
            panic!(
                "ponko: Game::run needs a window, and this build has none \
                 (the `window` feature is off); use Game::run_headless"
            );
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    struct Log(Vec<String>);
    struct Marker;

    fn ctx() -> Ctx {
        let mut ctx = Ctx::new(1.0 / 60.0, Vec2::new(800.0, 600.0));
        ctx.world.insert_resource(Log(Vec::new()));
        ctx
    }

    fn log(ctx: &mut Ctx, s: &str) {
        let line = format!("{s} dt={:.4}", ctx.dt());
        ctx.world.resource_mut::<Log>().0.push(line);
    }

    fn sim_a(ctx: &mut Ctx) {
        log(ctx, "sim_a");
    }

    /// A game without the built-in drawing systems.
    fn bare(game: Game) -> Game {
        game.remove_system(animate_sprites)
            .remove_system(draw_tilemaps)
            .remove_system(draw_sprites)
    }
    fn frame_b(ctx: &mut Ctx) {
        log(ctx, "frame_b");
    }

    #[cfg(feature = "3d")]
    #[test]
    fn late_system_sees_automatic_animation_pose() {
        use crate::{AnimationClip, AnimationGraph, AnimationState, Animator, Joint, Motion, Skeleton, Transform3D};
        let skeleton = Skeleton::new(vec![Joint {
            name: "root".into(),
            parent: None,
            rest: Transform3D::default(),
        }]);
        let clip = AnimationClip::new("rest", &skeleton, vec![]);
        let animator = Animator::new(AnimationGraph::new(
            vec![],
            vec![AnimationState::new(Motion::Clip(clip))],
            vec![],
            0,
        ));
        let mut ctx = ctx();
        let entity = ctx.world.spawn((skeleton, animator));
        let mut game = bare(Game::new("t", 1, 1))
            .system(move |ctx| ctx.world.get_mut::<Skeleton>(entity).unwrap().pose[0].position.x = 7.0)
            .late_system(move |ctx| {
                let s = ctx.world.get_mut::<Skeleton>(entity).unwrap();
                assert_eq!(s.pose[0].position.x, 0.0);
                s.pose[0].position.x = 2.0;
            });
        game.run_systems(&mut ctx, 0);
        assert_eq!(ctx.world.get::<Skeleton>(entity).unwrap().pose[0].position.x, 2.0);
    }

    #[test]
    fn late_system_runs_after_frame_before_draw_and_is_timed() {
        fn late(ctx: &mut Ctx) {
            log(ctx, "late");
        }
        fn draw(ctx: &mut Ctx) {
            log(ctx, "draw");
        }
        let mut game = bare(Game::new("t", 1, 1)).system(frame_b).late_system(late);
        game.draw_systems.push(System::new(draw));
        let mut ctx = ctx();
        game.run_systems(&mut ctx, 0);
        assert_eq!(
            ctx.world.resource::<Log>().0,
            ["frame_b dt=0.0000", "late dt=0.0000", "draw dt=0.0000"]
        );
        assert_eq!(ctx.system_timings().len(), 3);
        assert!(ctx.system_timings()[1].name.ends_with("::late"));
        let game = game.remove_system(late);
        assert!(game.late_systems.is_empty());
    }

    #[test]
    fn order_and_dt() {
        let mut game = Game::new("t", 1, 1)
            .sim_system(sim_a)
            .system(frame_b)
            .remove_system(draw_sprites);
        let mut ctx = ctx();
        game.run_systems(&mut ctx, 2);
        assert_eq!(
            ctx.world.resource::<Log>().0,
            ["sim_a dt=0.0167", "sim_a dt=0.0167", "frame_b dt=0.0000"]
        );
    }

    #[test]
    fn commands_apply_between_systems() {
        fn spawner(ctx: &mut Ctx) {
            ctx.commands.spawn((Marker,));
        }
        fn counter(ctx: &mut Ctx) {
            let n = ctx.world.query::<&Marker>().count();
            ctx.world.resource_mut::<Log>().0.push(n.to_string());
        }
        let mut game = Game::new("t", 1, 1).system(spawner).system(counter);
        let mut ctx = ctx();
        game.run_systems(&mut ctx, 0);
        game.run_systems(&mut ctx, 0);
        assert_eq!(ctx.world.resource::<Log>().0, ["1", "2"]);
    }

    #[test]
    fn remove_system_removes_builtin_and_user_systems() {
        let game = bare(Game::new("t", 1, 1).sim_system(sim_a)).remove_system(sim_a);
        assert!(game.systems.is_empty() && game.sim_systems.is_empty() && game.draw_systems.is_empty());
    }

    #[test]
    #[should_panic(expected = "no system")]
    fn removing_unknown_system_panics() {
        let _ = Game::new("t", 1, 1).remove_system(sim_a);
    }

    #[test]
    fn pause_step_and_speed_shape_frame_timing() {
        let mut clock = Clock::new(60);
        let mut ctx = ctx();
        let frame = 1.0 / 60.0;
        ctx.pause();
        assert_eq!(frame_timing(&mut clock, &mut ctx, frame).fixed_steps, 0);
        ctx.step();
        ctx.step();
        assert_eq!(
            frame_timing(&mut clock, &mut ctx, frame).fixed_steps,
            2,
            "two single steps while paused"
        );
        assert_eq!(
            frame_timing(&mut clock, &mut ctx, frame).fixed_steps,
            0,
            "steps are used up"
        );
        ctx.resume();
        ctx.set_sim_speed(4.0);
        let steps: u32 = (0..60)
            .map(|_| frame_timing(&mut clock, &mut ctx, frame).fixed_steps)
            .sum();
        assert!((239..=240).contains(&steps), "4x speed for one second, got {steps}");
    }

    #[test]
    fn records_system_timings() {
        fn slow(_: &mut Ctx) {
            std::thread::sleep(std::time::Duration::from_millis(2));
        }
        let mut game = bare(Game::new("t", 1, 1).sim_system(slow)).system(frame_b);
        let mut ctx = ctx();
        game.run_systems(&mut ctx, 3);
        let t = ctx.system_timings();
        assert_eq!(t.len(), 2, "{t:?}");
        assert!(t[0].sim && !t[1].sim);
        assert!(t[0].name.ends_with("slow"), "{}", t[0].name);
        assert!(t[0].last_ms >= 6.0, "3 steps of 2 ms, got {}", t[0].last_ms);
        assert!(t[0].avg_ms > 0.0 && t[0].avg_ms < t[0].last_ms);
    }

    #[test]
    fn drawing_sees_positions_from_frame_systems() {
        fn move_right(ctx: &mut Ctx) {
            ctx.world
                .query::<&mut crate::Transform2D>()
                .for_each(|t| t.position.x += 1.0);
        }
        let mut game = Game::new("t", 1, 1).system(move_right);
        let mut ctx = ctx();
        game.run_systems(&mut ctx, 0);
        let order: Vec<_> = ctx.system_timings().iter().map(|t| t.name).collect();
        assert!(
            order[0].ends_with("move_right") && order.last().unwrap().ends_with("draw_sprites"),
            "{order:?}"
        );
    }

    #[test]
    fn draw_sprites_queues_world_sprites() {
        let mut game = Game::new("t", 1, 1);
        let mut ctx = ctx();
        let tex = crate::texture::Texture::new(0, 16, 16);
        for i in 0..10 {
            ctx.world
                .spawn((crate::Transform2D::at(Vec2::splat(i as f32)), crate::Sprite::new(tex)));
        }
        ctx.world.spawn((crate::Transform2D::default(),)); // no sprite: not drawn
        game.run_systems(&mut ctx, 0);
        assert_eq!(ctx.sprite_count(), 10);
    }
}