concinnity-engine 0.18.69

Runtime engine for Concinnity: ECS schedule, graphics, spawn, streaming
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
//! Gate builders for the system table (`define_systems!` in `registry`). Each
//! gate inspects the world's content and returns the constructed system when
//! its gating components are present, or `None` to leave it out of the
//! schedule. `World::start` and `World::system_manifest` both run these same
//! gates, so what the manifest reports and what `start` builds cannot drift.
//!
//! Gates construct their system, so every system constructor must stay cheap
//! and side-effect-free: the manifest probe discards the value, and anything
//! heavy (device acquisition, payload reads) belongs in `System::init`.

use crate::ecs::World;

// OverlaySystem: paired with GraphicsSystem (same gate) -- it shapes the
// overlay draw list graphics submits. Scheduled first so the menu state it
// publishes gates every later system this same tick.
pub(crate) fn overlay(world: &World) -> Option<crate::gfx::overlay::OverlaySystem> {
    world
        .query::<crate::components::GraphicsConfig>()
        .next()
        .map(|_| crate::gfx::overlay::OverlaySystem::new())
}

// BehaviorSystem: present whenever the world declares any `Behavior`.
// Scheduled before SpawnSystem / SettingsSystem / StorySystem / AudioSystem so
// the requests its firing bodies emit are drained the same tick. Built with
// what this host lends it: the job pool and a file-backed state store.
pub(crate) fn behavior(world: &World) -> Option<concinnity_core::behavior::BehaviorSystem> {
    world
        .query::<crate::components::Behavior>()
        .next()
        .map(|_| crate::behavior::build())
}

// SpawnSystem: paired with GraphicsSystem (same gate) -- its churn retires and
// clones the GPU draw slots graphics owns. Scheduled immediately before it so
// a despawn is applied before the transform push and a spawn reuses slots
// freed this same frame.
pub(crate) fn spawn(world: &World) -> Option<crate::spawn::SpawnSystem> {
    world
        .query::<crate::components::GraphicsConfig>()
        .next()
        .map(|_| crate::spawn::SpawnSystem::new())
}

// SettingsSystem: paired with GraphicsSystem (same gate) -- it applies the
// settings/scene command batches against the backend graphics owns and holds
// the settings snapshot GraphicsSystem's init resolves. Scheduled just before
// GraphicsSystem so a change lands for this frame's submit.
pub(crate) fn settings(world: &World) -> Option<crate::gfx::settings_system::SettingsSystem> {
    world
        .query::<crate::components::GraphicsConfig>()
        .next()
        .map(|_| crate::gfx::settings_system::SettingsSystem::new())
}

// StreamingSystem: paired with GraphicsSystem (same gate) -- it drives the
// streaming pools and publishes the camera-relative screen graphics draws.
// Scheduled immediately before GraphicsSystem so a chunk world's screen rebase is
// ready for this frame's submit and any texture/mesh upload lands before it.
pub(crate) fn streaming(world: &World) -> Option<crate::gfx::streaming_system::StreamingSystem> {
    world
        .query::<crate::components::GraphicsConfig>()
        .next()
        .map(|_| crate::gfx::streaming_system::StreamingSystem::new())
}

// GraphicsSystem: present whenever the world declares a `GraphicsConfig`
// (the render marker).
pub(crate) fn graphics(world: &World) -> Option<crate::gfx::graphics_system::GraphicsSystem> {
    world
        .query::<crate::components::GraphicsConfig>()
        .next()
        .map(|_| crate::gfx::graphics_system::GraphicsSystem::new())
}

// InputSystem: paired with GraphicsSystem (same gate) -- it samples the window
// backend graphics drives. Scheduled immediately after it so the snapshot is
// taken right after the draw (the OS event pump on Metal runs inside
// draw_frame) and is fresh for every consumer below.
pub(crate) fn input(world: &World) -> Option<crate::gfx::input_system::InputSystem> {
    world
        .query::<crate::components::GraphicsConfig>()
        .next()
        .map(|_| crate::gfx::input_system::InputSystem::new())
}

// StatHud: present whenever the world declares a `StatHud`; built from that
// component (the HUD's TextLabel refs).
pub(crate) fn stat_hud(world: &World) -> Option<crate::hud::stat_hud::StatHudSystem> {
    world
        .query::<crate::components::StatHud>()
        .next()
        .cloned()
        .map(crate::hud::stat_hud::StatHudSystem::new)
}

// DebugHud: present whenever the world declares a `DebugHud`, but only in
// developer contexts. Blobs are profile-agnostic (the build injects a
// DebugHud into every rendering world), so the running binary is the one
// place its own profile is knowable: a debug build or a `cn debug` session
// activates the HUD, a release `cn run` leaves it inert.
pub(crate) fn debug_hud(world: &World) -> Option<crate::hud::debug_hud::DebugHudSystem> {
    if !(cfg!(debug_assertions) || crate::app::dev_flags::enabled()) {
        return None;
    }
    world
        .query::<crate::components::DebugHud>()
        .next()
        .cloned()
        .map(crate::hud::debug_hud::DebugHudSystem::new)
}

// LoadingOverlaySystem: present whenever the world declares a `LoadingOverlay`;
// built from that component (its screen + element refs).
pub(crate) fn loading_overlay(
    world: &World,
) -> Option<crate::hud::loading_overlay::LoadingOverlaySystem> {
    world
        .query::<crate::components::LoadingOverlay>()
        .next()
        .cloned()
        .map(crate::hud::loading_overlay::LoadingOverlaySystem::new)
}

// PhysicsSystem: present whenever the world has physics content, namely a
// `PhysicsConfig` (optional floor / terrain tuning), a `RigidBody` (character
// capsule), a `PropBody` (dynamic prop), or a `TriggerVolume` (sensor
// region). Reads the `PhysicsConfig` if present, otherwise a flat-floor
// default.
pub(crate) fn physics(world: &World) -> Option<concinnity_core::physics::PhysicsSystem> {
    let needs = world
        .query::<crate::components::PhysicsConfig>()
        .next()
        .is_some()
        || world.query::<crate::components::RigidBody>().next().is_some()
        || world.query::<crate::components::PropBody>().next().is_some()
        || world
            .query::<crate::components::TriggerVolume>()
            .next()
            .is_some()
        // A skinned mesh with a character capsule needs the rig drive
        // (the CharacterRig itself is published later, by GraphicsSystem
        // init, so gate on the baked resource data).
        || world
            .resource::<crate::resource::SkinnedMeshTable>()
            .is_some_and(|t| t.has_capsule());
    if !needs {
        return None;
    }
    // Cook injects the config into every shipped world with physics content,
    // so the fallback covers worlds built directly (tests, the editor's
    // in-memory path).
    let config = world
        .query::<crate::components::PhysicsConfig>()
        .next()
        .cloned()
        .unwrap_or_default();
    Some(crate::physics::build(config))
}

// The first controlled `Camera3D` picks the controller flavor: no `follow`
// block selects this first-person / fly controller, a `follow` block selects
// the adjacent ThirdPersonSystem entry instead (a camera never gets both). A
// `controller: null` camera opts out entirely (cutscene cameras).
pub(crate) fn camera3d(world: &World) -> Option<crate::gfx::camera_controller::Camera3DSystem> {
    let ctrl = controlled_camera(world)?;
    ctrl.follow
        .is_none()
        .then(|| crate::gfx::camera_controller::Camera3DSystem::new(ctrl))
}

// Counterpart of `camera3d`: the first controlled camera declares a `follow`
// block, so the third-person controller drives it.
pub(crate) fn third_person(world: &World) -> Option<crate::gfx::third_person::ThirdPersonSystem> {
    let ctrl = controlled_camera(world)?;
    ctrl.follow
        .is_some()
        .then(|| crate::gfx::third_person::ThirdPersonSystem::new(&ctrl))
}

fn controlled_camera(world: &World) -> Option<crate::components::CameraController> {
    world
        .query::<crate::components::Camera3D>()
        .find_map(|c| c.controller.clone())
}

// FpsCounter: present whenever the world declares an `FpsCounter`; built from
// that component (its optional TextLabel ref).
pub(crate) fn fps_counter(world: &World) -> Option<crate::hud::fps_counter::FpsCounterSystem> {
    world
        .query::<crate::components::FpsCounter>()
        .next()
        .cloned()
        .map(crate::hud::fps_counter::FpsCounterSystem::new)
}

// AnimationSystem: present whenever the world declares any `Animation` or
// `AnimationGraph`. It drains both at init and writes `SkeletonPose` each
// frame. (A graph without clips is a build error, so the second check
// only matters for hand-assembled worlds.)
pub(crate) fn animation(world: &World) -> Option<crate::gfx::animation::AnimationSystem> {
    let declared = world
        .query::<crate::components::Animation>()
        .next()
        .is_some()
        || world
            .query::<crate::components::AnimationGraph>()
            .next()
            .is_some();
    declared.then(crate::gfx::animation::AnimationSystem::new)
}

// StorySystem: present whenever the world declares a `Story` (a compiled
// story graph). It runs before AudioSystem so its page-audio requests are
// heard the same tick, and before UiInputSystem like every other event
// producer (its screen commands apply next frame).
pub(crate) fn story(world: &World) -> Option<crate::story::StorySystem> {
    world
        .query::<crate::components::Story>()
        .next()
        .cloned()
        .map(crate::story::StorySystem::new)
}

// AudioSystem: present whenever the world declares any `AudioEmitter`
// (positional sound), `AudioCue` (screen-triggered sound), `Story`
// (page-triggered sound), or `Behavior` with a sound node. Its init opens
// an audio device, so a world with none of them stays silent and device-free.
pub(crate) fn audio(world: &World) -> Option<crate::audio::AudioSystem> {
    let needs = world
        .query::<crate::components::AudioEmitter>()
        .next()
        .is_some()
        || world
            .query::<crate::components::AudioCue>()
            .next()
            .is_some()
        || world
            .query::<crate::components::Story>()
            .next()
            .is_some_and(|s| {
                s.nodes.iter().any(|n| {
                    n.choice_music.is_some()
                        || !n.choice_sounds.is_empty()
                        || n.pages
                            .iter()
                            .any(|p| p.music.is_some() || !p.sounds.is_empty())
                })
            })
        || world
            .query::<crate::components::Behavior>()
            .any(crate::components::Behavior::plays_sound);
    if !needs {
        return None;
    }
    // The persisted volumes live in the engine's settings store; resolve them
    // here and hand them to the system so the audio crate stays free of the
    // engine's `Settings` type.
    let audio = crate::config::Settings::load().audio;
    Some(crate::audio::AudioSystem::new(crate::audio::AudioVolumes {
        master: audio.master_volume,
        music: audio.music_volume,
        sfx: audio.sfx_volume,
        voice: audio.voice_volume,
    }))
}

// UiInputSystem: present whenever the world declares any `HitRegion`, `Screen`,
// or `KeyBinding`. It drains all three at init.
pub(crate) fn ui_input(world: &World) -> Option<crate::ui::UiInputSystem> {
    let needs = world
        .query::<crate::components::HitRegion>()
        .next()
        .is_some()
        || world.query::<crate::components::Screen>().next().is_some()
        || world
            .query::<crate::components::KeyBinding>()
            .next()
            .is_some();
    needs.then(crate::ui::UiInputSystem::new)
}

// TextInputSystem: present whenever the world declares any `TextInput`. It
// edits the focused field in place from the frame's typed character and
// caret keys, so it runs after GraphicsSystem deposits `FrameInput`.
pub(crate) fn text_input(world: &World) -> Option<crate::text_input_system::TextInputSystem> {
    world
        .query::<crate::components::TextInput>()
        .next()
        .map(|_| crate::text_input_system::TextInputSystem::new())
}

#[cfg(test)]
mod tests {
    use crate::components::{Camera3D, CameraController, PhysicsConfig, RigidBody};
    use crate::ecs::{SYSTEMS, World};

    fn controlled_camera() -> Camera3D {
        Camera3D {
            fov_y_degrees: 75.0,
            near: 0.05,
            far: 200.0,
            view_matrix: [[0.0; 4]; 4],
            position: [0.0, 1.0, 0.0],
            yaw: 0.0,
            pitch: 0.0,
            desired_move: [0.0; 3],
            jump_requested: false,
            interact_requested: false,
            controller: Some(CameraController::default()),
        }
    }

    // A PhysicsConfig gates the internal physics system on.
    #[test]
    fn physics_config_spawns_internal_system() {
        let mut world = World::new();
        world.add_component(PhysicsConfig::default());
        world.start(SYSTEMS).unwrap();
        let names: Vec<&str> = world.systems().iter().map(|s| s.name()).collect();
        assert_eq!(names, ["PhysicsSystem"]);
    }

    // A RigidBody (character capsule) gates physics on, even with no config.
    #[test]
    fn rigid_body_spawns_internal_system() {
        let mut world = World::new();
        world.add_component(RigidBody::default());
        world.start(SYSTEMS).unwrap();
        let names: Vec<&str> = world.systems().iter().map(|s| s.name()).collect();
        assert_eq!(names, ["PhysicsSystem"]);
    }

    // No physics content (no PhysicsConfig / RigidBody / PropBody) → no system.
    #[test]
    fn no_physics_content_no_system() {
        let mut world = World::new();
        world.start(SYSTEMS).unwrap();
        assert!(world.systems().is_empty());
    }

    // PhysicsSystem runs before Camera3DSystem: it consumes the camera's
    // previous-frame movement intent.
    #[test]
    fn physics_runs_before_camera_controller() {
        let mut world = World::new();
        world.add_component(PhysicsConfig::default());
        world.add_component(controlled_camera());
        world.start(SYSTEMS).unwrap();
        let names: Vec<&str> = world.systems().iter().map(|s| s.name()).collect();
        assert_eq!(names, ["PhysicsSystem", "Camera3DSystem"]);
    }

    // An `AudioEmitter` in the world spawns the internal AudioSystem; without
    // one, no audio device is opened.
    #[test]
    fn audio_emitter_spawns_internal_system() {
        let mut world = World::new();
        world.add_component(crate::components::AudioEmitter::default());
        world.start(SYSTEMS).unwrap();

        let names: Vec<&str> = world.systems().iter().map(|s| s.name()).collect();
        assert_eq!(names, ["AudioSystem"]);
    }

    // No audio content means no AudioSystem (no audio device is opened).
    #[test]
    fn no_audio_emitter_means_no_system() {
        let mut world = World::new();
        world.start(SYSTEMS).unwrap();
        assert!(world.systems().is_empty());
    }

    // An `AudioCue` alone (no emitter) also spawns the audio system: a UI-only
    // world can play screen-triggered audio.
    #[test]
    fn audio_cue_spawns_internal_system() {
        let mut world = World::new();
        world.add_component(crate::components::AudioCue::default());
        world.start(SYSTEMS).unwrap();

        let names: Vec<&str> = world.systems().iter().map(|s| s.name()).collect();
        assert!(names.contains(&"AudioSystem"), "{names:?}");
    }

    // The full trigger chain: the initial screen's activation (announced by
    // UiInputSystem at init) reaches the audio system, which matches the
    // screen's cue on the first step. Playback itself needs a device and a
    // compiled payload, so the test observes the match counter.
    #[test]
    fn initial_view_fires_its_cue() {
        use crate::components::{AudioCue, Screen};
        use crate::ecs::AudioClipHandle;
        use crate::ecs::asset_id::AssetId;

        let mut world = World::new();
        let screen = AssetId(90);
        // The cue references its clip by handle. Matching (screen + clip present)
        // is independent of the clip payload, so no `AudioClipTable` is needed
        // here -- the counter observes the match, not playback.
        world.add_component(Screen {
            asset_id: screen,
            initial: true,
            fade_in_secs: 0.0,
            ..Default::default()
        });
        world.add_component(AudioCue {
            screen: Some(screen),
            clip: Some(AudioClipHandle(0)),
            ..Default::default()
        });
        world.start(SYSTEMS).unwrap();
        world.step();

        let matched = world
            .systems()
            .iter()
            .find_map(|s| s.downcast_ref::<crate::audio::AudioSystem>())
            .map(|a| a.cues_matched())
            .expect("world has an AudioSystem");
        assert_eq!(matched, 1, "the initial screen's cue should have matched");
    }
}