hiraku-engine 0.1.0

Hiraku visual-novel engine
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
use std::collections::{BTreeMap, HashMap};

use bevy::prelude::*;
use serde::{Deserialize, Serialize};

use crate::script::navigation::NavigationRequest;
use crate::state::StoredValue;

/// A typed side effect dispatched after a UI button accepts a click.
///
/// These are data, rather than Rust callbacks or string action routes, so a
/// declarative screen remains serializable and the ECS owns the actual work.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum UiEffect {
    PlaySfx {
        name: String,
        #[serde(default = "default_ui_effect_volume")]
        volume: f32,
    },
    OpenUi {
        role: String,
    },
    CloseUi,
    Save {
        slot: String,
    },
    Load {
        slot: String,
    },
    NextDialogue,
    Navigate(NavigationRequest),
}

fn default_ui_effect_volume() -> f32 {
    1.0
}

/// Runtime metadata for an ordinary HKS expression captured by a declarative
/// UI property. It is skipped by serialization; UI authors never manipulate
/// this type or a signal handle directly.
#[derive(Clone, Debug)]
pub struct UiReactiveBinding {
    pub(crate) program: hiraku_script::LinkedProgram,
    pub(crate) getter: hiraku_script::Value,
    pub(crate) setter: Option<hiraku_script::Value>,
    pub(crate) globals: BTreeMap<String, hiraku_script::Value>,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct UiPhaseAnimation {
    pub phases: Vec<crate::script::AnimationPhase>,
    pub spec: crate::script::AnimationSpec,
    /// Continuous rotation treats the last rotation as the equivalent of the
    /// first plus one turn, avoiding a backwards interpolation at the seam.
    #[serde(default)]
    pub continuous_rotation: bool,
}

/// A rendered declarative HKS UI root produced by `screen { ... }` or
/// `canvas { ... }`. Whether the root is modal is decided by its mount API:
/// `ui.open` blocks for a result, while `ui.mount` remains non-modal.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ScreenSpec {
    /// Optional title rendered by the default panel mode.
    pub title: Option<String>,
    /// When `true`, wraps children in the default centered panel.
    ///
    /// Set this to `false` for Ren'Py-style full-screen layouts where each child
    /// controls its own position with `left`, `right`, `top`, or `bottom`.
    #[serde(default = "default_screen_panel")]
    pub panel: bool,
    /// Width of the default panel, in logical pixels.
    #[serde(default)]
    pub width: Option<f32>,
    /// Full-screen catalog texture drawn behind all screen children.
    #[serde(default)]
    pub background_texture: Option<ScreenTexture>,
    /// Horizontal alignment for the default panel: `0.0` left, `0.5` center, `1.0` right.
    #[serde(default)]
    pub xalign: f32,
    /// Vertical alignment for the default panel: `0.0` top, `0.5` center, `1.0` bottom.
    #[serde(default)]
    pub yalign: f32,
    /// Padding applied to the default panel, in logical pixels.
    #[serde(default)]
    pub padding: f32,
    /// Gap between children in the default panel, in logical pixels.
    #[serde(default)]
    pub gap: f32,
    /// Full-screen overlay color in `[r, g, b, a]` form.
    #[serde(default)]
    pub overlay: Option<[f32; 4]>,
    /// Default panel background color in `[r, g, b, a]` form.
    #[serde(default)]
    pub background: Option<[f32; 4]>,
    /// Default panel border color in `[r, g, b, a]` form.
    #[serde(default)]
    pub border: Option<[f32; 4]>,
    /// Child nodes rendered inside the screen root or default panel.
    #[serde(default)]
    pub children: Vec<ScreenNode>,
}

/// A single displayable in an HKS screen tree.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum ScreenNode {
    /// Static UI text.
    Text(TextNode),
    /// A clickable text button that returns `value` from `screen(...)`.
    Button(ButtonNode),
    /// A UI image resolved from the texture catalog.
    Image(ScreenImageNode),
    /// A clickable texture with optional hover artwork.
    ImageButton(ScreenImageButtonNode),
    /// A non-interactive horizontal progress bar.
    Bar(BarNode),
    /// A horizontal flex container.
    Row(ContainerNode),
    /// A vertical flex container.
    Column(ContainerNode),
    /// A clipped vertical viewport whose children can be scrolled.
    Scrollable(ScrollableNode),
    /// A locally stateful two-visual toggle.
    Toggle(ToggleNode),
    /// Empty fixed-size space.
    Spacer(SpacerNode),
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ScrollableNode {
    pub children: Vec<ScreenNode>,
    pub speed: f32,
    #[serde(default)]
    pub layout: ScreenLayout,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ToggleNode {
    pub unchecked: ScreenImageNode,
    pub checked: ScreenImageNode,
    pub value: bool,
}

/// Shared layout options supported by most screen nodes.
///
/// Pixel fields and percent fields intentionally coexist. If both are set, the
/// percent value wins. Position fields switch the node to absolute positioning.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct ScreenLayout {
    /// Static visibility used before or instead of a live visibility binding.
    #[serde(default)]
    pub hidden: bool,
    /// Optional live Bool signal controlling whether this node participates in rendering/layout.
    #[serde(default)]
    pub visible_binding: Option<String>,
    #[serde(skip)]
    pub reactive_visibility: Option<UiReactiveBinding>,
    /// Optional engine-owned entrance/timeline animation specification.
    #[serde(default)]
    pub animation: Option<crate::script::AnimationSpec>,
    #[serde(default)]
    pub phase_animation: Option<UiPhaseAnimation>,
    /// Fixed width in logical pixels.
    #[serde(default)]
    pub width: Option<f32>,
    /// Fixed height in logical pixels.
    #[serde(default)]
    pub height: Option<f32>,
    /// Width as a percent of the parent.
    #[serde(default)]
    pub width_percent: Option<f32>,
    /// Height as a percent of the parent.
    #[serde(default)]
    pub height_percent: Option<f32>,
    /// Minimum width in logical pixels.
    #[serde(default)]
    pub min_width: Option<f32>,
    /// Absolute left inset in logical pixels.
    #[serde(default)]
    pub left: Option<f32>,
    /// Absolute left inset as a percent of the parent width.
    #[serde(default)]
    pub left_percent: Option<f32>,
    /// Absolute right inset in logical pixels.
    #[serde(default)]
    pub right: Option<f32>,
    /// Absolute right inset as a percent of the parent width.
    #[serde(default)]
    pub right_percent: Option<f32>,
    /// Absolute top inset in logical pixels.
    #[serde(default)]
    pub top: Option<f32>,
    /// Absolute top inset as a percent of the parent height.
    #[serde(default)]
    pub top_percent: Option<f32>,
    /// Absolute bottom inset in logical pixels.
    #[serde(default)]
    pub bottom: Option<f32>,
    /// Absolute bottom inset as a percent of the parent height.
    #[serde(default)]
    pub bottom_percent: Option<f32>,
}

/// Static text in an HKS screen.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct TextNode {
    /// Text content.
    pub text: String,
    /// Optional normalized live template. Static story values are captured
    /// during component evaluation; unresolved fields are read from UiModels.
    #[serde(default)]
    pub binding: Option<String>,
    #[serde(skip)]
    pub reactive_text: Option<UiReactiveBinding>,
    /// Font size in logical pixels.
    #[serde(default = "default_text_size")]
    pub size: f32,
    /// Text color in `[r, g, b, a]` form.
    #[serde(default)]
    pub color: Option<[f32; 4]>,
    /// Text alignment: `0.0` left, `0.5` center, `1.0` right.
    #[serde(default)]
    pub align: Option<f32>,
    /// Size and absolute positioning.
    #[serde(default)]
    pub layout: ScreenLayout,
}

impl StoredValue {
    pub fn as_bool(&self) -> Option<bool> {
        match self {
            Self::Bool(value) => Some(*value),
            _ => None,
        }
    }

    pub fn as_number(&self) -> Option<f64> {
        match self {
            Self::Int(value) => Some(*value as f64),
            Self::Float(value) => Some(*value),
            _ => None,
        }
    }

    pub(crate) fn display(&self) -> String {
        match self {
            Self::Bool(value) => value.to_string(),
            Self::Int(value) => value.to_string(),
            Self::Float(value) => value.to_string(),
            Self::String(value) => value.clone(),
            Self::Array(_) | Self::Map(_) => "<object>".to_string(),
        }
    }
}

/// Engine- and game-provided typed model roots consumed by live HKS UI bindings.
///
/// HKS selectors traverse each root in the VM. The engine therefore never
/// flattens a selector such as `dialogue.text` into an opaque string key.
#[derive(Resource, Default)]
pub struct UiModels {
    roots: BTreeMap<String, StoredValue>,
    revision: u64,
}

impl UiModels {
    pub fn set(&mut self, name: impl Into<String>, value: StoredValue) {
        let name = name.into();
        assert!(
            !name.contains('.'),
            "UI model names must be root identifiers"
        );
        if self.roots.get(&name) == Some(&value) {
            return;
        }
        self.roots.insert(name, value);
        self.revision = self
            .revision
            .checked_add(1)
            .expect("UI model revision must not be exhausted");
    }

    pub fn remove(&mut self, name: &str) {
        if self.roots.remove(name).is_some() {
            self.revision = self
                .revision
                .checked_add(1)
                .expect("UI model revision must not be exhausted");
        }
    }

    pub fn get(&self, path: &str) -> Option<&StoredValue> {
        let mut segments = path.split('.');
        let mut value = self.roots.get(segments.next()?)?;
        for segment in segments {
            let StoredValue::Map(fields) = value else {
                return None;
            };
            value = fields.get(segment)?;
        }
        Some(value)
    }

    pub fn revision(&self) -> u64 {
        self.revision
    }

    pub(crate) fn roots(&self) -> impl Iterator<Item = (&str, &StoredValue)> {
        self.roots
            .iter()
            .map(|(name, value)| (name.as_str(), value))
    }
}

/// Runtime binding attached only to text entities which read live models.
#[derive(Component)]
pub(crate) struct UiTextBinding {
    pub(crate) template: String,
    pub(crate) rendered_revision: u64,
}

#[derive(Component)]
pub(crate) struct UiVisibilityBinding {
    pub(crate) signal: String,
    pub(crate) rendered_revision: u64,
}

#[derive(Component)]
pub(crate) struct UiEnabledBinding {
    pub(crate) signal: String,
    pub(crate) rendered_revision: u64,
}

#[derive(Component)]
pub(crate) struct UiProgressBinding {
    pub(crate) signal: String,
    pub(crate) min: f32,
    pub(crate) max: f32,
    pub(crate) rendered_revision: u64,
}

#[derive(Component)]
pub(crate) struct UiReactiveTextBinding {
    pub(crate) expression: UiReactiveBinding,
    pub(crate) rendered_revision: u64,
}

#[derive(Component)]
pub(crate) struct UiReactiveVisibilityBinding {
    pub(crate) expression: UiReactiveBinding,
    pub(crate) rendered_revision: u64,
}

#[derive(Component)]
pub(crate) struct UiReactiveEnabledBinding {
    pub(crate) expression: UiReactiveBinding,
    pub(crate) rendered_revision: u64,
}

#[derive(Component)]
pub(crate) struct UiReactiveProgressBinding {
    pub(crate) expression: UiReactiveBinding,
    pub(crate) min: f32,
    pub(crate) max: f32,
    pub(crate) rendered_revision: u64,
}

#[derive(Component)]
pub(crate) struct UiAnimationPlayer {
    pub(crate) spec: crate::script::AnimationSpec,
    pub(crate) elapsed: f32,
    pub(crate) phases: Option<Vec<crate::script::AnimationPhase>>,
    pub(crate) continuous_rotation: bool,
}

/// A clickable text button in an HKS screen.
///
/// The button is intentionally text-first because that is the common Ren'Py
/// `textbutton` case. Image-backed buttons can be added later without changing
/// the existing ergonomic map shape.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ButtonNode {
    /// Label shown inside the button.
    pub text: String,
    /// Value returned from `screen(...)` when the button is pressed.
    ///
    /// Modal buttons normally use `value`. Non-modal overlays often use
    /// `action` instead.
    #[serde(default)]
    pub value: Option<StoredValue>,
    /// Typed effects dispatched when the click is accepted.
    #[serde(default)]
    pub click_effects: Vec<UiEffect>,
    /// Whether the button can be pressed.
    ///
    /// Disabled buttons remain visible and use insensitive colors, matching
    /// Ren'Py's `insensitive` state.
    #[serde(default = "default_button_enabled")]
    pub enabled: bool,
    #[serde(default)]
    pub enabled_binding: Option<String>,
    #[serde(skip)]
    pub reactive_enabled: Option<UiReactiveBinding>,
    /// Label font size in logical pixels.
    #[serde(default = "default_button_size")]
    pub size: f32,
    /// Idle label color.
    #[serde(default)]
    pub color: Option<[f32; 4]>,
    /// Hover label color.
    #[serde(default)]
    pub hovered_color: Option<[f32; 4]>,
    /// Pressed label color.
    #[serde(default)]
    pub pressed_color: Option<[f32; 4]>,
    /// Disabled label color.
    #[serde(default)]
    pub insensitive_color: Option<[f32; 4]>,
    /// Idle background color.
    #[serde(default)]
    pub background: Option<[f32; 4]>,
    /// Border color.
    #[serde(default)]
    pub border: Option<[f32; 4]>,
    /// Hover background color.
    #[serde(default)]
    pub hovered_background: Option<[f32; 4]>,
    /// Pressed background color.
    #[serde(default)]
    pub pressed_background: Option<[f32; 4]>,
    #[serde(default)]
    pub background_texture: Option<ScreenTexture>,
    #[serde(default)]
    pub hovered_background_texture: Option<ScreenTexture>,
    /// Scale applied while hovering. Defaults to `1.0`.
    #[serde(default = "default_interaction_scale")]
    pub hover_scale: f32,
    /// Scale applied while pressed. Defaults to `1.0`.
    #[serde(default = "default_interaction_scale")]
    pub press_scale: f32,
    /// Label alignment inside the button: `0.0` left, `0.5` center, `1.0` right.
    #[serde(default)]
    pub align: Option<f32>,
    /// Horizontal padding in logical pixels.
    #[serde(default)]
    pub padding_x: Option<f32>,
    /// Vertical padding in logical pixels.
    #[serde(default)]
    pub padding_y: Option<f32>,
    /// Border width in logical pixels.
    #[serde(default)]
    pub border_width: Option<f32>,
    /// Corner radius in logical pixels.
    #[serde(default)]
    pub radius: Option<f32>,
    /// Size and absolute positioning.
    #[serde(default)]
    pub layout: ScreenLayout,
}

/// An image displayable in an HKS screen.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ScreenImageNode {
    pub texture: ScreenTexture,
    /// Size and absolute positioning.
    #[serde(default)]
    pub layout: ScreenLayout,
}

/// A texture path and optional source rectangle resolved during script evaluation.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ScreenTexture {
    pub path: String,
    /// Source rectangle `[left, top, width, height]` in texture pixels.
    #[serde(default)]
    pub rect: Option<[f32; 4]>,
}

/// A catalog-backed image button with optional hover artwork.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ScreenImageButtonNode {
    pub texture: ScreenTexture,
    #[serde(default)]
    pub hovered_texture: Option<ScreenTexture>,
    /// Size and absolute positioning while the pointer hovers the button.
    #[serde(default)]
    pub hovered_layout: Option<ScreenLayout>,
    /// Scale applied while hovering. Defaults to `1.0`.
    #[serde(default = "default_interaction_scale")]
    pub hover_scale: f32,
    /// Scale applied while pressed. Defaults to `1.0`.
    #[serde(default = "default_interaction_scale")]
    pub press_scale: f32,
    /// Value returned from `screen(...)` when the button is released.
    #[serde(default)]
    pub value: Option<StoredValue>,
    /// Typed effects dispatched when the click is accepted.
    #[serde(default)]
    pub click_effects: Vec<UiEffect>,
    /// Whether the button can be pressed.
    #[serde(default = "default_button_enabled")]
    pub enabled: bool,
    #[serde(default)]
    pub enabled_binding: Option<String>,
    #[serde(skip)]
    pub reactive_enabled: Option<UiReactiveBinding>,
    /// Whether a disabled button still displays its hover artwork.
    #[serde(default)]
    pub hovered_when_disabled: bool,
    /// Size and absolute positioning.
    #[serde(default)]
    pub layout: ScreenLayout,
}

/// A non-interactive horizontal progress bar.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct BarNode {
    /// Current value.
    pub value: f32,
    #[serde(default)]
    pub binding: Option<String>,
    #[serde(skip)]
    pub reactive_value: Option<UiReactiveBinding>,
    /// Minimum value.
    #[serde(default)]
    pub min: f32,
    /// Maximum value.
    #[serde(default = "default_bar_max")]
    pub max: f32,
    /// Bar width in logical pixels.
    #[serde(default = "default_bar_width")]
    pub width: f32,
    /// Bar height in logical pixels.
    #[serde(default = "default_bar_height")]
    pub height: f32,
    /// Track background color.
    #[serde(default)]
    pub background: Option<[f32; 4]>,
    /// Filled portion color.
    #[serde(default)]
    pub fill: Option<[f32; 4]>,
    /// Border color.
    #[serde(default)]
    pub border: Option<[f32; 4]>,
    #[serde(default)]
    pub layout: ScreenLayout,
}

/// A flex container used by `vbox`, `hbox`, and `frame` HKS nodes.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ContainerNode {
    /// Gap between children in logical pixels.
    #[serde(default)]
    pub gap: f32,
    /// Uniform padding in logical pixels.
    #[serde(default)]
    pub padding: f32,
    /// Container background color.
    #[serde(default)]
    pub background: Option<[f32; 4]>,
    /// Container border color.
    #[serde(default)]
    pub border: Option<[f32; 4]>,
    /// Main-axis distribution: `start`, `center`, `end`, `between`, `around`, or `evenly`.
    #[serde(default)]
    pub justify: Option<String>,
    /// Cross-axis alignment: `start`, `center`, `end`, or `stretch`.
    #[serde(default)]
    pub align_items: Option<String>,
    /// Size and absolute positioning.
    #[serde(default)]
    pub layout: ScreenLayout,
    /// Child nodes.
    #[serde(default)]
    pub children: Vec<ScreenNode>,
}

/// Fixed empty space inside a container.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct SpacerNode {
    /// Width in logical pixels.
    #[serde(default)]
    pub width: f32,
    /// Height in logical pixels.
    #[serde(default)]
    pub height: f32,
    #[serde(default)]
    pub layout: ScreenLayout,
}

/// Runtime state for modal declarative HKS screens.
///
/// The renderer keeps old and pending roots alive during transitions so a screen
/// replacement never exposes an empty frame while images are loading.
#[derive(Resource, Default)]
pub struct ScreenUiState {
    /// Currently interactive screen root.
    pub active_root: Option<Entity>,
    /// Newly spawned root waiting for image readiness and warm-up frames.
    pub pending_root: Option<PendingScreenRoot>,
    /// Old roots kept under the active screen for flicker-free replacement.
    pub stale_roots: Vec<StaleScreenRoot>,
    /// Stable request currently blocked in `ui.open(...)`.
    pub waiting: Option<crate::script::ScriptRequestId>,
}

/// Active non-modal overlays spawned by `show_overlay(...)`.
#[derive(Resource, Default)]
pub struct OverlayUiState {
    /// Overlay roots keyed by script-provided name.
    pub roots: HashMap<String, Entity>,
}

/// A screen root that has been spawned but is not interactive yet.
pub struct PendingScreenRoot {
    /// Pending UI root entity.
    pub entity: Entity,
    /// Previous root kept visible until this pending root is ready.
    pub previous: Option<Entity>,
    /// Images that must be loaded before this screen becomes active.
    pub wait_images: Vec<Handle<Image>>,
    /// Extra update frames after image readiness, allowing layout and texture preparation to settle.
    pub ready_frames_remaining: u8,
    /// Stable request completed by a button intent.
    pub done: Option<crate::script::ScriptRequestId>,
}

/// An old screen root kept briefly under a replacement screen.
#[derive(Clone, Debug)]
pub struct StaleScreenRoot {
    /// Root entity to despawn after it is safe.
    pub entity: Entity,
    /// Minimum frames to keep the old root alive.
    pub frames_remaining: u8,
    /// Optional images to wait on before despawning.
    pub wait_images: Vec<Handle<Image>>,
}

/// Marker component for a screen root.
#[derive(Component)]
pub struct ScreenUiRoot;

/// Marker component for entities that belong to a declarative HKS screen.
#[derive(Component)]
pub struct ScreenUiNode;

/// Runtime interaction state for a screen button.
#[derive(Component, Clone)]
pub struct ScreenUiButton {
    /// Root this button belongs to; stale/pending roots are ignored.
    pub root: Entity,
    /// Intent value returned to the story runtime when the button is pressed.
    pub value: Option<StoredValue>,
    pub click_effects: Vec<UiEffect>,
    /// Whether press interactions should produce a value.
    pub enabled: bool,
    /// Text child whose color changes with interaction state.
    pub text_entity: Entity,
    /// Idle background color.
    pub normal_background: Color,
    /// Hover background color.
    pub hovered_background: Color,
    /// Pressed background color.
    pub pressed_background: Color,
    /// Disabled background color.
    pub insensitive_background: Color,
    /// Idle label color.
    pub normal_text_color: Color,
    /// Hover label color.
    pub hovered_text_color: Color,
    /// Pressed label color.
    pub pressed_text_color: Color,
    /// Disabled label color.
    pub insensitive_text_color: Color,
    pub hover_scale: f32,
    pub press_scale: f32,
    pub normal_texture: Option<Handle<Image>>,
    pub normal_atlas: Option<TextureAtlas>,
    pub normal_rect: Option<Rect>,
    pub hovered_texture: Option<Handle<Image>>,
    pub hovered_atlas: Option<TextureAtlas>,
    pub hovered_rect: Option<Rect>,
}

/// Marker component for the text child of a screen button.
#[derive(Component)]
pub struct ScreenUiButtonText;

/// Runtime interaction state for a texture-backed screen button.
#[derive(Component, Clone)]
pub struct ScreenUiImageButton {
    /// Root this button belongs to; stale and pending roots are ignored.
    pub root: Entity,
    /// Intent value returned to the story runtime when pressed.
    pub value: Option<StoredValue>,
    pub click_effects: Vec<UiEffect>,
    /// Whether press interactions should produce a value.
    pub enabled: bool,
    /// Whether a disabled button still displays its hover artwork.
    pub hovered_when_disabled: bool,
    /// Idle source rectangle.
    pub normal_rect: Option<Rect>,
    /// Idle image handle.
    pub normal_texture: Handle<Image>,
    /// Idle atlas section, when the texture came from the catalog.
    pub normal_atlas: Option<TextureAtlas>,
    /// Hover source rectangle, when supplied by the script.
    pub hovered_rect: Option<Rect>,
    /// Hover image handle, when supplied by the script.
    pub hovered_texture: Option<Handle<Image>>,
    /// Hover atlas section, when supplied by the script.
    pub hovered_atlas: Option<TextureAtlas>,
    /// Layout restored while the hovered artwork is displayed.
    pub hovered_node: Option<Node>,
    /// Layout restored while the idle artwork is displayed.
    pub normal_node: Node,
    /// Script-authored scale applied while hovering.
    pub hover_scale: f32,
    /// Script-authored scale applied while pressed.
    pub press_scale: f32,
}

#[derive(Component)]
pub struct ScreenUiScrollable {
    pub speed: f32,
}

#[derive(Component)]
pub struct ScreenUiToggle {
    pub checked: bool,
    pub unchecked_node: Node,
    pub checked_node: Node,
    pub unchecked_texture: Handle<Image>,
    pub unchecked_atlas: Option<TextureAtlas>,
    pub unchecked_rect: Option<Rect>,
    pub checked_texture: Handle<Image>,
    pub checked_atlas: Option<TextureAtlas>,
    pub checked_rect: Option<Rect>,
}

fn default_interaction_scale() -> f32 {
    1.0
}

fn default_screen_panel() -> bool {
    true
}

fn default_text_size() -> f32 {
    26.0
}

fn default_button_size() -> f32 {
    28.0
}

fn default_button_enabled() -> bool {
    true
}

fn default_bar_max() -> f32 {
    1.0
}

fn default_bar_width() -> f32 {
    320.0
}

fn default_bar_height() -> f32 {
    18.0
}

/// Converts an HKS `[r, g, b, a]` color into Bevy's sRGB color type.
pub fn color_from_rgba(rgba: [f32; 4]) -> Color {
    Color::srgba(rgba[0], rgba[1], rgba[2], rgba[3])
}