unlit3d 0.1.0-dev.3

The high-level WebGPU rendering API over unlit_wgpu and unlit_ecs: ECS components, frame sources, input, UI and winit presentation.
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
//! Frame behaviours: what a frame is made of, as components.
//!
//! The other behaviour families react to an event. A frame behaviour *is* the
//! frame: it runs once per dispatch, so a windowed application's frame loop is
//! one dispatch plus whatever the behaviours queued. Extending the frame is
//! spawning another behaviour, not editing a function.
//!
//! One family: [`OnFrame`] is the frame itself, dispatched by whatever owns
//! the world — a windowed application's host world, or a `Scene` advancing the
//! world it drives. A behaviour spawned with [`OnFrame::new`] states no order;
//! one whose reads or writes another depends on states the order at both ends
//! with [`OnFrame::with_order`]. unlit3d declares no order values of its own,
//! so a frame is extended by spawning behaviours, never by editing a list.
//!
//! Like every other behaviour, a frame behaviour runs with `&World`, so a
//! structural change goes through [`unlit_ecs::Scope::queue`] and lands when the driver
//! applies after the dispatch. A behaviour that needs the rest of the frame
//! skipped sets [FrameSkip], which its siblings read; [dispatch_frame] clears it
//! before the first behaviour runs, so every frame starts whole.

pub(crate) use unlit_ecs::{Entity, World};

/// One frame's context: what changes from frame to frame and is not world
/// state.
///
/// A frame behaviour receives it as its event, so it can tell how long the
/// frame was, which one it is, and what size the content is drawn at.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Frame {
    /// The seconds since the previous frame.
    pub delta_time: f32,
    /// The frame's index, counting from zero.
    pub index: u32,
    /// The size the content is drawn at, in pixels.
    pub size: (u32, u32),
}

/// How much time has passed, as the frame loop counts it.
///
/// [`spawn_context`](crate::source::spawn_context) puts one in the world's
/// shared subtree, so every source reads the same clock, and
/// [`dispatch_frame`] advances it once per frame, before any behaviour runs.
/// A source that draws with time — an animation, a shader's clock — reads this
/// rather than counting its own builds: a source may be built once per pass,
/// and time must not run faster because a frame has more passes.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct FrameClock {
    /// The seconds since the first frame.
    pub time: f32,
    /// The seconds the current frame took.
    pub delta_time: f32,
    /// The current frame's index, counting from zero.
    pub index: u32,
}

impl FrameClock {
    /// Move the clock on to `frame`.
    ///
    /// The clock follows the frame loop's own count rather than counting
    /// builds: `index` and `delta_time` are what the loop states, and `time`
    /// is the sum of the deltas it has stated.
    pub fn advance(&mut self, delta_time: f32, index: u32) {
        self.time += delta_time;
        self.delta_time = delta_time;
        self.index = index;
    }
}

/// When a frame behaviour runs, relative to the others.
///
/// Lower runs first. Behaviours at the same order have no order between them:
/// the dispatch promises nothing about which of them runs first, so a behaviour
/// whose reads or writes another depends on states a different order with
/// [`OnFrame::with_order`]. The default is the band a behaviour spawned with
/// [`OnFrame::new`] joins.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
pub struct FrameBehaviourOrder(pub i32);

/// A callback that runs once for the entity it is spawned on.
pub type FrameCallback = Box<dyn FnMut(&World, Entity, &mut Frame)>;

/// Whether this frame has been short-circuited.
///
/// The frame's behaviours are independent components with no shared stack, so
/// one that cannot carry the frame further sets this and its later siblings
/// read it and return. A sibling that reads the flag has to run after the one
/// that sets it, so it states a later order with [`OnFrame::with_order`]: the
/// same order would leave the two to chance.
///
/// Spawn one to take part; a world without one has nothing to skip.
#[derive(Debug, Default)]
pub struct FrameSkip(pub bool);

impl FrameSkip {
    /// Mark the frame as skipped.
    ///
    /// A no-op in a world that never spawned a [FrameSkip].
    pub fn skip(world: &World) {
        Self::set(world, true);
    }

    /// Whether the frame has been skipped.
    #[must_use]
    pub fn is_skipped(world: &World) -> bool {
        world
            .root_scope()
            .query::<&FrameSkip>()
            .any(|frame_skip| frame_skip.0)
    }

    /// Clear the flag, readying the frame for its behaviours.
    fn reset(world: &World) {
        Self::set(world, false);
    }

    /// Set the flag on every [FrameSkip] in the world.
    fn set(world: &World, value: bool) {
        for entity in Self::entities(world) {
            let _ = world
                .root_scope()
                .query_one::<&mut FrameSkip>(entity)
                .map(|mut skip| skip.0 = value);
        }
    }

    /// The entities carrying a [FrameSkip], collected before any is borrowed
    /// mutably.
    fn entities(world: &World) -> Vec<Entity> {
        world
            .root_scope()
            .query::<(&FrameSkip, Entity)>()
            .map(|(_frame_skip, entity)| entity)
            .collect()
    }
}

/// A component that runs once per frame.
///
/// Implemented by the `frame_behaviour!` macro for each family; a caller adds a
/// behaviour by spawning one of the family's components, not by implementing
/// this itself.
pub trait FrameBehaviour: 'static {
    /// The order this behaviour runs in.
    fn order(&self) -> FrameBehaviourOrder;

    /// Run this behaviour for `entity` with `frame`.
    fn run(&mut self, world: &World, entity: Entity, frame: &mut Frame);
}

/// The state every frame behaviour family shares: its callback and its order.
pub(crate) struct BehaviourSlot {
    callback: FrameCallback,
    order: FrameBehaviourOrder,
}

impl BehaviourSlot {
    fn new(order: FrameBehaviourOrder, callback: FrameCallback) -> Self {
        Self { callback, order }
    }

    fn order(&self) -> FrameBehaviourOrder {
        self.order
    }

    fn run(&mut self, world: &World, entity: Entity, frame: &mut Frame) {
        (self.callback)(world, entity, frame);
    }
}

/// Declares one frame behaviour family.
macro_rules! frame_behaviour {
    ($name:ident, $doc:expr) => {
        #[doc = $doc]
        pub struct $name($crate::frame::BehaviourSlot);

        impl $name {
            #[doc = concat!("Wrap `f` as an [`", stringify!($name), "`].")]
            ///
            /// It joins the band that states no order: it runs after every
            /// behaviour ordered before that band and before every behaviour
            /// ordered after it, and the dispatch promises nothing about the
            /// order within the band. State an order with `with_order` when
            /// another behaviour's reads or writes depend on it.
            pub fn new(
                f: impl FnMut(
                    &$crate::frame::World,
                    $crate::frame::Entity,
                    &mut $crate::frame::Frame,
                ) + 'static,
            ) -> Self {
                Self($crate::frame::BehaviourSlot::new(
                    $crate::frame::FrameBehaviourOrder::default(),
                    Box::new(f),
                ))
            }

            #[doc = concat!("Wrap `f` as an [`", stringify!($name), "`] that runs at `order`.")]
            ///
            /// For a behaviour whose reads or writes another behaviour depends
            /// on: stating a different order at both ends is what makes the
            /// dependency hold, since two behaviours at the same order have no
            /// order between them.
            pub fn with_order(
                order: $crate::frame::FrameBehaviourOrder,
                f: impl FnMut(
                    &$crate::frame::World,
                    $crate::frame::Entity,
                    &mut $crate::frame::Frame,
                ) + 'static,
            ) -> Self {
                Self($crate::frame::BehaviourSlot::new(order, Box::new(f)))
            }

            /// The order this behaviour runs in.
            pub fn order(&self) -> $crate::frame::FrameBehaviourOrder {
                self.0.order()
            }

            /// Run this behaviour for `entity` with `frame`.
            pub fn run(
                &mut self,
                world: &$crate::frame::World,
                entity: $crate::frame::Entity,
                frame: &mut $crate::frame::Frame,
            ) {
                self.0.run(world, entity, frame);
            }
        }

        impl $crate::frame::FrameBehaviour for $name {
            fn order(&self) -> $crate::frame::FrameBehaviourOrder {
                self.0.order()
            }

            fn run(
                &mut self,
                world: &$crate::frame::World,
                entity: $crate::frame::Entity,
                frame: &mut $crate::frame::Frame,
            ) {
                self.0.run(world, entity, frame);
            }
        }
    };
}

frame_behaviour!(
    OnFrame,
    "Runs once per frame of a windowed application.\n\nDispatch it with [`dispatch_frame`]."
);

/// Run every [`OnFrame`] in `world`, in resolved order, then apply what they
/// queued.
///
/// Any [FrameSkip] is cleared first, so a frame that was short-circuited does
/// not stay short-circuited for the next one. Every [`FrameClock`] then moves
/// on to this frame, before the first behaviour reads it.
///
/// What the behaviours queued is applied afterwards. A command that fails is
/// logged, because the frame loop has no caller to answer.
pub fn dispatch_frame(world: &mut World, frame: &mut Frame) {
    FrameSkip::reset(world);
    world
        .root_scope()
        .query::<&mut FrameClock>()
        .for_each(|mut clock| clock.advance(frame.delta_time, frame.index));
    dispatch::<OnFrame>(world, frame);
    // A frame keeps coming whatever a queued command made of itself, and the
    // caller of a frame has nowhere to report the failure to, so it is logged
    // rather than dropped.
    if let Err(error) = world.apply() {
        log::error!("a command queued by a behaviour failed: {error}");
    }
}

/// Run every `B` in `world`, sorted by order alone.
///
/// Behaviours that state no order sort equal, and the sort is unstable, so the
/// dispatch promises nothing about which of them runs first: a behaviour that
/// depends on another states a different order. A callback must not change the
/// frame's behaviour set: the list is resolved before the first one runs, and a
/// change landing inside the dispatch would leave it stale. Queue structural
/// work instead; the driver applies it after the dispatch.
fn dispatch<B: FrameBehaviour>(world: &World, frame: &mut Frame) {
    let mut order: Vec<(FrameBehaviourOrder, Entity)> = world
        .root_scope()
        .query::<(&B, Entity)>()
        .map(|(b, entity)| (b.order(), entity))
        .collect();
    order.sort_unstable_by_key(|(order, _entity)| *order);
    for (_, entity) in order {
        world
            .root_scope()
            .query_one::<&mut B>(entity)
            .map(|mut behaviour| behaviour.run(world, entity, frame))
            .unwrap_or_else(|_| panic!("the behaviour entity exists: {entity:?}"));
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::cell::Cell;
    use std::cell::RefCell;
    use std::rc::Rc;
    use unlit_ecs::bundle;

    fn frame() -> Frame {
        Frame {
            delta_time: 0.0,
            index: 0,
            size: (0, 0),
        }
    }

    /// A later order, for the tests that state one after the default band.
    const END: FrameBehaviourOrder = FrameBehaviourOrder(100);

    /// An earlier order, for the tests that state one before the default band.
    const START: FrameBehaviourOrder = FrameBehaviourOrder(-100);

    #[test]
    fn behaviours_run_in_their_declared_order() {
        let mut world = World::new();
        let log: Rc<RefCell<Vec<i32>>> = Rc::new(RefCell::new(Vec::new()));
        let later = {
            let log = log.clone();
            OnFrame::with_order(FrameBehaviourOrder(10), move |_world, _entity, _frame| {
                log.borrow_mut().push(2)
            })
        };
        let earlier = {
            let log = log.clone();
            OnFrame::with_order(FrameBehaviourOrder(5), move |_world, _entity, _frame| {
                log.borrow_mut().push(1)
            })
        };
        world.root_scope_mut().spawn(bundle![later]);
        world.root_scope_mut().spawn(bundle![earlier]);
        dispatch_frame(&mut world, &mut frame());
        assert_eq!(*log.borrow(), vec![1, 2]);
    }

    /// The band that states no order runs between the orders that state one,
    /// whatever order the three were spawned in. Nothing is asserted about the
    /// order within the band: the dispatch promises none.
    #[test]
    fn the_default_band_runs_between_the_stated_orders() {
        let mut world = World::new();
        let log: Rc<RefCell<Vec<&'static str>>> = Rc::new(RefCell::new(Vec::new()));
        for (order, name) in [(Some(END), "end"), (None, "update"), (Some(START), "start")] {
            let log = log.clone();
            let behaviour = match order {
                Some(order) => OnFrame::with_order(order, move |_world, _entity, _frame| {
                    log.borrow_mut().push(name)
                }),
                None => OnFrame::new(move |_world, _entity, _frame| log.borrow_mut().push(name)),
            };
            world.root_scope_mut().spawn(bundle![behaviour]);
        }
        dispatch_frame(&mut world, &mut frame());
        assert_eq!(*log.borrow(), vec!["start", "update", "end"]);
    }

    #[test]
    fn a_behaviour_receives_the_frame() {
        let mut world = World::new();
        let seen: Rc<RefCell<Option<Frame>>> = Rc::new(RefCell::new(None));
        {
            let seen = seen.clone();
            world
                .root_scope_mut()
                .spawn(bundle![OnFrame::new(move |_world, _entity, frame| {
                    *seen.borrow_mut() = Some(*frame);
                }),]);
        }
        let mut frame = Frame {
            delta_time: 0.5,
            index: 7,
            size: (320, 240),
        };
        dispatch_frame(&mut world, &mut frame);
        assert_eq!(
            *seen.borrow(),
            Some(Frame {
                delta_time: 0.5,
                index: 7,
                size: (320, 240)
            })
        );
    }

    #[test]
    fn a_frame_behaviour_may_advance_the_index() {
        let mut world = World::new();
        world
            .root_scope_mut()
            .spawn(bundle![OnFrame::new(|_world, _entity, frame| {
                frame.index += 1;
            }),]);
        let mut frame = frame();
        dispatch_frame(&mut world, &mut frame);
        assert_eq!(frame.index, 1);
    }

    #[test]
    fn dispatch_applies_what_a_behaviour_queued() {
        struct Marker;
        let mut world = World::new();
        world
            .root_scope_mut()
            .spawn(bundle![OnFrame::new(|world, _entity, _frame| {
                let _ = world.root_scope().queue().spawn(bundle![Marker]);
            }),]);
        dispatch_frame(&mut world, &mut frame());
        assert_eq!(world.root_scope().query::<&Marker>().count(), 1);
    }

    /// A stated order runs after the default band, however the two were
    /// spawned.
    #[test]
    fn a_stated_order_runs_after_the_default_band() {
        let mut world = World::new();
        let log: Rc<RefCell<Vec<&'static str>>> = Rc::new(RefCell::new(Vec::new()));
        {
            let log = log.clone();
            world.root_scope_mut().spawn(bundle![OnFrame::with_order(
                END,
                move |_world, _entity, _frame| {
                    log.borrow_mut().push("end");
                }
            ),]);
        }
        {
            let log = log.clone();
            world
                .root_scope_mut()
                .spawn(bundle![OnFrame::new(move |_world, _entity, _frame| {
                    log.borrow_mut().push("update");
                }),]);
        }
        dispatch_frame(&mut world, &mut frame());
        assert_eq!(*log.borrow(), vec!["update", "end"]);
    }

    #[test]
    fn skip_marks_the_frame_and_is_skipped_reads_it() {
        let mut world = World::new();
        world.root_scope_mut().spawn(bundle![FrameSkip::default()]);
        assert!(!FrameSkip::is_skipped(&world));
        FrameSkip::skip(&world);
        assert!(FrameSkip::is_skipped(&world));
    }

    #[test]
    fn skip_is_a_no_op_without_a_flag_component() {
        let world = World::new();
        FrameSkip::skip(&world);
        assert!(!FrameSkip::is_skipped(&world));
    }

    /// A frame that short-circuited does not leave the next one short-circuited:
    /// the dispatch clears the flag before the first behaviour runs.
    #[test]
    fn dispatch_clears_a_skip_left_by_the_previous_frame() {
        let mut world = World::new();
        let first = Rc::new(Cell::new(true));
        world.root_scope_mut().spawn(bundle![FrameSkip::default()]);
        {
            let first = first.clone();
            world
                .root_scope_mut()
                .spawn(bundle![OnFrame::new(move |world, _entity, _frame| {
                    assert!(!FrameSkip::is_skipped(world), "the flag starts whole");
                    if first.replace(false) {
                        FrameSkip::skip(world);
                    }
                }),]);
        }
        dispatch_frame(&mut world, &mut frame());
        assert!(FrameSkip::is_skipped(&world));
        dispatch_frame(&mut world, &mut frame());
        assert!(!FrameSkip::is_skipped(&world));
    }

    /// The clock follows the frame the loop states, so a frame that takes
    /// longer moves the clock further, and a frame index the loop skips over is
    /// not counted twice.
    #[test]
    fn the_clock_follows_the_frame_it_is_dispatched_with() {
        let mut world = World::new();
        let clock = world.root_scope_mut().spawn(bundle![FrameClock::default()]);
        let seen: Rc<RefCell<Vec<FrameClock>>> = Rc::new(RefCell::new(Vec::new()));
        {
            let seen = seen.clone();
            world
                .root_scope_mut()
                .spawn(bundle![OnFrame::new(move |world, _entity, _frame| {
                    let clock = *world
                        .root_scope()
                        .query_one::<&FrameClock>(clock)
                        .expect("the clock is spawned");
                    seen.borrow_mut().push(clock);
                }),]);
        }

        let mut frame = Frame {
            delta_time: 0.25,
            index: 3,
            size: (0, 0),
        };
        dispatch_frame(&mut world, &mut frame);
        frame.delta_time = 0.5;
        frame.index = 4;
        dispatch_frame(&mut world, &mut frame);

        let seen = seen.borrow();
        assert_eq!(
            seen[0],
            FrameClock {
                time: 0.25,
                delta_time: 0.25,
                index: 3,
            },
            "the first frame's clock starts from zero"
        );
        assert_eq!(
            seen[1],
            FrameClock {
                time: 0.75,
                delta_time: 0.5,
                index: 4,
            },
            "time accumulates the deltas the loop states"
        );
    }

    /// A world with no clock still dispatches: the clock is the application's to
    /// spawn, and nothing in the dispatch requires one.
    #[test]
    fn dispatch_without_a_clock_still_runs_every_behaviour() {
        let mut world = World::new();
        let ran = Rc::new(Cell::new(0));
        {
            let ran = ran.clone();
            world
                .root_scope_mut()
                .spawn(bundle![OnFrame::new(move |_world, _entity, _frame| {
                    ran.set(ran.get() + 1);
                }),]);
        }
        dispatch_frame(&mut world, &mut frame());
        assert_eq!(ran.get(), 1);
    }
}