pebble-engine 0.26.1

A modular, ECS-style graphics/app framework for Rust.
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
use std::cell::RefMut;
use std::ops::{Deref, DerefMut};

use crate::ecs::resources::Resources;

/// Immutable borrow of a singleton resource `T`.
///
/// Obtained as a system parameter; derefs to `T`.
pub struct Res<'a, T: hecs::Component> {
    pub(crate) data: hecs::Ref<'a, T>,
}

impl<'a, T: hecs::Component> Deref for Res<'a, T> {
    type Target = T;
    fn deref(&self) -> &Self::Target {
        &self.data
    }
}

/// Mutable borrow of a singleton resource `T`.
///
/// Obtained as a system parameter; derefs to `T`.
pub struct ResMut<'a, T: hecs::Component> {
    data: hecs::RefMut<'a, T>,
}

impl<'a, T: hecs::Component> Deref for ResMut<'a, T> {
    type Target = T;
    fn deref(&self) -> &Self::Target {
        &self.data
    }
}

impl<'a, T: hecs::Component> DerefMut for ResMut<'a, T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.data
    }
}

/// Borrow of an ECS query result — a curated wrapper around `hecs`'s query types, not a
/// transparent passthrough to them: no `hecs::*` type appears in any method here, and nothing
/// leaks through beyond what's listed below.
///
/// # Iterating
///
/// [`iter`](Self::iter) returns a plain `Iterator`, so the usual adapters (`.filter(...)`,
/// `.map(...)`, `.take(...)`, `.collect()`, ...) all compose directly — reach for `.filter(...)`
/// for a predicate over the yielded *values* (health below a threshold, say); [`with`](Self::with)/
/// [`without`](Self::without) below are for filtering by which *components* an entity has, not
/// their values.
///
/// ```ignore
/// fn move_system(mut q: Query<(&mut Position, &Velocity)>) {
///     for (pos, vel) in q.iter() {
///         pos.x += vel.x;
///         pos.y += vel.y;
///     }
/// }
/// ```
///
/// `Query` also implements `IntoIterator` for `&mut Query`, so `for item in &mut q` works too,
/// identically to `for item in q.iter()`.
///
/// Include `hecs::Entity` in `Q` (e.g. `Query<(Entity, &Position)>`) if you need the entity id
/// back alongside its components — it's a query term like any other, not a separate mechanism.
///
/// # Narrowing by component (`with`/`without`)
///
/// [`with`](Self::with)/[`without`](Self::without) narrow which entities match, without adding
/// to (or needing) the yielded item type, and — unlike calling straight through to `hecs` —
/// chain: each returns another `Query`, so `.with::<&Enemy>().without::<&Dead>().iter()` keeps
/// every method on this page available at each step, no `hecs::With`/`hecs::Without` naming
/// required on your end.
///
/// # Single-entity lookups
///
/// Use [`Query::get`] to fetch components for one known `Entity` without scanning the whole
/// result set, and [`Query::single`]/[`Query::get_single`] when you expect exactly one match
/// (e.g. "the player", "the active camera").
pub struct Query<'a, Q: hecs::Query> {
    world: &'a hecs::World,
    borrow: hecs::QueryBorrow<'a, Q>,
    /// Scratch storage for [`get`](Self::get) — a fresh one-shot lookup is built into this slot
    /// on every call (dropping whatever was there from the last call) so the item it returns
    /// can borrow from `self` (stable, caller-controlled) instead of a temporary that would be
    /// gone by the time the caller could use it.
    scratch: Option<hecs::QueryOne<'a, Q>>,
}

impl<'q, Q: hecs::Query> IntoIterator for &'q mut Query<'_, Q> {
    type Item = Q::Item<'q>;
    type IntoIter = hecs::QueryIter<'q, Q>;

    fn into_iter(self) -> Self::IntoIter {
        (&mut self.borrow).into_iter()
    }
}

impl<'a, Q: hecs::Query> Query<'a, Q> {
    /// Iterate every entity matching this query. An ordinary `Iterator` — `.filter(...)`,
    /// `.map(...)`, `.count()`, `.collect()`, and every other standard adapter work directly on
    /// the result, no `hecs` types involved.
    pub fn iter(&mut self) -> impl Iterator<Item = Q::Item<'_>> {
        self.borrow.iter()
    }

    /// Look up a single entity's components for this query. `None` if the entity doesn't exist
    /// or doesn't match `Q`.
    pub fn get(&mut self, entity: hecs::Entity) -> Option<Q::Item<'_>> {
        self.scratch = Some(self.world.query_one::<Q>(entity));
        self.scratch.as_mut().unwrap().get().ok()
    }

    /// Narrow this query to only entities that ALSO have component(s) `R`, without `R` itself
    /// being part of the yielded items. Consumes `self` and returns another `Query` — chain
    /// further `.with`/`.without`, or call `.iter`/`.get`/`.single` directly on the result.
    pub fn with<R: hecs::Query>(self) -> Query<'a, hecs::With<Q, R>> {
        Query { world: self.world, borrow: self.borrow.with::<R>(), scratch: None }
    }

    /// Narrow this query to only entities that do NOT have component(s) `R`. Same shape as
    /// [`with`](Self::with).
    pub fn without<R: hecs::Query>(self) -> Query<'a, hecs::Without<Q, R>> {
        Query { world: self.world, borrow: self.borrow.without::<R>(), scratch: None }
    }

    /// Return the single entity's components for this query.
    ///
    /// Panics if there isn't exactly one match. Intended for singleton-style
    /// queries (the player, the active camera, ...) where zero or multiple
    /// matches indicate a bug. See [`Query::get_single`] for a
    /// non-panicking version. Include `hecs::Entity` in `Q` if you need the
    /// id alongside the components.
    pub fn single(&mut self) -> Q::Item<'_> {
        self.get_single()
            .expect("Query::single: expected exactly one matching entity")
    }

    /// Like [`Query::single`], but returns `None` instead of panicking when
    /// there isn't exactly one match.
    pub fn get_single(&mut self) -> Option<Q::Item<'_>> {
        let mut iter = self.borrow.iter();
        let first = iter.next()?;
        if iter.next().is_some() {
            return None;
        }
        Some(first)
    }
}

/// Deferred world-mutation commands available as a system parameter.
///
/// Mutations are buffered and applied to the world after all systems in the
/// current stage have finished running.
pub struct Commands<'a> {
    buffer: RefMut<'a, hecs::CommandBuffer>,
    resource_entity: hecs::Entity,
}

impl<'a> Commands<'a> {
    /// Queue a resource insertion. Applied after the current stage finishes.
    pub fn insert_resource<T: hecs::Component>(&mut self, res: T) {
        self.buffer.insert_one(self.resource_entity, res);
    }

    /// Queue a resource removal. Applied after the current stage finishes.
    pub fn remove_resource<T: hecs::Component>(&mut self) {
        self.buffer.remove_one::<T>(self.resource_entity);
    }
}

impl<'a> Deref for Commands<'a> {
    type Target = hecs::CommandBuffer;
    fn deref(&self) -> &Self::Target {
        &self.buffer
    }
}

impl<'a> DerefMut for Commands<'a> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.buffer
    }
}

/// Per-system persistent local state.
///
/// Unlike [`Res`]/[`ResMut`], a `Local<T>` is *not* shared through
/// [`Resources`] — each system gets its own private `T`, initialized with
/// [`Default::default`] the first time the system is registered, and
/// preserved across every subsequent run of that system.
///
/// Useful for counters, caches, or any state a single system needs to
/// remember without polluting the global resource set.
pub struct Local<'a, T: Default + Send + Sync + 'static> {
    data: &'a mut T,
}

impl<'a, T: Default + Send + Sync + 'static> Deref for Local<'a, T> {
    type Target = T;
    fn deref(&self) -> &Self::Target {
        self.data
    }
}

impl<'a, T: Default + Send + Sync + 'static> DerefMut for Local<'a, T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.data
    }
}

/// Trait implemented for each valid system parameter type.
///
/// The macro-generated [`impl_system!`] blanket implementations use this to
/// fetch each parameter from the world and resources before calling the system
/// function. `State` is per-system storage owned by the [`FunctionSystem`]
/// itself (as opposed to `Item`, which only lives for the duration of one
/// call) — this is what lets [`Local`] persist between runs.
pub trait SystemParam {
    type Item<'a>;
    type State: Default + 'static;
    fn fetch<'a>(
        state: &'a mut Self::State,
        world: &'a hecs::World,
        resources: &'a Resources,
    ) -> Self::Item<'a>;
}

impl<T> SystemParam for Res<'static, T>
where
    T: 'static + Sync + Send,
{
    type Item<'a> = Res<'a, T>;
    type State = ();

    fn fetch<'a>(
        _state: &'a mut Self::State,
        world: &'a hecs::World,
        resource: &'a Resources,
    ) -> Self::Item<'a> {
        Res {
            data: resource.get_resource(world),
        }
    }
}

impl<T> SystemParam for Option<Res<'static, T>>
where
    T: 'static + Sync + Send,
{
    type Item<'a> = Option<Res<'a, T>>;
    type State = ();

    fn fetch<'a>(
        _state: &'a mut Self::State,
        world: &'a hecs::World,
        resource: &'a Resources,
    ) -> Self::Item<'a> {
        if resource.has_resource::<T>(world) {
            return Some(Res {
                data: resource.get_resource(world),
            });
        }

        None
    }
}

impl<T> SystemParam for ResMut<'static, T>
where
    T: 'static + Sync + Send,
{
    type Item<'a> = ResMut<'a, T>;
    type State = ();

    fn fetch<'a>(
        _state: &'a mut Self::State,
        world: &'a hecs::World,
        resource: &'a Resources,
    ) -> Self::Item<'a> {
        ResMut {
            data: resource.get_resource_mut(world),
        }
    }
}

impl<T> SystemParam for Option<ResMut<'static, T>>
where
    T: 'static + Sync + Send,
{
    type Item<'a> = Option<ResMut<'a, T>>;
    type State = ();

    fn fetch<'a>(
        _state: &'a mut Self::State,
        world: &'a hecs::World,
        resource: &'a Resources,
    ) -> Self::Item<'a> {
        if resource.has_resource::<T>(world) {
            return Some(ResMut {
                data: resource.get_resource_mut(world),
            });
        }

        None
    }
}

impl<Q> SystemParam for Query<'static, Q>
where
    Q: hecs::Query + 'static,
{
    type Item<'a> = Query<'a, Q>;
    type State = ();

    fn fetch<'a>(
        _state: &'a mut Self::State,
        world: &'a hecs::World,
        _resources: &'a Resources,
    ) -> Self::Item<'a> {
        Query {
            world,
            borrow: world.query::<Q>(),
            scratch: None,
        }
    }
}

impl SystemParam for Commands<'static> {
    type Item<'a> = Commands<'a>;
    type State = ();

    fn fetch<'a>(
        _state: &'a mut Self::State,
        _world: &'a hecs::World,
        resources: &'a Resources,
    ) -> Self::Item<'a> {
        Commands {
            buffer: resources.get_command_buffer(),
            resource_entity: resources.resource_entity,
        }
    }
}

impl SystemParam for &'static hecs::World {
    type Item<'a> = &'a hecs::World;
    type State = ();

    fn fetch<'a>(
        _state: &'a mut Self::State,
        world: &'a hecs::World,
        _resources: &'a Resources,
    ) -> Self::Item<'a> {
        world
    }
}

impl SystemParam for &'static Resources {
    type Item<'a> = &'a Resources;
    type State = ();

    fn fetch<'a>(
        _state: &'a mut Self::State,
        _world: &'a hecs::World,
        resources: &'a Resources,
    ) -> Self::Item<'a> {
        resources
    }
}

impl<T> SystemParam for Local<'static, T>
where
    T: Default + Send + Sync + 'static,
{
    type Item<'a> = Local<'a, T>;
    type State = T;

    fn fetch<'a>(
        state: &'a mut Self::State,
        _world: &'a hecs::World,
        _resources: &'a Resources,
    ) -> Self::Item<'a> {
        Local { data: state }
    }
}

/// A type-erased, executable system.
pub trait System: 'static {
    fn run(&mut self, world: &hecs::World, resources: &Resources);

    /// Human-readable identifier for this system, used in error/trace output.
    /// Defaults to the type name of the [`System`] impl; [`FunctionSystem`]
    /// overrides this with the name of the wrapped function/closure.
    fn name(&self) -> &'static str {
        std::any::type_name::<Self>()
    }

    /// This system's identity for ordering purposes — the [`TypeId`](std::any::TypeId)
    /// of the function/closure it wraps. Automatic: every distinct function
    /// or closure has a distinct type, so no manual labeling is needed to
    /// make a system a valid target for another system's
    /// [`after`](SystemOrderingExt::after)/[`before`](SystemOrderingExt::before).
    /// Defaults to `Self`'s own `TypeId`; [`FunctionSystem`]/[`OnceFunctionSystem`]
    /// override it with the wrapped function's `TypeId` instead of the
    /// wrapper's, so ordering constraints referencing the bare function match.
    fn ordering_id(&self) -> std::any::TypeId {
        std::any::TypeId::of::<Self>()
    }

    /// Other systems in the same stage that must run before this one. Set
    /// via [`SystemOrderingExt::after`]. A referenced system that isn't
    /// registered in the same stage is silently ignored.
    fn after_ids(&self) -> &[std::any::TypeId] {
        &[]
    }

    /// Other systems in the same stage that must run after this one. Set
    /// via [`SystemOrderingExt::before`]. A referenced system that isn't
    /// registered in the same stage is silently ignored.
    fn before_ids(&self) -> &[std::any::TypeId] {
        &[]
    }
}

/// Wraps a [`System`] with ordering constraints relative to other systems in
/// the same stage, added via [`SystemOrderingExt`].
///
/// Constraints only take effect within the stage the system is registered
/// to — there's no cross-stage ordering, since stage order is already fixed
/// by [`SystemStage`](crate::app::SystemStage). [`App::build`](crate::app::App::build)
/// topologically sorts each stage's systems by these constraints, breaking
/// ties by registration order, and panics if constraints form a cycle.
pub struct Labeled<S: System> {
    inner: S,
    after: Vec<std::any::TypeId>,
    before: Vec<std::any::TypeId>,
}

impl<S: System> Labeled<S> {
    /// Require that `system` runs before this one, within the same stage.
    /// Chainable — call multiple times to depend on multiple systems.
    pub fn after<F: 'static, Marker>(mut self, system: F) -> Self
    where
        F: IntoSystem<Marker>,
    {
        let _ = system;
        self.after.push(std::any::TypeId::of::<F>());
        self
    }

    /// Require that `system` runs after this one, within the same stage.
    /// Chainable — call multiple times to constrain multiple systems.
    pub fn before<F: 'static, Marker>(mut self, system: F) -> Self
    where
        F: IntoSystem<Marker>,
    {
        let _ = system;
        self.before.push(std::any::TypeId::of::<F>());
        self
    }
}

impl<S: System> System for Labeled<S> {
    fn run(&mut self, world: &hecs::World, resources: &Resources) {
        self.inner.run(world, resources)
    }

    fn name(&self) -> &'static str {
        self.inner.name()
    }

    fn ordering_id(&self) -> std::any::TypeId {
        self.inner.ordering_id()
    }

    fn after_ids(&self) -> &[std::any::TypeId] {
        &self.after
    }

    fn before_ids(&self) -> &[std::any::TypeId] {
        &self.before
    }
}

impl<S: System> IntoSystem<()> for Labeled<S> {
    type System = Self;

    fn into_system(self) -> Self::System {
        self
    }
}

/// Adds [`.after()`](SystemOrderingExt::after)/[`.before()`](SystemOrderingExt::before)
/// to any system, for declaring run-order constraints relative to other
/// systems in the same stage — referenced directly by their function/closure,
/// no string labels needed.
///
/// ```ignore
/// app.add_system(SystemStage::Update, physics_step);
/// app.add_system(SystemStage::Update, apply_damage.after(physics_step));
/// ```
pub trait SystemOrderingExt<Marker>: IntoSystem<Marker> + Sized {
    /// Require that `system` runs before this one, within the same stage.
    fn after<F: 'static, Marker2>(self, system: F) -> Labeled<Self::System>
    where
        F: IntoSystem<Marker2>,
    {
        let _ = system;
        Labeled {
            inner: self.into_system(),
            after: vec![std::any::TypeId::of::<F>()],
            before: Vec::new(),
        }
    }

    /// Require that `system` runs after this one, within the same stage.
    fn before<F: 'static, Marker2>(self, system: F) -> Labeled<Self::System>
    where
        F: IntoSystem<Marker2>,
    {
        let _ = system;
        Labeled {
            inner: self.into_system(),
            after: Vec::new(),
            before: vec![std::any::TypeId::of::<F>()],
        }
    }
}

impl<T, Marker> SystemOrderingExt<Marker> for T where T: IntoSystem<Marker> {}

/// Type-erased wrapper around a system function, created by [`IntoSystem`].
///
/// Holds `State`, the tuple of each parameter's [`SystemParam::State`] — this
/// is where [`Local`] values actually live between calls to `run`.
pub struct FunctionSystem<F, Marker, State = ()> {
    pub func: F,
    state: State,
    _marker: std::marker::PhantomData<Marker>,
}

/// Converts a function (or closure) with valid system parameters into a
/// [`System`] that can be registered with [`App::add_system`](crate::app::App::add_system).
///
/// Implemented via the [`impl_system!`] macro for function arities 0–12.
pub trait IntoSystem<Marker> {
    type System: System;

    fn into_system(self) -> Self::System;
}

macro_rules! impl_system {
    ($($param:ident),*) => {
        impl<T, $($param),*> IntoSystem<($($param,)*)> for T
        where
            T: for<'a> FnMut($($param::Item<'a>),*) + 'static,
            for<'a> &'a mut T: FnMut($($param),*),
            $($param: SystemParam + 'static),*
        {
            type System = FunctionSystem<T, ($($param,)*), ($($param::State,)*)>;

            fn into_system(self) -> Self::System {
                FunctionSystem {
                    func: self,
                    state: Default::default(),
                    _marker: std::marker::PhantomData,
                }
            }
        }

        impl<T, $($param),*> System for FunctionSystem<T, ($($param,)*), ($($param::State,)*)>
        where
            T: for<'a> FnMut($($param::Item<'a>),*) + 'static,
            $($param: SystemParam + 'static),*
        {
            fn run(&mut self, _world: &hecs::World, _resources: &Resources) {
                #[allow(non_snake_case)]
                let ($($param,)*) = &mut self.state;
                (self.func)($($param::fetch($param, _world, _resources)),*);
            }

            fn name(&self) -> &'static str {
                std::any::type_name::<T>()
            }

            fn ordering_id(&self) -> std::any::TypeId {
                std::any::TypeId::of::<T>()
            }
        }
    };
}

impl_system!();
impl_system!(A);
impl_system!(A, B);
impl_system!(A, B, C);
impl_system!(A, B, C, D);
impl_system!(A, B, C, D, E);
impl_system!(A, B, C, D, E, F);
impl_system!(A, B, C, D, E, F, G);
impl_system!(A, B, C, D, E, F, G, H);
impl_system!(A, B, C, D, E, F, G, H, I);
impl_system!(A, B, C, D, E, F, G, H, I, J);
impl_system!(A, B, C, D, E, F, G, H, I, J, K);
impl_system!(A, B, C, D, E, F, G, H, I, J, K, L);

/// Marker type used as the first element of the `Marker` tuple in
/// [`IntoSystem`] for functions that return `Option<()>`. This distinguishes
/// their [`IntoSystem`] impl from the regular void-function impl so that both
/// can coexist without conflicting — Rust's coherence checker sees different
/// marker tuples `(OnceMark, A, B, ...)` vs `(A, B, ...)` and never confuses
/// them.
pub struct OnceMark;

/// Type-erased wrapper for functions returning `Option<()>`. Runs `func`
/// every tick until `func` returns `Some(())`, at which point it is
/// permanently retired — every subsequent invocation is a no-op. The "have I
/// already succeeded" bookkeeping lives entirely in `done`, hidden inside
/// this wrapper; the wrapped function itself just returns `None` ("not ready,
/// call me again") or `Some(())` ("done").
pub struct OnceFunctionSystem<F, Marker, State = ()> {
    func: F,
    state: State,
    done: bool,
    _marker: std::marker::PhantomData<Marker>,
}

macro_rules! impl_auto_once_system {
    ($($param:ident),*) => {
        impl<T, $($param),*> IntoSystem<(OnceMark, $($param,)*)> for T
        where
            T: for<'a> FnMut($($param::Item<'a>),*) -> Option<()> + 'static,
            for<'a> &'a mut T: FnMut($($param),*) -> Option<()>,
            $($param: SystemParam + 'static),*
        {
            type System = OnceFunctionSystem<T, ($($param,)*), ($($param::State,)*)>;

            fn into_system(self) -> Self::System {
                OnceFunctionSystem {
                    func: self,
                    state: Default::default(),
                    done: false,
                    _marker: std::marker::PhantomData,
                }
            }
        }

        impl<T, $($param),*> IntoSystem<(OnceMark, $($param,)*)> for OnceFunctionSystem<T, ($($param,)*), ($($param::State,)*)>
        where
            T: for<'a> FnMut($($param::Item<'a>),*) -> Option<()> + 'static,
            $($param: SystemParam + 'static),*
        {
            type System = Self;

            fn into_system(self) -> Self::System {
                self
            }
        }

        impl<T, $($param),*> System for OnceFunctionSystem<T, ($($param,)*), ($($param::State,)*)>
        where
            T: for<'a> FnMut($($param::Item<'a>),*) -> Option<()> + 'static,
            $($param: SystemParam + 'static),*
        {
            fn run(&mut self, _world: &hecs::World, _resources: &Resources) {
                if self.done {
                    return;
                }
                #[allow(non_snake_case)]
                let ($($param,)*) = &mut self.state;
                let result = (self.func)($($param::fetch($param, _world, _resources)),*);
                if result.is_some() {
                    self.done = true;
                }
            }

            fn name(&self) -> &'static str {
                std::any::type_name::<T>()
            }

            fn ordering_id(&self) -> std::any::TypeId {
                std::any::TypeId::of::<T>()
            }
        }
    };
}

impl_auto_once_system!();
impl_auto_once_system!(A);
impl_auto_once_system!(A, B);
impl_auto_once_system!(A, B, C);
impl_auto_once_system!(A, B, C, D);
impl_auto_once_system!(A, B, C, D, E);
impl_auto_once_system!(A, B, C, D, E, F);
impl_auto_once_system!(A, B, C, D, E, F, G);
impl_auto_once_system!(A, B, C, D, E, F, G, H);
impl_auto_once_system!(A, B, C, D, E, F, G, H, I);
impl_auto_once_system!(A, B, C, D, E, F, G, H, I, J);
impl_auto_once_system!(A, B, C, D, E, F, G, H, I, J, K);
impl_auto_once_system!(A, B, C, D, E, F, G, H, I, J, K, L);

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

    struct Health(i32);
    struct Enemy;
    struct Dead;

    fn make_query<Q: hecs::Query>(world: &hecs::World) -> Query<'_, Q> {
        Query { world, borrow: world.query::<Q>(), scratch: None }
    }

    #[test]
    fn iter_yields_every_matching_entity() {
        let mut world = hecs::World::new();
        world.spawn((Health(10),));
        world.spawn((Health(20),));

        let mut query = make_query::<&Health>(&world);
        let mut totals: Vec<i32> = query.iter().map(|h| h.0).collect();
        totals.sort();
        assert_eq!(totals, vec![10, 20]);
    }

    #[test]
    fn iter_composes_with_standard_iterator_adapters() {
        let mut world = hecs::World::new();
        world.spawn((Health(5),));
        world.spawn((Health(50),));

        let mut query = make_query::<&Health>(&world);
        let low_health_count = query.iter().filter(|h| h.0 < 10).count();
        assert_eq!(low_health_count, 1);
    }

    #[test]
    fn get_returns_some_for_a_matching_entity_and_none_otherwise() {
        let mut world = hecs::World::new();
        let matching = world.spawn((Health(7),));
        let non_matching = world.spawn(()); // no Health

        let mut query = make_query::<&Health>(&world);
        assert_eq!(query.get(matching).map(|h| h.0), Some(7));
        assert!(query.get(non_matching).is_none());
    }

    #[test]
    fn get_can_be_called_more_than_once_on_the_same_query() {
        let mut world = hecs::World::new();
        let a = world.spawn((Health(1),));
        let b = world.spawn((Health(2),));

        let mut query = make_query::<&Health>(&world);
        assert_eq!(query.get(a).map(|h| h.0), Some(1));
        assert_eq!(query.get(b).map(|h| h.0), Some(2));
    }

    #[test]
    fn with_and_without_chain_and_narrow_by_component_presence() {
        let mut world = hecs::World::new();
        let alive_enemy = world.spawn((Health(1), Enemy));
        world.spawn((Health(1), Enemy, Dead));
        world.spawn((Health(1),));

        let query = make_query::<&Health>(&world);
        let mut narrowed = query.with::<&Enemy>().without::<&Dead>();

        assert_eq!(narrowed.iter().count(), 1);
        assert!(narrowed.get(alive_enemy).is_some());
    }

    #[test]
    fn single_panics_on_zero_or_multiple_matches_get_single_does_not() {
        let mut world = hecs::World::new();

        assert!(make_query::<&Health>(&world).get_single().is_none());

        world.spawn((Health(1),));
        assert_eq!(make_query::<&Health>(&world).single().0, 1);

        world.spawn((Health(2),));
        assert!(make_query::<&Health>(&world).get_single().is_none());
    }
}