concinnity-core 0.19.1

Runtime vocabulary for the Concinnity engine: GPU layouts, ECS components, registry, CPU kernels
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
//! Runtime entity spawn: instantiate a copy of an existing placement at a new
//! transform and give it the components and (optionally) the Lifetime the copy
//! needs to live in the world.
//!
//! What a copy's draw slot is comes from a host, through the `clone_slot` /
//! `acquire_slot` seams: a slot index is a renderer's to allocate, and it is
//! the one thing here that is. Everything else -- which components a copy
//! carries, when a Spawner is due, when a Lifetime is up -- is the world's, so
//! it lives with the world.

use crate::memory::InlineVec;

use crate::components::{
    BodyDynamics, Collider, GlobalTransform, Lifetime, MeshRenderer, ModelRenderer, Pickup,
    PropInstance, RenderHandle, SkeletonPose, Spawner, Transform,
};
use crate::ecs::asset_id::AssetId;
use crate::ecs::{Entity, EntityByName, FrameVec, PipelineContext};

/// Instantiate a runtime copy of `template`'s renderable: clone each of its
/// backend draw slots at `transform` through `clone_slot`, then build a new
/// entity carrying the cloned slots, a copy of the template's renderer, the
/// placement, and an optional Lifetime.
///
/// `clone_slot(src_draw_idx, model)` returns the new backend slot index (a
/// vacated slot reused, or a freshly appended one); it is the seam a host wires
/// to its own allocator. When `name` is Some the new entity is registered under
/// it so it can later be addressed by name like an authored placement;
/// transient spawns (a Spawner's churn) pass None to avoid interning a name per
/// spawn. Returns the new entity, or None when the template has no draw slots to
/// copy or a clone fails.
pub fn spawn_from_template(
    ctx: &mut PipelineContext,
    template: Entity,
    name: Option<AssetId>,
    transform: Transform,
    lifetime: Option<f32>,
    mut clone_slot: impl FnMut(usize, [[f32; 4]; 4]) -> Option<usize>,
) -> Option<Entity> {
    let src_slots: InlineVec<u32> = ctx.get::<RenderHandle>(template).map(|h| h.draws.clone())?;
    if src_slots.is_empty() {
        return None;
    }
    let model = transform.model_matrix();
    let mut draws = InlineVec::new();
    for src in src_slots {
        let new_slot = clone_slot(src as usize, model)?;
        draws.push(new_slot as u32);
    }

    // Copy whichever renderer the template carries so the new entity is a
    // first-class renderable for every system that joins on it, plus its
    // physics components so the physics system builds it a body.
    let mesh_renderer = ctx.get::<MeshRenderer>(template).cloned();
    let model_renderer = ctx.get::<ModelRenderer>(template).cloned();
    let collider = ctx.get::<Collider>(template).cloned();
    let body_dynamics = ctx.get::<BodyDynamics>(template).copied();
    let pickup = ctx.get::<Pickup>(template).is_some();
    let prop_instance = ctx.get::<PropInstance>(template).is_some();

    let entity = ctx.components.spawn();
    ctx.insert(entity, transform);
    ctx.insert(entity, GlobalTransform(model));
    ctx.insert(entity, RenderHandle { draws });
    if let Some(renderer) = mesh_renderer {
        ctx.insert(entity, renderer);
    } else if let Some(renderer) = model_renderer {
        ctx.insert(entity, renderer);
    }
    if let Some(collider) = collider {
        ctx.insert(entity, collider);
    }
    if let Some(body_dynamics) = body_dynamics {
        ctx.insert(entity, body_dynamics);
    }
    if pickup {
        ctx.insert(entity, Pickup);
    }
    if prop_instance {
        ctx.insert(entity, PropInstance);
    }
    if let Some(secs) = lifetime {
        ctx.insert(entity, Lifetime { remaining: secs });
    }
    if let Some(name) = name
        && let Some(by_name) = ctx.resource_mut::<EntityByName>()
    {
        by_name.0.insert(name, entity);
    }
    Some(entity)
}

/// Instantiate a runtime copy of a skinned `template` (a SkinnedMesh's
/// SkeletonPose entity) at `transform`.
///
/// Unlike the static path, a skinned instance is not a cloned draw slot: it
/// claims one of the template's pre-reserved hidden bind-pose copies through
/// `acquire_slot`, which reveals it and returns its skinned index. The new
/// entity carries its own SkeletonPose (so an animation system drives it, keyed
/// on the shared mesh id, in lockstep with the template), a Transform (so the
/// per-frame model push can move it), and an optional Lifetime. When `name` is
/// Some the instance is registered so it can be addressed (e.g. despawned) by
/// name. Returns the new entity, or None when the template is not skinned or
/// its instance pool is exhausted.
pub fn spawn_skinned_from_template(
    ctx: &mut PipelineContext,
    template: Entity,
    name: Option<AssetId>,
    transform: Transform,
    lifetime: Option<f32>,
    mut acquire_slot: impl FnMut(usize, [[f32; 4]; 4]) -> Option<usize>,
) -> Option<Entity> {
    let template_pose = ctx.get::<SkeletonPose>(template)?;
    let model = transform.model_matrix();
    let skinned_index = acquire_slot(template_pose.skinned_index, model)?;
    let pose = template_pose.clone_for_slot(skinned_index);

    let prop_instance = ctx.get::<PropInstance>(template).is_some();

    let entity = ctx.components.spawn();
    ctx.insert(entity, transform);
    ctx.insert(entity, pose);
    if prop_instance {
        ctx.insert(entity, PropInstance);
    }
    if let Some(secs) = lifetime {
        ctx.insert(entity, Lifetime { remaining: secs });
    }
    if let Some(name) = name
        && let Some(by_name) = ctx.resource_mut::<EntityByName>()
    {
        by_name.0.insert(name, entity);
    }
    Some(entity)
}

/// One spawn a Spawner is due to emit this step: the template to copy, where to
/// place it, and how long the copy should live.
///
/// Returned by [`tick_spawners`] for the caller to route through
/// [`spawn_from_template`] with the live backend, the same way
/// [`tick_lifetimes`] returns expiries for the caller to despawn.
#[derive(Clone, Copy)]
pub struct DueSpawn {
    /// The placement to copy.
    pub template: AssetId,
    /// Where the copy is placed.
    pub transform: Transform,
    /// Seconds the copy lives for, or `None` when it is not auto-removed.
    pub lifetime: Option<f32>,
}

/// Advance every Spawner's clock by `dt` and return the spawns now due, in
/// frame scratch.
///
/// A spawner emits one copy per whole `interval` elapsed (so a long frame that
/// crosses several intervals catches up), at the spawner entity's own
/// Transform. A non-positive interval is inert (never spawns). A zero
/// `lifetime` means the copy is not auto-removed; otherwise it carries that
/// countdown.
pub fn tick_spawners<'a>(ctx: &mut PipelineContext<'a>, dt: f32) -> FrameVec<'a, DueSpawn> {
    let frame = ctx.frame;
    // Advance every spawner's clock in place, recording only the ones that
    // crossed at least one interval this step (template, lifetime, and how many
    // copies are due). Every spawner could fire, so the reservation is exact.
    let mut fired = frame.vec::<(Entity, AssetId, f32, u32)>(ctx.query::<Spawner>().len());
    for (entity, spawner) in ctx.query_mut_with_entity::<Spawner>() {
        if spawner.interval <= 0.0 {
            continue;
        }
        spawner.elapsed += dt;
        let mut count = 0;
        while spawner.elapsed >= spawner.interval {
            spawner.elapsed -= spawner.interval;
            spawner.count += 1;
            count += 1;
        }
        if count > 0 {
            fired.push((entity, spawner.template, spawner.lifetime, count));
        }
    }
    // Resolve each fired spawner's placement (its Transform) now that the mutable
    // Spawner borrow is released, and expand to one DueSpawn per copy.
    let mut due = frame.vec::<DueSpawn>(
        fired
            .iter()
            .map(|&(.., count)| count as usize)
            .sum::<usize>(),
    );
    for &(entity, template, lifetime, count) in fired.iter() {
        let transform = ctx.get::<Transform>(entity).copied().unwrap_or_default();
        for _ in 0..count {
            due.push(DueSpawn {
                template,
                transform,
                lifetime: (lifetime > 0.0).then_some(lifetime),
            });
        }
    }
    due
}

/// Decrement every Lifetime by `dt` and return the entities whose countdown
/// reached zero this step, in frame scratch, for the caller to despawn.
///
/// Entities still alive keep their decremented remaining. Returning the expired
/// list (rather than despawning inline, which would mutate storage
/// mid-iteration) lets the caller route each expiry through the same despawn
/// cascade a DespawnRequest uses.
pub fn tick_lifetimes<'a>(ctx: &mut PipelineContext<'a>, dt: f32) -> FrameVec<'a, Entity> {
    let mut expired = ctx.frame.vec::<Entity>(ctx.query::<Lifetime>().len());
    for (entity, life) in ctx.query_mut_with_entity::<Lifetime>() {
        life.remaining -= dt;
        if life.remaining <= 0.0 {
            expired.push(entity);
        }
    }
    expired
}

#[cfg(test)]
mod tests {
    use super::*;
    use alloc::collections::BTreeMap;
    use alloc::vec;
    use alloc::vec::Vec;

    use crate::ecs::{
        Arena, ComponentStorage, FrameContext, NoPayloads, Resources, SkinnedMeshHandle,
    };
    use crate::gfx::profile::FrameProfile;
    use crate::gfx::skeleton::Skeleton;

    // Build an isolated PipelineContext over fresh storage, mirroring the
    // despawn tests, so the spawn/despawn loop can run without a backend.
    fn run<R>(body: impl FnOnce(&mut PipelineContext) -> R) -> R {
        let mut components = ComponentStorage::default();
        let mut blob = NoPayloads;
        let mut profile = FrameProfile::default();
        let mut resources = Resources::new();
        let scratch = Arena::with_capacity(64 * 1024);
        let mut ctx = PipelineContext {
            components: &mut components,
            blob: &mut blob,
            profile: &mut profile,
            resources: &mut resources,
            frame: FrameContext::new(&scratch),
        };
        body(&mut ctx)
    }

    // A `clone_slot` seam standing in for a renderer's draw-slot allocator: it
    // pops a vacated slot before growing, which is the property the recycle
    // tests are about.
    #[derive(Default)]
    struct Slots {
        free: Vec<usize>,
        len: usize,
    }

    impl Slots {
        fn with_len(len: usize) -> Slots {
            Slots {
                free: Vec::new(),
                len,
            }
        }

        fn allocate(&mut self) -> usize {
            match self.free.pop() {
                Some(slot) => slot,
                None => {
                    self.len += 1;
                    self.len - 1
                }
            }
        }

        fn free(&mut self, slot: usize) {
            self.free.push(slot);
        }
    }

    // The `acquire_slot` seam's stand-in: the pre-reserved hidden copies a
    // skinned template owns, and which of them are currently free.
    #[derive(Default)]
    struct Pool {
        free: BTreeMap<usize, Vec<usize>>,
        owner: BTreeMap<usize, usize>,
    }

    impl Pool {
        fn reserve(&mut self, template: usize, instance: usize) {
            self.owner.insert(instance, template);
            self.free.entry(template).or_default().push(instance);
        }

        fn acquire(&mut self, template: usize) -> Option<usize> {
            self.free.get_mut(&template).and_then(|slots| slots.pop())
        }

        fn release(&mut self, instance: usize) {
            if let Some(&template) = self.owner.get(&instance) {
                self.free.entry(template).or_default().push(instance);
            }
        }
    }

    #[test]
    fn spawned_copy_carries_the_template_physics_components() {
        run(|ctx| {
            ctx.insert_resource(EntityByName::default());

            let template = ctx.components.spawn();
            ctx.insert(template, Transform::default());
            ctx.insert(
                template,
                MeshRenderer {
                    mesh: None,
                    material: None,
                    texture: None,
                    cull_distance: 0.0,
                },
            );
            ctx.insert(template, RenderHandle { draws: [0].into() });
            ctx.insert(
                template,
                Collider(crate::components::PropCollider {
                    radius: 0.4,
                    ..Default::default()
                }),
            );
            ctx.insert(
                template,
                BodyDynamics {
                    mass: 2.5,
                    ..Default::default()
                },
            );
            ctx.insert(template, Pickup);

            let mut alloc = Slots::with_len(1);
            let spawned = spawn_from_template(
                ctx,
                template,
                None,
                Transform::default(),
                None,
                |_src, _model| Some(alloc.allocate()),
            )
            .expect("spawn");

            assert_eq!(
                ctx.get::<Collider>(spawned).map(|c| c.0.radius),
                Some(0.4),
                "the collider is copied"
            );
            assert_eq!(
                ctx.get::<BodyDynamics>(spawned).map(|b| b.mass),
                Some(2.5),
                "the dynamic-body parameters are copied"
            );
            assert!(ctx.get::<Pickup>(spawned).is_some(), "the tag is copied");
        });
    }

    #[test]
    fn freed_draw_slot_is_reused_by_the_next_spawn() {
        run(|ctx| {
            ctx.insert_resource(EntityByName::default());

            // A template placement occupying draw slot 0.
            let template = ctx.components.spawn();
            ctx.insert(template, Transform::default());
            ctx.insert(
                template,
                MeshRenderer {
                    mesh: None,
                    material: None,
                    texture: None,
                    cull_distance: 0.0,
                },
            );
            ctx.insert(template, RenderHandle { draws: [0].into() });

            // The backend starts with one live slot (the template's).
            let mut alloc = Slots::with_len(1);

            // First spawn appends a fresh slot past the template's.
            let first = spawn_from_template(
                ctx,
                template,
                Some(AssetId(1)),
                Transform::default(),
                Some(0.5),
                |_src, _model| Some(alloc.allocate()),
            )
            .expect("first spawn");
            let first_slot = ctx.get::<RenderHandle>(first).unwrap().draws.clone();
            assert_eq!(first_slot, vec![1], "first spawn appended slot 1");

            // Its Lifetime expires; the expiry frees the slot like a despawn's
            // retire -> free does, then despawns the entity.
            let expired = tick_lifetimes(ctx, 1.0);
            assert_eq!(&*expired, &[first], "the short-lived spawn expired");
            let freed: Vec<u32> = ctx.get::<RenderHandle>(first).unwrap().draws.to_vec();
            for slot in &freed {
                alloc.free(*slot as usize);
            }
            ctx.despawn(first);
            assert!(ctx.get::<RenderHandle>(first).is_none(), "first despawned");

            // The next spawn reuses the freed slot instead of growing the vec.
            let second = spawn_from_template(
                ctx,
                template,
                Some(AssetId(2)),
                Transform::default(),
                None,
                |_src, _model| Some(alloc.allocate()),
            )
            .expect("second spawn");
            let second_slot = ctx.get::<RenderHandle>(second).unwrap().draws.clone();
            assert_eq!(
                second_slot, freed,
                "the freed draw slot must be recycled by the next spawn"
            );
        });
    }

    #[test]
    fn skinned_spawn_claims_and_recycles_a_pooled_slot() {
        run(|ctx| {
            ctx.insert_resource(EntityByName::default());

            // A skinned template at draw slot 0 with two pre-reserved hidden
            // copies (slots 1 and 2) in the pool.
            let template = ctx.components.spawn();
            ctx.insert(
                template,
                SkeletonPose::new(SkinnedMeshHandle(10), 0, Skeleton::new(Vec::new())),
            );
            let mut pool = Pool::default();
            pool.reserve(0, 1);
            pool.reserve(0, 2);

            // The spawn claims a pooled copy and the new entity points at it.
            let first = spawn_skinned_from_template(
                ctx,
                template,
                Some(AssetId(11)),
                Transform::default(),
                Some(0.5),
                |template_idx, _model| pool.acquire(template_idx),
            )
            .expect("first skinned spawn");
            let first_slot = ctx.get::<SkeletonPose>(first).unwrap().skinned_index;
            assert_eq!(
                ctx.get::<SkeletonPose>(first).unwrap().mesh_id,
                SkinnedMeshHandle(10),
                "the instance shares the template's mesh id so it animates with it"
            );

            // Its Lifetime expires; the expiry releases the slot to the pool like
            // a despawn's retire does, then despawns the entity.
            let expired = tick_lifetimes(ctx, 1.0);
            assert_eq!(&*expired, &[first]);
            pool.release(first_slot);
            ctx.despawn(first);

            // The next spawn recycles the freed slot instead of a fresh one.
            let second = spawn_skinned_from_template(
                ctx,
                template,
                None,
                Transform::default(),
                None,
                |template_idx, _model| pool.acquire(template_idx),
            )
            .expect("second skinned spawn");
            assert_eq!(
                ctx.get::<SkeletonPose>(second).unwrap().skinned_index,
                first_slot,
                "the freed skinned slot must be recycled by the next spawn"
            );
        });
    }

    #[test]
    fn skinned_spawn_with_exhausted_pool_returns_none() {
        run(|ctx| {
            let template = ctx.components.spawn();
            ctx.insert(
                template,
                SkeletonPose::new(SkinnedMeshHandle(10), 0, Skeleton::new(Vec::new())),
            );
            // A template that reserved no instances has nothing to claim.
            let mut pool = Pool::default();
            let spawned = spawn_skinned_from_template(
                ctx,
                template,
                None,
                Transform::default(),
                None,
                |template_idx, _model| pool.acquire(template_idx),
            );
            assert!(spawned.is_none(), "an exhausted pool drops the spawn");
        });
    }

    #[test]
    fn spawn_registers_the_instance_by_name() {
        run(|ctx| {
            ctx.insert_resource(EntityByName::default());
            let template = ctx.components.spawn();
            ctx.insert(template, Transform::default());
            ctx.insert(template, RenderHandle { draws: [0].into() });
            let mut alloc = Slots::with_len(1);

            let spawned = spawn_from_template(
                ctx,
                template,
                Some(AssetId(42)),
                Transform::default(),
                None,
                |_src, _model| Some(alloc.allocate()),
            )
            .expect("spawn");

            let by_name = ctx.resource::<EntityByName>().unwrap();
            assert_eq!(by_name.get(AssetId(42)), Some(spawned));
        });
    }

    #[test]
    fn spawner_emits_one_copy_per_interval_elapsed() {
        run(|ctx| {
            let spawner = ctx.components.spawn();
            ctx.insert(
                spawner,
                Transform {
                    position: [1.0, 2.0, 3.0],
                    ..Transform::default()
                },
            );
            ctx.insert(
                spawner,
                Spawner {
                    template: AssetId(7),
                    interval: 1.0,
                    lifetime: 2.0,
                    elapsed: 0.0,
                    count: 0,
                },
            );

            // Below the interval: nothing due, but the clock advances.
            assert!(tick_spawners(ctx, 0.5).is_empty());
            // Crossing the interval emits one, carrying the lifetime + template
            // and the spawner's own position.
            let due = tick_spawners(ctx, 0.6);
            assert_eq!(due.len(), 1);
            assert_eq!(due[0].template, AssetId(7));
            assert_eq!(due[0].lifetime, Some(2.0));
            assert_eq!(due[0].transform.position, [1.0, 2.0, 3.0]);
            // A long frame crossing several intervals catches up.
            assert_eq!(tick_spawners(ctx, 2.5).len(), 2);
            assert_eq!(ctx.get::<Spawner>(spawner).unwrap().count, 3);
        });
    }

    #[test]
    fn spawner_with_nonpositive_interval_is_inert() {
        run(|ctx| {
            let spawner = ctx.components.spawn();
            ctx.insert(spawner, Transform::default());
            ctx.insert(
                spawner,
                Spawner {
                    template: AssetId(7),
                    interval: 0.0,
                    lifetime: 0.0,
                    elapsed: 0.0,
                    count: 0,
                },
            );
            assert!(tick_spawners(ctx, 100.0).is_empty());
        });
    }

    #[test]
    fn tick_only_expires_elapsed_lifetimes() {
        run(|ctx| {
            let short = ctx.components.spawn();
            ctx.insert(short, Lifetime { remaining: 0.1 });
            let long = ctx.components.spawn();
            ctx.insert(long, Lifetime { remaining: 5.0 });

            let expired = tick_lifetimes(ctx, 0.2);
            assert_eq!(&*expired, &[short], "only the short lifetime expired");
            // The survivor's clock advanced but it is still alive.
            assert_eq!(ctx.get::<Lifetime>(long).unwrap().remaining, 4.8);
        });
    }
}