concinnity-engine 0.19.119

Runtime engine for Concinnity: ECS schedule, graphics, spawn, streaming
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
// Settings-row plumbing shared by the per-frame SettingCommand drain and the
// init-time row captures: label / sprite writers, the gray-out helpers for
// disabled rows, and the captures GraphicsSystem's init runs on the
// SettingsState it resolves.

use concinnity_core::components::{
    HitRegion, Identity, ScrollPanel, SettingVerb, Sprite, TextLabel, UiAction, WindowMode,
};
use concinnity_core::ecs::PipelineContext;
use concinnity_core::ecs::asset_id::AssetId;
use concinnity_core::window::display_mode;

use super::SettingsState;
use crate::gfx::system::{PadRebindViz, RebindViz, SliderViz};
use crate::settings;
use crate::settings::SettingKey;

// Muted gray applied to the labels of a capability-disabled settings row, so it
// reads as unavailable next to the live rows.
pub(crate) const DISABLED_ROW_COLOR: [f32; 3] = [0.42, 0.42, 0.47];

// The full set of label ids to gray for a set of capability-gated rows: the
// gated value labels themselves (the fallback when a row is not in a scroll
// panel), plus every element of any scroll row that contains one of them, so a
// row dims as a whole (its name + value + stepper glyphs) rather than only its
// value. `rows` is each scroll row's element id list.
pub(crate) fn expand_dim_set(
    gated: &std::collections::HashSet<AssetId>,
    rows: &[Vec<AssetId>],
) -> std::collections::HashSet<AssetId> {
    let mut dim = gated.clone();
    for row in rows {
        if row.iter().any(|id| gated.contains(id)) {
            dim.extend(row.iter().copied());
        }
    }
    dim
}

// Gray a captured set of settings-row labels (or restore their authored
// colors), for a row disabled at runtime: the show_fps / show_vram rows under
// the "Display performance stats" master, and the Resolution row outside
// fullscreen. A free function taking the captured (id, color) list so it can
// run inside the settings drain, where the backend is a live borrow. The
// matching input inertness comes from the `DisabledSettingRows` resource,
// published after the drain.
pub(crate) fn set_rows_grayed(
    ctx: &mut PipelineContext,
    rows: &[(AssetId, [f32; 3])],
    grayed: bool,
) {
    for &(id, orig) in rows {
        let color = if grayed { DISABLED_ROW_COLOR } else { orig };
        crate::ecs::by_asset_id::update::<TextLabel>(ctx, Some(id), |l| l.color = color);
    }
}

// The (label id, authored color) list of every settings row whose key is in
// `keys`, each expanded to its whole scroll row (background + name + value +
// glyphs) so the row grays as a unit; the authored colors drive the restore.
// Runs at init while the HitRegions / ScrollPanels are still present.
pub(crate) fn capture_row_labels(
    ctx: &mut PipelineContext,
    keys: &[SettingKey],
) -> Vec<(AssetId, [f32; 3])> {
    // Collect the rows' value-label ids (every region of a row -- steppers'
    // prev/next or a dropdown's open -- references its value label).
    let mut anchors: std::collections::HashSet<AssetId> = std::collections::HashSet::new();
    for r in ctx.query::<HitRegion>() {
        if let Some(UiAction::Setting { key, .. }) = r.action
            && keys.contains(&key)
            && let Some(label) = r.label
        {
            anchors.insert(label.id());
        }
    }
    if anchors.is_empty() {
        return Vec::new();
    }
    let rows: Vec<Vec<AssetId>> = ctx
        .query::<ScrollPanel>()
        .flat_map(|p| {
            p.rows
                .iter()
                .map(|r| r.elements.iter().map(|e| e.id()).collect())
        })
        .collect();
    let dim = expand_dim_set(&anchors, &rows);
    ctx.join2::<TextLabel, Identity>()
        .filter(|(_, _, identity)| dim.contains(&identity.id()))
        .map(|(_, l, identity)| (identity.id(), l.color))
        .collect()
}

// Overwrite the text of the TextLabel with the given id, if present.
pub(crate) fn set_label_content(ctx: &mut PipelineContext, id: AssetId, text: &str) {
    crate::ecs::by_asset_id::set_text(ctx, id, text);
}

// Set a cycle row's value label from its init-captured id. Used to update a
// row other than the one that was clicked (the master preset relabels the
// quality toggles + render scale; a quality-toggle change relabels the master
// row). The menu's HitRegions are drained after init, so the row -> label map
// is captured once rather than re-queried here.
pub(crate) fn set_cached_row_label(
    labels: &std::collections::HashMap<SettingKey, AssetId>,
    ctx: &mut PipelineContext,
    key: SettingKey,
    text: &str,
) {
    if let Some(&id) = labels.get(&key) {
        set_label_content(ctx, id, text);
    }
}

// Move the Sprite with the given id to `x` (its left edge), if present. Used to
// slide a slider's handle along its track.
pub(crate) fn set_sprite_x(ctx: &mut PipelineContext, id: AssetId, x: f32) {
    crate::ecs::by_asset_id::update::<Sprite>(ctx, Some(id), |s| s.x = x);
}

impl SettingsState {
    // Capture each slider row's runtime bookkeeping from its drag HitRegion +
    // handle Sprite, then sync the handle position and value label to the live
    // value. Runs once at init, before UiInputSystem drains the HitRegions and
    // hides the screen elements. `persisted` serves every controls slider, which
    // reads the store rather than the render params.
    pub(crate) fn init_sliders(
        &mut self,
        ctx: &mut PipelineContext,
        persisted: &crate::config::Settings,
    ) {
        let mut sliders: Vec<SliderViz> = Vec::new();
        for r in ctx.query::<HitRegion>() {
            let Some(UiAction::Setting {
                key,
                verb: SettingVerb::Drag,
            }) = r.action
            else {
                continue;
            };
            let (Some(handle_id), Some(value_id)) = (r.drag_handle, r.label) else {
                continue;
            };
            let handle_w = ctx
                .get_by_id::<Sprite>(handle_id.id())
                .map_or(0.0, |s| s.width);
            sliders.push(SliderViz {
                key,
                track_x: r.x,
                track_w: r.width,
                handle_w,
                handle_id: handle_id.id(),
                value_id: value_id.id(),
            });
        }
        for s in &sliders {
            let Some(slider) = settings::slider(s.key) else {
                continue;
            };
            let value = slider.current_value(
                &self.graphics.post_process,
                &self.graphics.quality.post_config,
                self.graphics.ambient_intensity,
                persisted,
            );
            let hx = s.track_x + slider.fraction(value) * (s.track_w - s.handle_w).max(0.0);
            set_sprite_x(ctx, s.handle_id, hx);
            set_label_content(ctx, s.value_id, &(slider.format)(value));
        }
        self.sliders = sliders;
    }

    // Capture each key-rebind row's bookkeeping from its `Rebind` HitRegion, then sync each value label to the live bound key. Runs once at
    // init (after the keymap is seeded), before UiInputSystem drains the
    // HitRegions.
    pub(crate) fn init_rebind_rows(&mut self, ctx: &mut PipelineContext) {
        let mut rows: Vec<RebindViz> = Vec::new();
        let mut pad_rows: Vec<PadRebindViz> = Vec::new();
        for r in ctx.query::<HitRegion>() {
            let (
                Some(UiAction::Setting {
                    key,
                    verb: SettingVerb::Rebind,
                }),
                Some(value_id),
            ) = (&r.action, r.label)
            else {
                continue;
            };
            match *key {
                SettingKey::KeyRebind(action) => rows.push(RebindViz {
                    action,
                    value_id: value_id.id(),
                }),
                SettingKey::PadRebind(action) => pad_rows.push(PadRebindViz {
                    action,
                    value_id: value_id.id(),
                }),
                _ => {}
            }
        }
        for row in &rows {
            let name = self.keymap.get(row.action).display_name();
            set_label_content(ctx, row.value_id, name);
        }
        for row in &pad_rows {
            let name = self.gamepad_map.get(row.action).display_name();
            set_label_content(ctx, row.value_id, name);
        }
        self.rebind_rows = rows;
        self.pad_rebind_rows = pad_rows;
    }

    // Capture each cycle row's setting key -> value-label id, so a runtime change
    // can relabel a row other than the one clicked (the master preset relabels
    // its dependents; a quality-toggle change relabels the master row). Runs at
    // init, before UiInputSystem drains the HitRegions.
    pub(crate) fn init_cycle_value_labels(&mut self, ctx: &mut PipelineContext) {
        let mut labels = std::collections::HashMap::new();
        for r in ctx.query::<HitRegion>() {
            // A stepper row's `Next` region and a dropdown's `Open` region
            // both carry the value label; the stepper's `Prev` twin shares it,
            // so skipping `Prev` maps each cycle key exactly once.
            if let (
                Some(UiAction::Setting {
                    key,
                    verb: SettingVerb::Next | SettingVerb::Open,
                }),
                Some(value_id),
            ) = (&r.action, r.label)
            {
                labels.insert(*key, value_id.id());
            }
        }
        self.cycle_value_labels = labels;
    }

    // Capture the show_fps / show_vram row labels (with their authored colors)
    // so the master "Display performance stats" toggle can gray them out at
    // runtime and restore them, and apply the initial gray from the resolved
    // toggle. Runs once at init while the HitRegions / ScrollPanels are present.
    pub(crate) fn capture_perf_sub_rows(&mut self, ctx: &mut PipelineContext) {
        self.perf_sub_row_labels =
            capture_row_labels(ctx, &[SettingKey::ShowFps, SettingKey::ShowVram]);
        set_rows_grayed(ctx, &self.perf_sub_row_labels, !self.graphics.perf_stats);
    }

    // Capture the Resolution row's labels and apply the initial gray from the
    // resolved window mode: the row only applies in fullscreen (windowed sizes
    // come from the window itself, borderless covers the display), so it is
    // grayed + inert in the other modes. Same init window as the perf rows.
    pub(crate) fn capture_resolution_row(&mut self, ctx: &mut PipelineContext) {
        self.resolution_row_labels = capture_row_labels(ctx, &[SettingKey::Resolution]);
        set_rows_grayed(
            ctx,
            &self.resolution_row_labels,
            self.window_args.mode != WindowMode::Fullscreen,
        );
    }

    // The mode the Resolution row displays and cycles from: the user's choice,
    // else the display's own mode, else the authored window size (a backend
    // that cannot read the display; snaps to the nearest listed mode).
    pub(crate) fn effective_resolution(&self) -> display_mode::DisplayMode {
        self.resolution
            .or(self.current_mode)
            .unwrap_or(display_mode::DisplayMode {
                width: self.window_args.width,
                height: self.window_args.height,
                refresh_hz: 0,
            })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use concinnity_core::components::ScrollRow;
    use concinnity_core::ecs::Ref;
    use concinnity_core::ecs::World;
    use std::collections::HashSet;

    // A gated value label pulls in every element of the scroll row that holds
    // it (the row's background, name, value, and stepper glyphs), so the whole
    // row grays out; unrelated rows are untouched.
    #[test]
    fn dim_set_expands_a_gated_value_label_to_its_whole_row() {
        let value = AssetId(3);
        let gated: HashSet<AssetId> = [value].into_iter().collect();
        let rows = vec![
            // Row A: bg, name, prev_glyph, value, next_glyph (value is gated).
            vec![AssetId(1), AssetId(2), value, AssetId(4), AssetId(5)],
            // Row B: an unrelated row.
            vec![AssetId(10), AssetId(11)],
        ];
        let dim = expand_dim_set(&gated, &rows);
        for id in [1, 2, 3, 4, 5] {
            assert!(dim.contains(&AssetId(id)), "row A element {id} should dim");
        }
        assert!(!dim.contains(&AssetId(10)), "an unrelated row stays lit");
        assert!(!dim.contains(&AssetId(11)), "an unrelated row stays lit");
    }

    // With no scroll rows (a hand-authored menu outside a panel), only the gated
    // value label itself dims -- a graceful fallback, not a panic.
    #[test]
    fn dim_set_without_rows_falls_back_to_the_value_label() {
        let gated: HashSet<AssetId> = [AssetId(7)].into_iter().collect();
        assert_eq!(expand_dim_set(&gated, &[]), gated);
    }

    fn label(color: [f32; 3]) -> TextLabel {
        TextLabel {
            color,
            ..Default::default()
        }
    }

    fn region(action: serde_json::Value, label: Option<u32>) -> HitRegion {
        HitRegion {
            action: Some(serde_json::from_value(action).unwrap()),
            label: label.map(AssetId).map(Ref::new),
            ..Default::default()
        }
    }

    // Writing a label's content hits the one matching id and leaves the rest
    // alone; an id with no label is a no-op rather than a panic.
    #[test]
    fn set_label_content_writes_only_the_matching_label() {
        let mut world = World::new();
        world.push_identified(AssetId(1), label([1.0; 3]));
        world.push_identified(AssetId(2), label([1.0; 3]));
        let mut ctx = world.context();

        set_label_content(&mut ctx, AssetId(2), "High");
        let contents: Vec<&str> = ctx
            .query::<TextLabel>()
            .map(|l| l.content.as_str())
            .collect();
        assert_eq!(contents, ["", "High"]);

        set_label_content(&mut ctx, AssetId(9), "Ultra");
        let contents: Vec<&str> = ctx
            .query::<TextLabel>()
            .map(|l| l.content.as_str())
            .collect();
        assert_eq!(contents, ["", "High"], "an absent id changes nothing");
    }

    // Moving a slider handle hits the one matching sprite; an absent id is a
    // no-op.
    #[test]
    fn set_sprite_x_moves_only_the_matching_sprite() {
        let mut world = World::new();
        world.push_identified(
            AssetId(1),
            Sprite {
                x: 0.0,
                ..Default::default()
            },
        );
        world.push_identified(
            AssetId(2),
            Sprite {
                x: 0.0,
                ..Default::default()
            },
        );
        let mut ctx = world.context();

        set_sprite_x(&mut ctx, AssetId(2), 42.0);
        assert_eq!(
            ctx.query::<Sprite>().map(|s| s.x).collect::<Vec<_>>(),
            [0.0, 42.0]
        );

        set_sprite_x(&mut ctx, AssetId(9), 99.0);
        assert_eq!(
            ctx.query::<Sprite>().map(|s| s.x).collect::<Vec<_>>(),
            [0.0, 42.0],
            "an absent id changes nothing"
        );
    }

    // Graying a captured row set recolors every listed label, and ungraying
    // restores each label's own authored color rather than a shared default.
    #[test]
    fn set_rows_grayed_grays_then_restores_authored_colors() {
        let authored = [[0.9, 0.9, 0.9], [0.2, 0.6, 1.0]];
        let mut world = World::new();
        world.push_identified(AssetId(1), label(authored[0]));
        world.push_identified(AssetId(2), label(authored[1]));
        let rows = [(AssetId(1), authored[0]), (AssetId(2), authored[1])];
        let mut ctx = world.context();

        set_rows_grayed(&mut ctx, &rows, true);
        assert!(
            ctx.query::<TextLabel>()
                .all(|l| l.color == DISABLED_ROW_COLOR)
        );

        set_rows_grayed(&mut ctx, &rows, false);
        assert_eq!(
            ctx.query::<TextLabel>()
                .map(|l| l.color)
                .collect::<Vec<_>>(),
            authored
        );
    }

    // A capture keys off the rows' regions and returns the whole scroll row's
    // labels with their authored colors, skipping unrelated rows, regions with
    // no label, and non-setting actions.
    #[test]
    fn capture_row_labels_returns_a_matching_rows_labels_and_colors() {
        let mut world = World::new();
        for id in [1, 2, 3, 4, 5, 20] {
            world.push_identified(AssetId(id), label([id as f32 / 100.0; 3]));
        }
        world.push(region(
            serde_json::json!({"setting": {"key": "shadow_map_size", "verb": "next"}}),
            Some(3),
        ));
        world.push(region(
            serde_json::json!({"setting": {"key": "vsync", "verb": "next"}}),
            Some(20),
        ));
        world.push(region(serde_json::json!("quit"), Some(1)));
        world.push(region(
            serde_json::json!({"setting": {"key": "shadow_map_size", "verb": "prev"}}),
            None,
        ));
        world.push(ScrollPanel {
            rows: vec![
                ScrollRow {
                    elements: vec![
                        Ref::new(AssetId(1)),
                        Ref::new(AssetId(2)),
                        Ref::new(AssetId(3)),
                        Ref::new(AssetId(4)),
                        Ref::new(AssetId(5)),
                    ],
                    ..Default::default()
                },
                ScrollRow {
                    elements: vec![Ref::new(AssetId(20))],
                    ..Default::default()
                },
            ],
            ..Default::default()
        });
        let mut ctx = world.context();

        let captured = capture_row_labels(&mut ctx, &[SettingKey::ShadowMapSize]);
        let expected: Vec<(AssetId, [f32; 3])> = [1, 2, 3, 4, 5]
            .into_iter()
            .map(|id| (AssetId(id), [id as f32 / 100.0; 3]))
            .collect();
        assert_eq!(captured, expected);
    }

    // A key no region carries captures nothing, so a row absent from a world's
    // menu simply has no gray-out set.
    #[test]
    fn capture_row_labels_without_a_matching_key_captures_nothing() {
        let mut world = World::new();
        world.push_identified(AssetId(1), label([1.0; 3]));
        world.push(region(
            serde_json::json!({"setting": {"key": "shadow_map_size", "verb": "next"}}),
            Some(1),
        ));
        let mut ctx = world.context();

        assert!(capture_row_labels(&mut ctx, &[SettingKey::Resolution]).is_empty());
    }

    // A perf sub-row captured while the stats master is off starts grayed, and
    // one captured while it is on keeps its authored color.
    #[test]
    fn capture_perf_sub_rows_applies_the_initial_gray() {
        let authored = [0.8, 0.8, 0.8];
        for (perf_stats, expected) in [(false, DISABLED_ROW_COLOR), (true, authored)] {
            let mut world = World::new();
            world.push_identified(AssetId(1), label(authored));
            world.push(region(
                serde_json::json!({"setting": {"key": "show_fps", "verb": "next"}}),
                Some(1),
            ));
            let mut state = SettingsState::for_tests();
            state.graphics.perf_stats = perf_stats;
            let mut ctx = world.context();

            state.capture_perf_sub_rows(&mut ctx);
            assert_eq!(state.perf_sub_row_labels, [(AssetId(1), authored)]);
            assert_eq!(ctx.query::<TextLabel>().next().unwrap().color, expected);
        }
    }

    // The Resolution row starts grayed in every mode but fullscreen.
    #[test]
    fn capture_resolution_row_grays_outside_fullscreen() {
        let authored = [0.8, 0.8, 0.8];
        for (mode, expected) in [
            (WindowMode::Windowed, DISABLED_ROW_COLOR),
            (WindowMode::Borderless, DISABLED_ROW_COLOR),
            (WindowMode::Fullscreen, authored),
        ] {
            let mut world = World::new();
            world.push_identified(AssetId(1), label(authored));
            world.push(region(
                serde_json::json!({"setting": {"key": "resolution", "verb": "next"}}),
                Some(1),
            ));
            let mut state = SettingsState::for_tests();
            state.window_args.mode = mode;
            let mut ctx = world.context();

            state.capture_resolution_row(&mut ctx);
            assert_eq!(state.resolution_row_labels, [(AssetId(1), authored)]);
            assert_eq!(
                ctx.query::<TextLabel>().next().unwrap().color,
                expected,
                "{mode:?}"
            );
        }
    }

    // Each cycle row's value label is captured under its key; drag and rebind
    // rows are not cycle rows.
    #[test]
    fn init_cycle_value_labels_maps_each_cycle_key_to_its_label() {
        let mut world = World::new();
        world.push(region(
            serde_json::json!({"setting": {"key": "vsync", "verb": "next"}}),
            Some(1),
        ));
        world.push(region(
            serde_json::json!({"setting": {"key": "vsync", "verb": "prev"}}),
            Some(1),
        ));
        world.push(region(
            serde_json::json!({"setting": {"key": "exposure", "verb": "drag"}}),
            Some(2),
        ));
        let mut state = SettingsState::for_tests();
        let mut ctx = world.context();

        state.init_cycle_value_labels(&mut ctx);
        assert_eq!(state.cycle_value_labels.len(), 1);
        assert_eq!(
            state.cycle_value_labels.get(&SettingKey::Vsync),
            Some(&AssetId(1))
        );
    }

    // The Resolution row reads the user's choice first, then the display's own
    // mode, then the authored window size.
    #[test]
    fn effective_resolution_falls_back_from_choice_to_display_to_window() {
        let mode = |width, height, refresh_hz| display_mode::DisplayMode {
            width,
            height,
            refresh_hz,
        };
        let mut state = SettingsState::for_tests();
        state.window_args.width = 640;
        state.window_args.height = 360;
        assert_eq!(state.effective_resolution(), mode(640, 360, 0));

        state.current_mode = Some(mode(2560, 1440, 144));
        assert_eq!(state.effective_resolution(), mode(2560, 1440, 144));

        state.resolution = Some(mode(1920, 1080, 60));
        assert_eq!(state.effective_resolution(), mode(1920, 1080, 60));
    }
}