1use core::fmt;
2use serde::{Deserialize, Serialize};
3
4use crate::{FinalDisposition, Point, Rect};
5
6const SCENE_FORMAT_VERSION: u16 = 1;
7const ABSOLUTE_MAX_NODES: u8 = 48;
8const ABSOLUTE_MAX_DEPTH: u8 = 5;
9const ABSOLUTE_MAX_ACTIONS: u8 = 8;
10const ABSOLUTE_MAX_DIAGRAM_NODES: u8 = 16;
11const ABSOLUTE_MAX_DIAGRAM_EDGES: u8 = 24;
12const ABSOLUTE_MAX_EFFECTS: u8 = 12;
13const ABSOLUTE_MAX_PHASES: u8 = 4;
14const ABSOLUTE_MAX_LIVE_EFFECTS: u8 = 5;
15const ABSOLUTE_MAX_FRAGMENTS: u8 = 8;
16const ABSOLUTE_MAX_DISPLACEMENT: u8 = 3;
17const ABSOLUTE_MAX_PHASE_MS: u16 = 2_400;
18const ABSOLUTE_MAX_INTERACTION_MS: u32 = 8_000;
19const ABSOLUTE_MAX_JSON_BYTES: u32 = 65_536;
20const MAX_TEXT_BYTES: usize = 512;
21
22#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
24#[serde(rename_all = "snake_case")]
25pub enum SceneRecipe {
26 Calm,
28 Balanced,
30 Vivid,
32}
33
34#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
36pub struct SceneBudgets {
37 pub max_nodes: u8,
39 pub max_depth: u8,
41 pub max_actions: u8,
43 pub max_diagram_nodes: u8,
45 pub max_diagram_edges: u8,
47 pub max_effects: u8,
49 pub max_phases_per_effect: u8,
51 pub max_live_effects: u8,
53 pub max_fragments: u8,
55 pub max_displacement: u8,
57 pub max_phase_ms: u16,
59 pub max_interaction_ms: u32,
61 pub max_json_bytes: u32,
63}
64
65impl Default for SceneBudgets {
66 fn default() -> Self {
67 Self {
68 max_nodes: ABSOLUTE_MAX_NODES,
69 max_depth: ABSOLUTE_MAX_DEPTH,
70 max_actions: ABSOLUTE_MAX_ACTIONS,
71 max_diagram_nodes: ABSOLUTE_MAX_DIAGRAM_NODES,
72 max_diagram_edges: ABSOLUTE_MAX_DIAGRAM_EDGES,
73 max_effects: ABSOLUTE_MAX_EFFECTS,
74 max_phases_per_effect: ABSOLUTE_MAX_PHASES,
75 max_live_effects: ABSOLUTE_MAX_LIVE_EFFECTS,
76 max_fragments: ABSOLUTE_MAX_FRAGMENTS,
77 max_displacement: ABSOLUTE_MAX_DISPLACEMENT,
78 max_phase_ms: ABSOLUTE_MAX_PHASE_MS,
79 max_interaction_ms: ABSOLUTE_MAX_INTERACTION_MS,
80 max_json_bytes: ABSOLUTE_MAX_JSON_BYTES,
81 }
82 }
83}
84
85#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
87pub struct FactContent {
88 pub label: String,
90 pub value: String,
92}
93
94#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
96pub struct ActionContent {
97 pub key: String,
99 pub label: String,
101}
102
103#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
105pub struct ReceiptContent {
106 pub eyebrow: String,
108 pub title: String,
110 pub outcome: FinalDisposition,
112 pub facts: Vec<FactContent>,
114 pub evidence: Vec<String>,
116 pub table_headers: Vec<String>,
118 pub table_rows: Vec<Vec<String>>,
120 pub diagram_labels: Vec<String>,
122 pub actions: Vec<ActionContent>,
124 pub menu_items: Vec<String>,
126}
127
128#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
130pub struct SceneRequest {
131 pub seed: u64,
133 pub recipe: SceneRecipe,
135 pub content: ReceiptContent,
137 pub budgets: SceneBudgets,
139}
140
141#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
143#[serde(rename_all = "snake_case")]
144pub enum LayoutProfile {
145 Instrument,
147 Split,
149 Asymmetric,
151 ResultLed,
153 DiagramLed,
155 Terminal,
157 Editorial,
159}
160
161#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
163#[serde(rename_all = "snake_case")]
164pub enum SceneNodeKind {
165 Frame,
167 Header,
169 Facts,
171 List,
173 Table,
175 Diagram,
177 Result,
179 Actions,
181 Menu,
183}
184
185#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
187#[serde(rename_all = "snake_case")]
188pub enum GridRole {
189 Frame,
191 Lead,
193 Primary,
195 Secondary,
197 Full,
199 Outcome,
201 Footer,
203}
204
205#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
207#[serde(rename_all = "snake_case")]
208pub enum VisualRole {
209 Quiet,
211 Standard,
213 Emphasis,
215 Outcome,
217 Interactive,
219}
220
221#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
223#[serde(rename_all = "snake_case")]
224pub enum ButtonSize {
225 Compact,
227 Regular,
229 Prominent,
231}
232
233#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
235pub struct SceneAction {
236 pub id: String,
238 pub key: String,
240 pub label: String,
242 pub size: ButtonSize,
244}
245
246#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
248#[serde(tag = "kind", rename_all = "snake_case")]
249pub enum SceneNodeContent {
250 Empty,
252 Header {
254 eyebrow: String,
256 title: String,
258 },
259 Facts {
261 items: Vec<FactContent>,
263 },
264 List {
266 items: Vec<String>,
268 },
269 Table {
271 headers: Vec<String>,
273 rows: Vec<Vec<String>>,
275 },
276 Result {
278 disposition: FinalDisposition,
280 },
281 Actions {
283 items: Vec<SceneAction>,
285 },
286 Menu {
288 items: Vec<String>,
290 },
291}
292
293#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
295pub struct SceneNode {
296 pub id: String,
298 pub kind: SceneNodeKind,
300 pub grid_role: GridRole,
302 pub visual_role: VisualRole,
304 pub effect_target: bool,
306 pub content: SceneNodeContent,
308 pub children: Vec<Self>,
310}
311
312#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
314#[serde(rename_all = "snake_case")]
315pub enum DiagramForm {
316 Linear,
318 Tree,
320 State,
322 Network,
324}
325
326#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
328pub struct DiagramNode {
329 pub id: String,
331 pub label: String,
333 pub terminal: bool,
335}
336
337#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
339pub struct DiagramEdge {
340 pub id: String,
342 pub from: String,
344 pub to: String,
346}
347
348#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
350pub struct DiagramPlan {
351 pub form: DiagramForm,
353 pub nodes: Vec<DiagramNode>,
355 pub edges: Vec<DiagramEdge>,
357}
358
359#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
361#[serde(rename_all = "snake_case")]
362pub enum EffectPattern {
363 Pulse,
365 Glitch,
367 Invert,
369 Fragment,
371 EdgeTraverse,
373 Packet,
375 Scanline,
377}
378
379#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
381#[serde(tag = "kind", content = "id", rename_all = "snake_case")]
382pub enum EffectTarget {
383 Node(String),
385 Edge(String),
387}
388
389#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
391pub struct EffectPhase {
392 pub at_ms: u32,
394 pub duration_ms: u16,
396}
397
398#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
400pub struct EffectParameters {
401 pub intensity: u8,
403 pub offset_x: i8,
405 pub offset_y: i8,
407 pub fragments: u8,
409}
410
411#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
413pub struct EffectPlan {
414 pub id: String,
416 pub pattern: EffectPattern,
418 pub target: EffectTarget,
420 pub parameters: EffectParameters,
422 pub phases: Vec<EffectPhase>,
424}
425
426#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
428#[serde(tag = "kind", content = "action_id", rename_all = "snake_case")]
429pub enum InteractionTrigger {
430 Load,
432 Action(String),
434}
435
436#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
438pub struct InteractionScript {
439 pub trigger: InteractionTrigger,
441 pub effect_ids: Vec<String>,
443}
444
445#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
447pub struct ScenePlan {
448 pub format_version: u16,
450 pub seed: u64,
452 pub recipe: SceneRecipe,
454 pub layout: LayoutProfile,
456 pub root: SceneNode,
458 pub diagram: DiagramPlan,
460 pub effects: Vec<EffectPlan>,
462 pub scripts: Vec<InteractionScript>,
464}
465
466impl ScenePlan {
467 pub fn to_json(&self) -> Result<String, SceneError> {
473 serde_json::to_string(self).map_err(|error| SceneError::Serialization(error.to_string()))
474 }
475}
476
477#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
479pub struct NodeGeometry {
480 pub id: String,
482 pub rect: Rect,
484 pub incoming: Point,
486 pub outgoing: Point,
488}
489
490#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
492pub struct SceneSimulationInput {
493 pub plan: ScenePlan,
495 pub geometry: Vec<NodeGeometry>,
497 pub trigger: InteractionTrigger,
499}
500
501#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
503#[serde(tag = "kind", rename_all = "snake_case")]
504pub enum SceneEvent {
505 InteractionStarted {
507 at_ms: u32,
509 },
510 PhaseStarted {
512 effect_id: String,
514 phase_index: u8,
516 at_ms: u32,
518 duration_ms: u16,
520 },
521 NodeActivated {
523 target_id: String,
525 point: Point,
527 at_ms: u32,
529 duration_ms: u16,
531 intensity: u8,
533 },
534 BackingGlitched {
536 target_id: String,
538 at_ms: u32,
540 duration_ms: u16,
542 offset_x: i8,
544 offset_y: i8,
546 },
547 BackingInverted {
549 target_id: String,
551 at_ms: u32,
553 duration_ms: u16,
555 },
556 FragmentsEmitted {
558 target_id: String,
560 point: Point,
562 at_ms: u32,
564 duration_ms: u16,
566 count: u8,
568 },
569 EdgeTraversed {
571 edge_id: String,
573 from: Point,
575 to: Point,
577 at_ms: u32,
579 duration_ms: u16,
581 },
582 PacketTraversed {
584 edge_id: String,
586 from: Point,
588 to: Point,
590 at_ms: u32,
592 duration_ms: u16,
594 },
595 ScanlineSwept {
597 target_id: String,
599 rect: Rect,
601 at_ms: u32,
603 duration_ms: u16,
605 },
606 InteractionFinished {
608 at_ms: u32,
610 },
611}
612
613#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
615pub struct SceneTrace {
616 pub format_version: u16,
618 pub seed: u64,
620 pub trigger: InteractionTrigger,
622 pub events: Vec<SceneEvent>,
624}
625
626impl SceneTrace {
627 pub fn to_json(&self) -> Result<String, SceneError> {
633 serde_json::to_string(self).map_err(|error| SceneError::Serialization(error.to_string()))
634 }
635}
636
637#[derive(Clone, Debug, Eq, PartialEq)]
639pub enum SceneError {
640 ZeroSeed,
642 InvalidContent(&'static str),
644 BudgetExceeded(&'static str),
646 InvalidIdentifier(&'static str),
648 InvalidGeometry(&'static str),
650 UnknownInteraction,
652 Serialization(String),
654}
655
656impl fmt::Display for SceneError {
657 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
658 match self {
659 Self::ZeroSeed => formatter.write_str("scene seed must be nonzero"),
660 Self::InvalidContent(name) => write!(formatter, "invalid scene content: {name}"),
661 Self::BudgetExceeded(name) => write!(formatter, "scene budget exceeded: {name}"),
662 Self::InvalidIdentifier(name) => write!(formatter, "invalid scene identifier: {name}"),
663 Self::InvalidGeometry(name) => write!(formatter, "invalid scene geometry: {name}"),
664 Self::UnknownInteraction => formatter.write_str("interaction is not declared by scene"),
665 Self::Serialization(message) => {
666 write!(formatter, "scene serialization failed: {message}")
667 }
668 }
669 }
670}
671
672impl std::error::Error for SceneError {}
673
674pub fn generate_scene(request: &SceneRequest) -> Result<ScenePlan, SceneError> {
680 validate_request(request)?;
681 let mut choice_random = SceneRandom::new(request.seed);
682 let mut timing_random = SceneRandom::new(request.seed ^ 0xe703_7ed1_a0b4_28db);
683 let layout = choice_random.layout();
684 let diagram = generate_diagram(
685 &request.content.diagram_labels,
686 choice_random.diagram_form(),
687 );
688 let actions = generate_actions(&request.content.actions, &mut choice_random);
689 let root = generate_tree(&request.content, &actions, layout);
690 let (effects, scripts) = generate_effects(
691 request,
692 &root,
693 &diagram,
694 &actions,
695 &mut choice_random,
696 &mut timing_random,
697 )?;
698 let plan = ScenePlan {
699 format_version: SCENE_FORMAT_VERSION,
700 seed: request.seed,
701 recipe: request.recipe,
702 layout,
703 root,
704 diagram,
705 effects,
706 scripts,
707 };
708 validate_plan(&plan, request.budgets)?;
709 let byte_count = plan.to_json()?.len();
710 let byte_limit = usize::try_from(request.budgets.max_json_bytes)
711 .map_err(|_| SceneError::BudgetExceeded("serialized scene bytes"))?;
712 if byte_count > byte_limit {
713 return Err(SceneError::BudgetExceeded("serialized scene bytes"));
714 }
715 Ok(plan)
716}
717
718pub fn simulate_scene(input: &SceneSimulationInput) -> Result<SceneTrace, SceneError> {
724 validate_plan(&input.plan, SceneBudgets::default())?;
725 validate_geometry(&input.plan, &input.geometry)?;
726 let script = input
727 .plan
728 .scripts
729 .iter()
730 .find(|script| script.trigger == input.trigger)
731 .ok_or(SceneError::UnknownInteraction)?;
732 let mut events = vec![SceneEvent::InteractionStarted { at_ms: 0 }];
733 let mut finish_ms = 0_u32;
734 for effect_id in &script.effect_ids {
735 let effect = input
736 .plan
737 .effects
738 .iter()
739 .find(|effect| effect.id == *effect_id)
740 .ok_or(SceneError::InvalidIdentifier("script effect"))?;
741 for (phase_index, phase) in effect.phases.iter().enumerate() {
742 let phase_index = u8::try_from(phase_index)
743 .map_err(|_| SceneError::BudgetExceeded("phases per effect"))?;
744 events.push(SceneEvent::PhaseStarted {
745 effect_id: effect.id.clone(),
746 phase_index,
747 at_ms: phase.at_ms,
748 duration_ms: phase.duration_ms,
749 });
750 push_effect_event(&mut events, effect, *phase, &input.plan, &input.geometry)?;
751 finish_ms = finish_ms.max(phase.at_ms + u32::from(phase.duration_ms));
752 }
753 }
754 events.sort_by_key(event_time);
755 events.push(SceneEvent::InteractionFinished { at_ms: finish_ms });
756 Ok(SceneTrace {
757 format_version: input.plan.format_version,
758 seed: input.plan.seed,
759 trigger: input.trigger.clone(),
760 events,
761 })
762}
763
764fn validate_request(request: &SceneRequest) -> Result<(), SceneError> {
765 if request.seed == 0 {
766 return Err(SceneError::ZeroSeed);
767 }
768 validate_budgets(request.budgets)?;
769 validate_text(&request.content.eyebrow, "eyebrow")?;
770 validate_text(&request.content.title, "title")?;
771 if request.content.facts.is_empty() || request.content.facts.len() > 12 {
772 return Err(SceneError::InvalidContent("facts"));
773 }
774 for fact in &request.content.facts {
775 validate_text(&fact.label, "fact label")?;
776 validate_text(&fact.value, "fact value")?;
777 }
778 if request.content.evidence.is_empty() || request.content.evidence.len() > 12 {
779 return Err(SceneError::InvalidContent("evidence list"));
780 }
781 for item in &request.content.evidence {
782 validate_text(item, "evidence item")?;
783 }
784 if request.content.table_headers.is_empty() || request.content.table_headers.len() > 6 {
785 return Err(SceneError::InvalidContent("table headers"));
786 }
787 for header in &request.content.table_headers {
788 validate_text(header, "table header")?;
789 }
790 if request.content.table_rows.is_empty() || request.content.table_rows.len() > 12 {
791 return Err(SceneError::InvalidContent("table rows"));
792 }
793 for row in &request.content.table_rows {
794 if row.len() != request.content.table_headers.len() {
795 return Err(SceneError::InvalidContent("table row width"));
796 }
797 for cell in row {
798 validate_text(cell, "table cell")?;
799 }
800 }
801 let diagram_count = request.content.diagram_labels.len();
802 if !(2..=usize::from(request.budgets.max_diagram_nodes)).contains(&diagram_count) {
803 return Err(SceneError::InvalidContent("diagram labels"));
804 }
805 let worst_case_edges = if diagram_count > 3 {
806 diagram_count + 1
807 } else {
808 diagram_count.saturating_sub(1)
809 };
810 if worst_case_edges > usize::from(request.budgets.max_diagram_edges) {
811 return Err(SceneError::BudgetExceeded("diagram edges"));
812 }
813 for label in &request.content.diagram_labels {
814 validate_text(label, "diagram label")?;
815 }
816 if request.content.actions.is_empty()
817 || request.content.actions.len() > usize::from(request.budgets.max_actions)
818 {
819 return Err(SceneError::InvalidContent("actions"));
820 }
821 if request.content.actions.len() >= usize::from(request.budgets.max_effects) {
822 return Err(SceneError::BudgetExceeded("action and load effects"));
823 }
824 if request.content.actions.len() + 9 > usize::from(request.budgets.max_nodes) {
825 return Err(SceneError::BudgetExceeded("scene and action nodes"));
826 }
827 for action in &request.content.actions {
828 validate_key(&action.key, "action key")?;
829 validate_text(&action.label, "action label")?;
830 }
831 if request.content.menu_items.is_empty() || request.content.menu_items.len() > 8 {
832 return Err(SceneError::InvalidContent("menu items"));
833 }
834 for item in &request.content.menu_items {
835 validate_text(item, "menu item")?;
836 }
837 Ok(())
838}
839
840fn validate_budgets(budgets: SceneBudgets) -> Result<(), SceneError> {
841 let valid = budgets.max_nodes >= 9
842 && budgets.max_nodes <= ABSOLUTE_MAX_NODES
843 && budgets.max_depth >= 2
844 && budgets.max_depth <= ABSOLUTE_MAX_DEPTH
845 && budgets.max_actions > 0
846 && budgets.max_actions <= ABSOLUTE_MAX_ACTIONS
847 && budgets.max_diagram_nodes >= 2
848 && budgets.max_diagram_nodes <= ABSOLUTE_MAX_DIAGRAM_NODES
849 && budgets.max_diagram_edges > 0
850 && budgets.max_diagram_edges <= ABSOLUTE_MAX_DIAGRAM_EDGES
851 && budgets.max_effects > 0
852 && budgets.max_effects <= ABSOLUTE_MAX_EFFECTS
853 && budgets.max_phases_per_effect > 0
854 && budgets.max_phases_per_effect <= ABSOLUTE_MAX_PHASES
855 && budgets.max_live_effects > 0
856 && budgets.max_live_effects <= ABSOLUTE_MAX_LIVE_EFFECTS
857 && budgets.max_fragments > 0
858 && budgets.max_fragments <= ABSOLUTE_MAX_FRAGMENTS
859 && budgets.max_displacement <= ABSOLUTE_MAX_DISPLACEMENT
860 && budgets.max_phase_ms >= 60
861 && budgets.max_phase_ms <= ABSOLUTE_MAX_PHASE_MS
862 && budgets.max_interaction_ms >= u32::from(budgets.max_phase_ms)
863 && budgets.max_interaction_ms <= ABSOLUTE_MAX_INTERACTION_MS
864 && budgets.max_json_bytes > 0
865 && budgets.max_json_bytes <= ABSOLUTE_MAX_JSON_BYTES;
866 if !valid {
867 return Err(SceneError::BudgetExceeded("invalid hard limits"));
868 }
869 Ok(())
870}
871
872fn validate_text(value: &str, name: &'static str) -> Result<(), SceneError> {
873 if value.trim().is_empty() || value.len() > MAX_TEXT_BYTES {
874 return Err(SceneError::InvalidContent(name));
875 }
876 Ok(())
877}
878
879fn validate_key(value: &str, name: &'static str) -> Result<(), SceneError> {
880 validate_text(value, name)?;
881 if !value
882 .bytes()
883 .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_'))
884 {
885 return Err(SceneError::InvalidContent(name));
886 }
887 Ok(())
888}
889
890fn generate_actions(actions: &[ActionContent], random: &mut SceneRandom) -> Vec<SceneAction> {
891 actions
892 .iter()
893 .enumerate()
894 .map(|(index, action)| SceneAction {
895 id: format!("action-{index}"),
896 key: action.key.clone(),
897 label: action.label.clone(),
898 size: random.button_size(),
899 })
900 .collect()
901}
902
903fn generate_tree(
904 content: &ReceiptContent,
905 actions: &[SceneAction],
906 layout: LayoutProfile,
907) -> SceneNode {
908 let roles = layout_roles(layout);
909 let children = vec![
910 scene_node(
911 "header",
912 SceneNodeKind::Header,
913 roles[0],
914 VisualRole::Emphasis,
915 true,
916 SceneNodeContent::Header {
917 eyebrow: content.eyebrow.clone(),
918 title: content.title.clone(),
919 },
920 ),
921 scene_node(
922 "facts",
923 SceneNodeKind::Facts,
924 roles[1],
925 VisualRole::Standard,
926 true,
927 SceneNodeContent::Facts {
928 items: content.facts.clone(),
929 },
930 ),
931 scene_node(
932 "evidence",
933 SceneNodeKind::List,
934 roles[2],
935 VisualRole::Quiet,
936 true,
937 SceneNodeContent::List {
938 items: content.evidence.clone(),
939 },
940 ),
941 scene_node(
942 "records",
943 SceneNodeKind::Table,
944 roles[3],
945 VisualRole::Standard,
946 true,
947 SceneNodeContent::Table {
948 headers: content.table_headers.clone(),
949 rows: content.table_rows.clone(),
950 },
951 ),
952 scene_node(
953 "diagram",
954 SceneNodeKind::Diagram,
955 roles[4],
956 VisualRole::Emphasis,
957 true,
958 SceneNodeContent::Empty,
959 ),
960 scene_node(
961 "result",
962 SceneNodeKind::Result,
963 roles[5],
964 VisualRole::Outcome,
965 true,
966 SceneNodeContent::Result {
967 disposition: content.outcome,
968 },
969 ),
970 scene_node(
971 "actions",
972 SceneNodeKind::Actions,
973 roles[6],
974 VisualRole::Interactive,
975 true,
976 SceneNodeContent::Actions {
977 items: actions.to_vec(),
978 },
979 ),
980 scene_node(
981 "menu",
982 SceneNodeKind::Menu,
983 GridRole::Footer,
984 VisualRole::Interactive,
985 true,
986 SceneNodeContent::Menu {
987 items: content.menu_items.clone(),
988 },
989 ),
990 ];
991 SceneNode {
992 id: "scene".to_owned(),
993 kind: SceneNodeKind::Frame,
994 grid_role: GridRole::Frame,
995 visual_role: VisualRole::Standard,
996 effect_target: true,
997 content: SceneNodeContent::Empty,
998 children,
999 }
1000}
1001
1002fn scene_node(
1003 id: &str,
1004 kind: SceneNodeKind,
1005 grid_role: GridRole,
1006 visual_role: VisualRole,
1007 effect_target: bool,
1008 content: SceneNodeContent,
1009) -> SceneNode {
1010 SceneNode {
1011 id: id.to_owned(),
1012 kind,
1013 grid_role,
1014 visual_role,
1015 effect_target,
1016 content,
1017 children: Vec::new(),
1018 }
1019}
1020
1021fn layout_roles(layout: LayoutProfile) -> [GridRole; 7] {
1022 match layout {
1023 LayoutProfile::Instrument | LayoutProfile::Terminal => [
1024 GridRole::Lead,
1025 GridRole::Primary,
1026 GridRole::Primary,
1027 GridRole::Full,
1028 GridRole::Full,
1029 GridRole::Outcome,
1030 GridRole::Footer,
1031 ],
1032 LayoutProfile::Split | LayoutProfile::Asymmetric => [
1033 GridRole::Lead,
1034 GridRole::Primary,
1035 GridRole::Secondary,
1036 GridRole::Primary,
1037 GridRole::Secondary,
1038 GridRole::Outcome,
1039 GridRole::Footer,
1040 ],
1041 LayoutProfile::ResultLed | LayoutProfile::DiagramLed => [
1042 GridRole::Lead,
1043 GridRole::Secondary,
1044 GridRole::Secondary,
1045 GridRole::Full,
1046 GridRole::Primary,
1047 GridRole::Outcome,
1048 GridRole::Footer,
1049 ],
1050 LayoutProfile::Editorial => [
1051 GridRole::Lead,
1052 GridRole::Primary,
1053 GridRole::Secondary,
1054 GridRole::Full,
1055 GridRole::Full,
1056 GridRole::Outcome,
1057 GridRole::Footer,
1058 ],
1059 }
1060}
1061
1062fn generate_diagram(labels: &[String], form: DiagramForm) -> DiagramPlan {
1063 let nodes = labels
1064 .iter()
1065 .enumerate()
1066 .map(|(index, label)| DiagramNode {
1067 id: format!("diagram-node-{index}"),
1068 label: label.clone(),
1069 terminal: index + 1 == labels.len(),
1070 })
1071 .collect::<Vec<_>>();
1072 let mut pairs = Vec::new();
1073 match form {
1074 DiagramForm::Linear | DiagramForm::State => {
1075 for index in 1..nodes.len() {
1076 pairs.push((index - 1, index));
1077 }
1078 if form == DiagramForm::State && nodes.len() > 2 {
1079 pairs.push((nodes.len() - 1, 0));
1080 }
1081 }
1082 DiagramForm::Tree => {
1083 for index in 1..nodes.len() {
1084 pairs.push(((index - 1) / 2, index));
1085 }
1086 }
1087 DiagramForm::Network => {
1088 for index in 1..nodes.len() {
1089 pairs.push((index - 1, index));
1090 }
1091 if nodes.len() > 3 {
1092 pairs.push((0, 2));
1093 pairs.push((1, nodes.len() - 1));
1094 }
1095 }
1096 }
1097 let edges = pairs
1098 .into_iter()
1099 .enumerate()
1100 .map(|(index, (from, to))| DiagramEdge {
1101 id: format!("diagram-edge-{index}"),
1102 from: nodes[from].id.clone(),
1103 to: nodes[to].id.clone(),
1104 })
1105 .collect();
1106 DiagramPlan { form, nodes, edges }
1107}
1108
1109fn generate_effects(
1110 request: &SceneRequest,
1111 root: &SceneNode,
1112 diagram: &DiagramPlan,
1113 actions: &[SceneAction],
1114 choice_random: &mut SceneRandom,
1115 timing_random: &mut SceneRandom,
1116) -> Result<(Vec<EffectPlan>, Vec<InteractionScript>), SceneError> {
1117 let mut node_targets = Vec::new();
1118 collect_effect_targets(root, &mut node_targets);
1119 node_targets.extend(diagram.nodes.iter().map(|node| node.id.clone()));
1120 let desired_load_effects = match request.recipe {
1121 SceneRecipe::Calm => 2,
1122 SceneRecipe::Balanced => 4,
1123 SceneRecipe::Vivid => 6,
1124 };
1125 let action_effects = actions.len();
1126 let effect_limit = usize::from(request.budgets.max_effects);
1127 let load_effects = desired_load_effects.min(effect_limit.saturating_sub(action_effects));
1128 if load_effects == 0 {
1129 return Err(SceneError::BudgetExceeded("load effects"));
1130 }
1131 let mut effects = Vec::with_capacity(load_effects + action_effects);
1132 let mut load_ids = Vec::with_capacity(load_effects);
1133 let mut cursor_ms = 0_u32;
1134 for index in 0..load_effects {
1135 let pattern = choice_random.pattern(!diagram.edges.is_empty());
1136 let target = target_for_pattern(pattern, &node_targets, diagram, choice_random)?;
1137 let effect = generated_effect(
1138 format!("effect-load-{index}"),
1139 pattern,
1140 target,
1141 cursor_ms,
1142 request.budgets,
1143 timing_random,
1144 );
1145 cursor_ms = effect_end(&effect).saturating_add(40);
1146 load_ids.push(effect.id.clone());
1147 effects.push(effect);
1148 }
1149 let mut scripts = vec![InteractionScript {
1150 trigger: InteractionTrigger::Load,
1151 effect_ids: load_ids,
1152 }];
1153 for (index, action) in actions.iter().enumerate() {
1154 let pattern = choice_random.action_pattern();
1155 let target = EffectTarget::Node(action.id.clone());
1156 let effect = generated_effect(
1157 format!("effect-action-{index}"),
1158 pattern,
1159 target,
1160 0,
1161 request.budgets,
1162 timing_random,
1163 );
1164 scripts.push(InteractionScript {
1165 trigger: InteractionTrigger::Action(action.id.clone()),
1166 effect_ids: vec![effect.id.clone()],
1167 });
1168 effects.push(effect);
1169 }
1170 Ok((effects, scripts))
1171}
1172
1173fn generated_effect(
1174 id: String,
1175 pattern: EffectPattern,
1176 target: EffectTarget,
1177 start_ms: u32,
1178 budgets: SceneBudgets,
1179 random: &mut SceneRandom,
1180) -> EffectPlan {
1181 let maximum_phases = budgets.max_phases_per_effect.min(3);
1182 let phase_count = random.range_u8(1, maximum_phases);
1183 let mut phases = Vec::with_capacity(usize::from(phase_count));
1184 let mut cursor_ms = start_ms;
1185 for _ in 0..phase_count {
1186 let maximum_duration = budgets.max_phase_ms.min(640);
1187 let minimum_duration = maximum_duration.min(120);
1188 let duration_ms = random.range_u16(minimum_duration, maximum_duration);
1189 phases.push(EffectPhase {
1190 at_ms: cursor_ms,
1191 duration_ms,
1192 });
1193 cursor_ms = cursor_ms.saturating_add(u32::from(duration_ms) + 30);
1194 }
1195 let displacement = i8::try_from(budgets.max_displacement).map_or(3, |value| value);
1196 EffectPlan {
1197 id,
1198 pattern,
1199 target,
1200 parameters: EffectParameters {
1201 intensity: random.range_u8(1, 3),
1202 offset_x: random.signed_range(displacement),
1203 offset_y: random.signed_range(displacement),
1204 fragments: random.range_u8(1, budgets.max_fragments),
1205 },
1206 phases,
1207 }
1208}
1209
1210fn target_for_pattern(
1211 pattern: EffectPattern,
1212 node_targets: &[String],
1213 diagram: &DiagramPlan,
1214 random: &mut SceneRandom,
1215) -> Result<EffectTarget, SceneError> {
1216 if matches!(pattern, EffectPattern::EdgeTraverse | EffectPattern::Packet) {
1217 let index = random.index(diagram.edges.len());
1218 return diagram
1219 .edges
1220 .get(index)
1221 .map(|edge| EffectTarget::Edge(edge.id.clone()))
1222 .ok_or(SceneError::InvalidContent("diagram edge target"));
1223 }
1224 let index = random.index(node_targets.len());
1225 node_targets
1226 .get(index)
1227 .cloned()
1228 .map(EffectTarget::Node)
1229 .ok_or(SceneError::InvalidContent("scene node target"))
1230}
1231
1232fn collect_effect_targets(node: &SceneNode, targets: &mut Vec<String>) {
1233 if node.effect_target {
1234 targets.push(node.id.clone());
1235 }
1236 for child in &node.children {
1237 collect_effect_targets(child, targets);
1238 }
1239}
1240
1241fn effect_end(effect: &EffectPlan) -> u32 {
1242 effect.phases.iter().fold(0, |end_ms, phase| {
1243 end_ms.max(phase.at_ms + u32::from(phase.duration_ms))
1244 })
1245}
1246
1247fn validate_plan(plan: &ScenePlan, budgets: SceneBudgets) -> Result<(), SceneError> {
1248 if plan.format_version != SCENE_FORMAT_VERSION {
1249 return Err(SceneError::InvalidIdentifier("scene format version"));
1250 }
1251 if plan.seed == 0 {
1252 return Err(SceneError::ZeroSeed);
1253 }
1254 validate_budgets(budgets)?;
1255 let mut node_ids = Vec::new();
1256 validate_tree(&plan.root, 1, budgets, &mut node_ids)?;
1257 let mut action_ids = Vec::new();
1258 collect_action_ids(&plan.root, &mut action_ids)?;
1259 for action_id in &action_ids {
1260 if node_ids.contains(action_id) {
1261 return Err(SceneError::InvalidIdentifier("duplicate action node"));
1262 }
1263 node_ids.push(action_id.clone());
1264 }
1265 if node_ids.len() > usize::from(budgets.max_nodes) {
1266 return Err(SceneError::BudgetExceeded("scene and action nodes"));
1267 }
1268 let diagram_node_limit = usize::from(budgets.max_diagram_nodes);
1269 if plan.diagram.nodes.len() > diagram_node_limit {
1270 return Err(SceneError::BudgetExceeded("diagram nodes"));
1271 }
1272 let diagram_edge_limit = usize::from(budgets.max_diagram_edges);
1273 if plan.diagram.edges.len() > diagram_edge_limit {
1274 return Err(SceneError::BudgetExceeded("diagram edges"));
1275 }
1276 for node in &plan.diagram.nodes {
1277 if node_ids.contains(&node.id) {
1278 return Err(SceneError::InvalidIdentifier("duplicate node"));
1279 }
1280 node_ids.push(node.id.clone());
1281 }
1282 let mut edge_ids = Vec::new();
1283 for edge in &plan.diagram.edges {
1284 if edge_ids.contains(&edge.id)
1285 || !node_ids.contains(&edge.from)
1286 || !node_ids.contains(&edge.to)
1287 {
1288 return Err(SceneError::InvalidIdentifier("diagram edge"));
1289 }
1290 edge_ids.push(edge.id.clone());
1291 }
1292 if plan.effects.len() > usize::from(budgets.max_effects) {
1293 return Err(SceneError::BudgetExceeded("effects"));
1294 }
1295 let mut effect_ids = Vec::new();
1296 for effect in &plan.effects {
1297 validate_effect(effect, &node_ids, &edge_ids, budgets)?;
1298 if effect_ids.contains(&effect.id) {
1299 return Err(SceneError::InvalidIdentifier("duplicate effect"));
1300 }
1301 effect_ids.push(effect.id.clone());
1302 }
1303 let mut triggers = Vec::new();
1304 for script in &plan.scripts {
1305 if triggers.contains(&script.trigger) {
1306 return Err(SceneError::InvalidIdentifier("duplicate interaction"));
1307 }
1308 if let InteractionTrigger::Action(action_id) = &script.trigger {
1309 if !action_ids.contains(action_id) {
1310 return Err(SceneError::InvalidIdentifier("interaction action"));
1311 }
1312 }
1313 triggers.push(script.trigger.clone());
1314 if script.effect_ids.is_empty()
1315 || script
1316 .effect_ids
1317 .iter()
1318 .any(|effect_id| !effect_ids.contains(effect_id))
1319 {
1320 return Err(SceneError::InvalidIdentifier("script effect"));
1321 }
1322 let script_effects = script
1323 .effect_ids
1324 .iter()
1325 .filter_map(|id| plan.effects.iter().find(|effect| effect.id == **id))
1326 .collect::<Vec<_>>();
1327 if script_effects
1328 .iter()
1329 .fold(0, |end_ms, effect| end_ms.max(effect_end(effect)))
1330 > budgets.max_interaction_ms
1331 {
1332 return Err(SceneError::BudgetExceeded("interaction duration"));
1333 }
1334 validate_live_effects(&script_effects, budgets.max_live_effects)?;
1335 }
1336 if !triggers.contains(&InteractionTrigger::Load)
1337 || action_ids
1338 .iter()
1339 .any(|action_id| !triggers.contains(&InteractionTrigger::Action(action_id.clone())))
1340 {
1341 return Err(SceneError::InvalidIdentifier("missing interaction"));
1342 }
1343 Ok(())
1344}
1345
1346fn validate_tree(
1347 node: &SceneNode,
1348 depth: u8,
1349 budgets: SceneBudgets,
1350 ids: &mut Vec<String>,
1351) -> Result<(), SceneError> {
1352 if depth > budgets.max_depth {
1353 return Err(SceneError::BudgetExceeded("scene depth"));
1354 }
1355 if ids.contains(&node.id) {
1356 return Err(SceneError::InvalidIdentifier("duplicate scene node"));
1357 }
1358 ids.push(node.id.clone());
1359 if ids.len() > usize::from(budgets.max_nodes) {
1360 return Err(SceneError::BudgetExceeded("scene nodes"));
1361 }
1362 for child in &node.children {
1363 validate_tree(child, depth + 1, budgets, ids)?;
1364 }
1365 Ok(())
1366}
1367
1368fn collect_action_ids(node: &SceneNode, ids: &mut Vec<String>) -> Result<(), SceneError> {
1369 if let SceneNodeContent::Actions { items } = &node.content {
1370 for action in items {
1371 if ids.contains(&action.id) {
1372 return Err(SceneError::InvalidIdentifier("duplicate action node"));
1373 }
1374 ids.push(action.id.clone());
1375 }
1376 }
1377 for child in &node.children {
1378 collect_action_ids(child, ids)?;
1379 }
1380 Ok(())
1381}
1382
1383fn validate_live_effects(effects: &[&EffectPlan], maximum_live: u8) -> Result<(), SceneError> {
1384 let intervals = effects
1385 .iter()
1386 .flat_map(|effect| {
1387 effect
1388 .phases
1389 .iter()
1390 .map(|phase| (phase.at_ms, phase.at_ms + u32::from(phase.duration_ms)))
1391 })
1392 .collect::<Vec<_>>();
1393 let exceeds_limit = intervals.iter().any(|(start, _)| {
1394 intervals
1395 .iter()
1396 .filter(|(other_start, other_end)| other_start <= start && start < other_end)
1397 .count()
1398 > usize::from(maximum_live)
1399 });
1400 if exceeds_limit {
1401 return Err(SceneError::BudgetExceeded("simultaneously live effects"));
1402 }
1403 Ok(())
1404}
1405
1406fn validate_effect(
1407 effect: &EffectPlan,
1408 node_ids: &[String],
1409 edge_ids: &[String],
1410 budgets: SceneBudgets,
1411) -> Result<(), SceneError> {
1412 let target_valid = match &effect.target {
1413 EffectTarget::Node(id) => node_ids.contains(id),
1414 EffectTarget::Edge(id) => edge_ids.contains(id),
1415 };
1416 if !target_valid {
1417 return Err(SceneError::InvalidIdentifier("effect target"));
1418 }
1419 let target_kind_valid = matches!(
1420 (&effect.pattern, &effect.target),
1421 (
1422 EffectPattern::EdgeTraverse | EffectPattern::Packet,
1423 EffectTarget::Edge(_)
1424 ) | (
1425 EffectPattern::Pulse
1426 | EffectPattern::Glitch
1427 | EffectPattern::Invert
1428 | EffectPattern::Fragment
1429 | EffectPattern::Scanline,
1430 EffectTarget::Node(_)
1431 )
1432 );
1433 if !target_kind_valid {
1434 return Err(SceneError::InvalidIdentifier("pattern target kind"));
1435 }
1436 if effect.phases.is_empty() || effect.phases.len() > usize::from(budgets.max_phases_per_effect)
1437 {
1438 return Err(SceneError::BudgetExceeded("effect phases"));
1439 }
1440 for phase in &effect.phases {
1441 if phase.duration_ms == 0 || phase.duration_ms > budgets.max_phase_ms {
1442 return Err(SceneError::BudgetExceeded("phase duration"));
1443 }
1444 }
1445 if effect
1446 .phases
1447 .windows(2)
1448 .any(|pair| pair[0].at_ms > pair[1].at_ms)
1449 {
1450 return Err(SceneError::InvalidIdentifier("phase order"));
1451 }
1452 let displacement_limit = i16::from(budgets.max_displacement);
1453 if i16::from(effect.parameters.offset_x).abs() > displacement_limit
1454 || i16::from(effect.parameters.offset_y).abs() > displacement_limit
1455 || effect.parameters.fragments == 0
1456 || effect.parameters.fragments > budgets.max_fragments
1457 || !(1..=3).contains(&effect.parameters.intensity)
1458 {
1459 return Err(SceneError::BudgetExceeded("effect parameters"));
1460 }
1461 Ok(())
1462}
1463
1464fn validate_geometry(plan: &ScenePlan, geometry: &[NodeGeometry]) -> Result<(), SceneError> {
1465 let mut required = Vec::new();
1466 for effect in &plan.effects {
1467 match &effect.target {
1468 EffectTarget::Node(id) => push_unique(&mut required, id),
1469 EffectTarget::Edge(id) => {
1470 let edge = plan
1471 .diagram
1472 .edges
1473 .iter()
1474 .find(|edge| edge.id == *id)
1475 .ok_or(SceneError::InvalidIdentifier("effect edge"))?;
1476 push_unique(&mut required, &edge.from);
1477 push_unique(&mut required, &edge.to);
1478 }
1479 }
1480 }
1481 let mut seen = Vec::new();
1482 for measurement in geometry {
1483 if seen.contains(&measurement.id) {
1484 return Err(SceneError::InvalidGeometry("duplicate node"));
1485 }
1486 seen.push(measurement.id.clone());
1487 if !rect_is_valid(measurement.rect)
1488 || !point_is_finite(measurement.incoming)
1489 || !point_is_finite(measurement.outgoing)
1490 {
1491 return Err(SceneError::InvalidGeometry("non-finite node"));
1492 }
1493 }
1494 if required.iter().any(|id| !seen.contains(id)) {
1495 return Err(SceneError::InvalidGeometry("missing required node"));
1496 }
1497 Ok(())
1498}
1499
1500fn push_unique(values: &mut Vec<String>, value: &str) {
1501 if !values.iter().any(|existing| existing == value) {
1502 values.push(value.to_owned());
1503 }
1504}
1505
1506fn point_is_finite(point: Point) -> bool {
1507 point.x.is_finite() && point.y.is_finite()
1508}
1509
1510fn rect_is_valid(rect: Rect) -> bool {
1511 rect.x.is_finite()
1512 && rect.y.is_finite()
1513 && rect.width.is_finite()
1514 && rect.height.is_finite()
1515 && rect.width > 0.0
1516 && rect.height > 0.0
1517}
1518
1519fn push_effect_event(
1520 events: &mut Vec<SceneEvent>,
1521 effect: &EffectPlan,
1522 phase: EffectPhase,
1523 plan: &ScenePlan,
1524 geometry: &[NodeGeometry],
1525) -> Result<(), SceneError> {
1526 match (&effect.pattern, &effect.target) {
1527 (EffectPattern::Pulse, EffectTarget::Node(id)) => {
1528 let measurement = find_geometry(geometry, id)?;
1529 events.push(SceneEvent::NodeActivated {
1530 target_id: id.clone(),
1531 point: rect_center(measurement.rect),
1532 at_ms: phase.at_ms,
1533 duration_ms: phase.duration_ms,
1534 intensity: effect.parameters.intensity,
1535 });
1536 }
1537 (EffectPattern::Glitch, EffectTarget::Node(id)) => {
1538 events.push(SceneEvent::BackingGlitched {
1539 target_id: id.clone(),
1540 at_ms: phase.at_ms,
1541 duration_ms: phase.duration_ms,
1542 offset_x: effect.parameters.offset_x,
1543 offset_y: effect.parameters.offset_y,
1544 });
1545 }
1546 (EffectPattern::Invert, EffectTarget::Node(id)) => {
1547 events.push(SceneEvent::BackingInverted {
1548 target_id: id.clone(),
1549 at_ms: phase.at_ms,
1550 duration_ms: phase.duration_ms,
1551 });
1552 }
1553 (EffectPattern::Fragment, EffectTarget::Node(id)) => {
1554 let measurement = find_geometry(geometry, id)?;
1555 events.push(SceneEvent::FragmentsEmitted {
1556 target_id: id.clone(),
1557 point: rect_center(measurement.rect),
1558 at_ms: phase.at_ms,
1559 duration_ms: phase.duration_ms,
1560 count: effect.parameters.fragments,
1561 });
1562 }
1563 (EffectPattern::Scanline, EffectTarget::Node(id)) => {
1564 let measurement = find_geometry(geometry, id)?;
1565 events.push(SceneEvent::ScanlineSwept {
1566 target_id: id.clone(),
1567 rect: measurement.rect,
1568 at_ms: phase.at_ms,
1569 duration_ms: phase.duration_ms,
1570 });
1571 }
1572 (EffectPattern::EdgeTraverse, EffectTarget::Edge(id)) => {
1573 let (from, to) = measured_edge(plan, geometry, id)?;
1574 events.push(SceneEvent::EdgeTraversed {
1575 edge_id: id.clone(),
1576 from,
1577 to,
1578 at_ms: phase.at_ms,
1579 duration_ms: phase.duration_ms,
1580 });
1581 }
1582 (EffectPattern::Packet, EffectTarget::Edge(id)) => {
1583 let (from, to) = measured_edge(plan, geometry, id)?;
1584 events.push(SceneEvent::PacketTraversed {
1585 edge_id: id.clone(),
1586 from,
1587 to,
1588 at_ms: phase.at_ms,
1589 duration_ms: phase.duration_ms,
1590 });
1591 }
1592 _ => return Err(SceneError::InvalidIdentifier("pattern target kind")),
1593 }
1594 Ok(())
1595}
1596
1597fn find_geometry<'a>(
1598 geometry: &'a [NodeGeometry],
1599 id: &str,
1600) -> Result<&'a NodeGeometry, SceneError> {
1601 geometry
1602 .iter()
1603 .find(|measurement| measurement.id == id)
1604 .ok_or(SceneError::InvalidGeometry("missing effect target"))
1605}
1606
1607fn measured_edge(
1608 plan: &ScenePlan,
1609 geometry: &[NodeGeometry],
1610 id: &str,
1611) -> Result<(Point, Point), SceneError> {
1612 let edge = plan
1613 .diagram
1614 .edges
1615 .iter()
1616 .find(|edge| edge.id == id)
1617 .ok_or(SceneError::InvalidIdentifier("diagram edge"))?;
1618 let from = find_geometry(geometry, &edge.from)?;
1619 let to = find_geometry(geometry, &edge.to)?;
1620 Ok((from.outgoing, to.incoming))
1621}
1622
1623fn rect_center(rect: Rect) -> Point {
1624 Point::new(rect.x + rect.width / 2.0, rect.y + rect.height / 2.0)
1625}
1626
1627fn event_time(event: &SceneEvent) -> u32 {
1628 match event {
1629 SceneEvent::InteractionStarted { at_ms }
1630 | SceneEvent::PhaseStarted { at_ms, .. }
1631 | SceneEvent::NodeActivated { at_ms, .. }
1632 | SceneEvent::BackingGlitched { at_ms, .. }
1633 | SceneEvent::BackingInverted { at_ms, .. }
1634 | SceneEvent::FragmentsEmitted { at_ms, .. }
1635 | SceneEvent::EdgeTraversed { at_ms, .. }
1636 | SceneEvent::PacketTraversed { at_ms, .. }
1637 | SceneEvent::ScanlineSwept { at_ms, .. }
1638 | SceneEvent::InteractionFinished { at_ms } => *at_ms,
1639 }
1640}
1641
1642struct SceneRandom {
1643 state: u64,
1644}
1645
1646impl SceneRandom {
1647 const fn new(seed: u64) -> Self {
1648 Self {
1649 state: seed ^ 0xa076_1d64_78bd_642f,
1650 }
1651 }
1652
1653 fn next_u64(&mut self) -> u64 {
1654 self.state = self.state.wrapping_add(0x9e37_79b9_7f4a_7c15);
1655 let mut value = self.state;
1656 value = (value ^ (value >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
1657 value = (value ^ (value >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
1658 value ^ (value >> 31)
1659 }
1660
1661 fn index(&mut self, length: usize) -> usize {
1662 if length == 0 {
1663 return 0;
1664 }
1665 usize::from(self.next_u64().to_le_bytes()[0]) % length
1666 }
1667
1668 fn layout(&mut self) -> LayoutProfile {
1669 match self.index(7) {
1670 0 => LayoutProfile::Instrument,
1671 1 => LayoutProfile::Split,
1672 2 => LayoutProfile::Asymmetric,
1673 3 => LayoutProfile::ResultLed,
1674 4 => LayoutProfile::DiagramLed,
1675 5 => LayoutProfile::Terminal,
1676 _ => LayoutProfile::Editorial,
1677 }
1678 }
1679
1680 fn diagram_form(&mut self) -> DiagramForm {
1681 match self.index(4) {
1682 0 => DiagramForm::Linear,
1683 1 => DiagramForm::Tree,
1684 2 => DiagramForm::State,
1685 _ => DiagramForm::Network,
1686 }
1687 }
1688
1689 fn button_size(&mut self) -> ButtonSize {
1690 match self.index(3) {
1691 0 => ButtonSize::Compact,
1692 1 => ButtonSize::Regular,
1693 _ => ButtonSize::Prominent,
1694 }
1695 }
1696
1697 fn pattern(&mut self, allow_edge: bool) -> EffectPattern {
1698 match self.index(if allow_edge { 7 } else { 5 }) {
1699 0 => EffectPattern::Pulse,
1700 1 => EffectPattern::Glitch,
1701 2 => EffectPattern::Invert,
1702 3 => EffectPattern::Fragment,
1703 4 => EffectPattern::Scanline,
1704 5 => EffectPattern::EdgeTraverse,
1705 _ => EffectPattern::Packet,
1706 }
1707 }
1708
1709 fn action_pattern(&mut self) -> EffectPattern {
1710 match self.index(4) {
1711 0 => EffectPattern::Pulse,
1712 1 => EffectPattern::Glitch,
1713 2 => EffectPattern::Invert,
1714 _ => EffectPattern::Fragment,
1715 }
1716 }
1717
1718 fn range_u8(&mut self, minimum: u8, maximum: u8) -> u8 {
1719 let width = maximum - minimum + 1;
1720 minimum + self.next_u64().to_le_bytes()[0] % width
1721 }
1722
1723 fn range_u16(&mut self, minimum: u16, maximum: u16) -> u16 {
1724 let width = maximum - minimum + 1;
1725 let sample = u16::from(self.next_u64().to_le_bytes()[0]);
1726 minimum + sample % width
1727 }
1728
1729 fn signed_range(&mut self, maximum: i8) -> i8 {
1730 if maximum == 0 {
1731 return 0;
1732 }
1733 let width = u8::try_from(i16::from(maximum) * 2 + 1).map_or(1, |value| value);
1734 let sample = self.next_u64().to_le_bytes()[0] % width;
1735 i8::try_from(sample).map_or(0, |value| value) - maximum
1736 }
1737}