Skip to main content

euv_example/state/
impl.rs

1use super::*;
2
3/// Lazy constructor for `ReactiveSignals`.
4impl ReactiveSignals {
5    /// Materializes the `/reactive` counter and derived `computed!` memo on first access.
6    ///
7    /// # Returns
8    ///
9    /// - `Self` - Initialized `/reactive` signal group.
10    #[must_use]
11    pub(crate) fn create() -> Self {
12        let counter: Signal<i32> = Signal::new(1);
13        let doubled: Memo<i32> = computed!((counter) -> i32 => move |n: i32| n * 2);
14        Self { counter, doubled }
15    }
16}
17
18/// Lazy constructor for `RenderWindowSignals`.
19impl RenderWindowSignals {
20    /// Materializes the `/render` and `/window` OS capability signals on first access.
21    ///
22    /// # Arguments
23    ///
24    /// - `usize` - Default host platform selector index.
25    ///
26    /// # Returns
27    ///
28    /// - `Self` - Initialized `/render` and `/window` signal group.
29    #[must_use]
30    pub(crate) fn create(default_plat_idx: usize) -> Self {
31        Self {
32            render_mode_index: Signal::new(0),
33            demo_fps_cap_index: Signal::new(0),
34            fullscreen: Signal::new(false),
35            island_active: Signal::new(false),
36            island_progress: Signal::new(25),
37            camera_perm_status: Signal::new(DEFAULT_CAMERA_PERM.to_string()),
38            protocol_status: Signal::new(DEFAULT_PROTOCOL_STATUS.to_string()),
39            a11y_announcements: Signal::new(0),
40            haptic_pulses: Signal::new(0),
41            os_target_platform_idx: Signal::new(default_plat_idx),
42            island_mode_idx: Signal::new(0),
43            system_notifications: Signal::new(vec![(
44                DEFAULT_SYS_NOTIF_TITLE.to_string(),
45                DEFAULT_SYS_NOTIF_BODY.to_string(),
46            )]),
47            permission_statuses: Signal::new(vec![PermissionStatus::NotDetermined; 14]),
48        }
49    }
50}
51
52/// Lazy constructor for `FormsSignals`.
53impl FormsSignals {
54    /// Materializes the `/forms` interactive control signals on first access.
55    ///
56    /// # Returns
57    ///
58    /// - `Self` - Initialized `/forms` signal group.
59    #[must_use]
60    pub(crate) fn create() -> Self {
61        Self {
62            username: Signal::new(DEFAULT_USERNAME.to_string()),
63            bio: Signal::new(DEFAULT_BIO_TEXT.to_string()),
64            stepper_value: Signal::new(4),
65            radio_index: Signal::new(1),
66            slider_value: Signal::new(65.0),
67            select_index: Signal::new(0),
68            select_open: Signal::new(false),
69            rating_value: Signal::new(4),
70            pin_toggled: Signal::new(false),
71            hardware_accel: Signal::new(true),
72            agree_terms: Signal::new(true),
73            active_tab: Signal::new(0),
74            page_index: Signal::new(1),
75            step_index: Signal::new(1),
76            accordion_open: Signal::new(Some(0)),
77            picker_color: Signal::new(Color::hex(0x2563EB)),
78            picker_time: Signal::new((14, 30)),
79            tag_items: Signal::new(vec![
80                DEFAULT_TAG_RUST.to_string(),
81                DEFAULT_TAG_NATIVE.to_string(),
82                DEFAULT_TAG_WASM.to_string(),
83            ]),
84            tree_selected: Signal::new(None),
85            breadcrumb_active: Signal::new(2),
86        }
87    }
88}
89
90/// Lazy constructor for `OverlaysSignals`.
91impl OverlaysSignals {
92    /// Materializes the `/overlays` modal, drawer, sheet, and toast signals on first access.
93    ///
94    /// # Returns
95    ///
96    /// - `Self` - Initialized `/overlays` signal group.
97    #[must_use]
98    pub(crate) fn create() -> Self {
99        Self {
100            modal_open: Signal::new(false),
101            drawer_open: Signal::new(false),
102            sheet_open: Signal::new(false),
103            popover_open: Signal::new(false),
104            dropdown_open: Signal::new(false),
105            dropdown_selected: Signal::new(None),
106            toast_visible: Signal::new(false),
107            notif_visible: Signal::new(false),
108            loading_active: Signal::new(false),
109        }
110    }
111}
112
113/// Lazy constructor for `DataSignals`.
114impl DataSignals {
115    /// Materializes the `/data` virtualized list scroll signal on first access.
116    ///
117    /// # Returns
118    ///
119    /// - `Self` - Initialized `/data` signal group.
120    #[must_use]
121    pub(crate) fn create() -> Self {
122        Self {
123            list_scroll_y: Signal::new(640.0),
124        }
125    }
126}
127
128/// Lazy constructor and shared-cell accessor for `Engine3dSignals`.
129impl Engine3dSignals {
130    /// Materializes the `/game3d` quality, ray-tracing, lighting, and camera control signals on first access.
131    ///
132    /// # Returns
133    ///
134    /// - `Self` - Initialized `/game3d` signal group.
135    #[must_use]
136    pub(crate) fn create() -> Self {
137        Self {
138            engine3d_quality: Signal::new(RenderQualityConfig::from_preset(
139                QualityPreset::Cinematic,
140            )),
141            engine3d_preset_idx: Signal::new(4),
142            engine3d_rt_idx: Signal::new(3),
143            engine3d_res_scale: Signal::new(100.0),
144            engine3d_time_of_day: Signal::new(17.2),
145            engine3d_import_queue: Signal::new(0),
146            engine3d_import_status: Signal::new(DEFAULT_ENGINE3D_STATUS.to_string()),
147            engine3d_camera_mode: Signal::new(0),
148            engine3d_tsr_idx: Signal::new(0),
149            engine3d_atmosphere_idx: Signal::new(0),
150        }
151    }
152
153    /// Returns the cached `Engine3dSignals` inside `cell`, materializing it once inside `owner_scope` on first call.
154    ///
155    /// # Arguments
156    ///
157    /// - `&Cell<Option<Self>>` - Shared lazy signal cell.
158    /// - `Scope` - Root ownership scope keeping materialized signals alive across page unmounts.
159    ///
160    /// # Returns
161    ///
162    /// - `Self` - Active `/game3d` signal group.
163    #[must_use]
164    pub(crate) fn get_or_init(cell: &Cell<Option<Self>>, owner_scope: Scope) -> Self {
165        if let Some(existing) = cell.get() {
166            return existing;
167        }
168        let created: Self = owner_scope.enter(Self::create);
169        cell.set(Some(created));
170        created
171    }
172}
173
174/// Lazy constructor and shared-cell accessor for `DynamicSignals`.
175impl DynamicSignals {
176    /// Materializes the `/dynamic` OTA and WASM control signals on first access.
177    ///
178    /// # Returns
179    ///
180    /// - `Self` - Initialized `/dynamic` signal group.
181    #[must_use]
182    pub(crate) fn create() -> Self {
183        Self {
184            sibling_counter: Signal::new(0),
185            dynamic_action_log: Signal::new(DEFAULT_DYNAMIC_ACTION_LOG.to_string()),
186            wasm_offline: Signal::new(false),
187            wasm_fault_status: Signal::new(DEFAULT_WASM_STATUS.to_string()),
188            wasm_bg_task: Signal::new(None),
189        }
190    }
191
192    /// Returns the cached `DynamicSignals` inside `cell`, materializing it once inside `owner_scope` on first call.
193    ///
194    /// # Arguments
195    ///
196    /// - `&Cell<Option<Self>>` - Shared lazy signal cell.
197    /// - `Scope` - Root ownership scope keeping materialized signals alive across global WASM slot swaps.
198    ///
199    /// # Returns
200    ///
201    /// - `Self` - Active `/dynamic` signal group.
202    #[must_use]
203    pub(crate) fn get_or_init(cell: &Cell<Option<Self>>, owner_scope: Scope) -> Self {
204        if let Some(existing) = cell.get() {
205            return existing;
206        }
207        let created: Self = owner_scope.enter(Self::create);
208        cell.set(Some(created));
209        created
210    }
211}
212
213/// Lazy constructor for `LabSignals`.
214impl LabSignals {
215    /// Materializes the `/lab` shadcn/ui component gallery and edge-case signals on first access.
216    ///
217    /// # Returns
218    ///
219    /// - `Self` - Initialized `/lab` signal group.
220    #[must_use]
221    pub(crate) fn create() -> Self {
222        Self {
223            alert_dialog_open: Signal::new(false),
224            alert_dialog_confirmed: Signal::new(false),
225            collapsible_open: Signal::new(true),
226            toggle_group_index: Signal::new(0),
227            otp_code: Signal::new(DEFAULT_OTP_CODE.to_string()),
228            command_query: Signal::new(String::new()),
229            command_selected: Signal::new(Some(0)),
230            hover_card_open: Signal::new(false),
231            calendar_day: Signal::new(25),
232            menubar_active: Signal::new(None),
233            carousel_index: Signal::new(0),
234            lab_combobox_query: Signal::new(String::new()),
235            lab_combobox_selected: Signal::new(0),
236            lab_combobox_open: Signal::new(false),
237            lab_table_filter: Signal::new(String::new()),
238            lab_table_sort_asc: Signal::new(true),
239            lab_table_selected: Signal::new(Some(0)),
240            lab_date_day: Signal::new(26),
241            lab_date_open: Signal::new(false),
242            lab_input_group_val: Signal::new(DEFAULT_INPUT_GROUP_VAL.to_string()),
243            lab_native_select_idx: Signal::new(0),
244            lab_nav_menu_active: Signal::new(None),
245            lab_split_ratio: Signal::new(0.45),
246            lab_block_scroll_chain: Signal::new(false),
247            lab_stop_click_bubble: Signal::new(true),
248            lab_parent_clicks: Signal::new(0),
249            lab_child_clicks: Signal::new(0),
250            lab_resize_preserve_count: Signal::new(1),
251            lab_rtl_mode: Signal::new(false),
252        }
253    }
254}
255
256/// Lazy constructor for `MediaSignals`.
257impl MediaSignals {
258    /// Materializes the `/media` Media Studio playback signals on first access.
259    ///
260    /// # Returns
261    ///
262    /// - `Self` - Initialized `/media` signal group.
263    #[must_use]
264    pub(crate) fn create() -> Self {
265        Self {
266            media_gif: Signal::new(GifAnimation::default()),
267            media_live: Signal::new(LivePhotoAsset::default()),
268            media_video: Signal::new(VideoTrack::default()),
269            media_audio: Signal::new(AudioTrack::default()),
270            media_pdf: Signal::new(PdfDocument::default()),
271            media_html_link_log: Signal::new(DEFAULT_MEDIA_LINK_LOG.to_string()),
272            media_loading: Signal::new(false),
273            media_bg_task: Signal::new(None),
274        }
275    }
276}
277
278/// Lazy constructor for `MarkdownSignals`.
279impl MarkdownSignals {
280    /// Materializes the `/markdown` Markdown & Code Studio signals on first access.
281    ///
282    /// # Returns
283    ///
284    /// - `Self` - Initialized `/markdown` signal group.
285    #[must_use]
286    pub(crate) fn create() -> Self {
287        Self {
288            markdown_copy_log: Signal::new(DEFAULT_MD_COPY_LOG.to_string()),
289            markdown_link_log: Signal::new(DEFAULT_MD_LINK_LOG.to_string()),
290            markdown_tasks_toggled: Signal::new(0),
291            markdown_lang_tab: Signal::new(0),
292            markdown_selectable: Signal::new(true),
293        }
294    }
295}
296
297/// Lazy constructor for `StressSignals`.
298impl StressSignals {
299    /// Materializes the `/stress` interactive UI stress benchmark signals on first access.
300    ///
301    /// # Returns
302    ///
303    /// - `Self` - Initialized `/stress` signal group.
304    #[must_use]
305    pub(crate) fn create() -> Self {
306        Self {
307            stress_results: Signal::new(Vec::new()),
308            stress_summary: Signal::new(STRESS_SUMMARY_READY.to_string()),
309        }
310    }
311}
312
313/// Lazy constructor for `ChartsSignals`.
314impl ChartsSignals {
315    /// Materializes the `/charts` ECharts Studio filter and readout signals on first access.
316    ///
317    /// # Returns
318    ///
319    /// - `Self` - Initialized `/charts` signal group.
320    #[must_use]
321    pub(crate) fn create() -> Self {
322        Self {
323            charts_category_idx: Signal::new(0),
324            charts_event_log: Signal::new(CHARTS_EVENT_READY.to_string()),
325        }
326    }
327}
328
329/// Lazy constructor for `WaterSignals`.
330impl WaterSignals {
331    /// Materializes the `/water` liquid physics control and telemetry signals on first access.
332    ///
333    /// # Returns
334    ///
335    /// - `Self` - Initialized `/water` signal group.
336    #[must_use]
337    pub(crate) fn create() -> Self {
338        Self {
339            fill_pct: Signal::new(FLUID_DEFAULT_FILL_RATIO * 100.0),
340            viscosity_idx: Signal::new(0),
341            buoyant_enabled: Signal::new(true),
342            fullscreen_open: Signal::new(false),
343            sensor_perm_status: Signal::new(WATER_PERM_DESKTOP_STATUS.to_string()),
344            stats: Signal::new(GyroLiquidStats::default()),
345        }
346    }
347}
348
349/// Lazy scene creation and zero-boot-cost handle accessors for `LazyWaterScene`.
350impl LazyWaterScene {
351    /// Creates a zero-allocation lazy placeholder bound to shared `scene_cell` and `signals_cell`.
352    ///
353    /// # Arguments
354    ///
355    /// - `Rc<RefCell<Option<GyroLiquidGameScene>>>` - Shared cell lazily storing the active liquid scene.
356    /// - `Rc<Cell<Option<WaterSignals>>>` - Shared cell storing `/water` reactive signals.
357    ///
358    /// # Returns
359    ///
360    /// - `Self` - Uninitialized lazy liquid scene wrapper.
361    #[must_use]
362    pub(crate) fn create_deferred(
363        scene_cell: Rc<RefCell<Option<GyroLiquidGameScene>>>,
364        signals_cell: Rc<Cell<Option<WaterSignals>>>,
365    ) -> Self {
366        Self {
367            scene_cell,
368            signals_cell,
369            stats_throttle_tick: Rc::new(Cell::new(0)),
370        }
371    }
372
373    /// Publishes `next` into the `/water` telemetry signal immediately when physical state changed, throttling timing-only jitter updates to once every 10 frames.
374    ///
375    /// # Arguments
376    ///
377    /// - `GyroLiquidStats` - Latest liquid physics and frame-timing snapshot.
378    fn sync_water_stats_throttled(&self, next: GyroLiquidStats) {
379        let Some(sig) = self.get_signals_cell().get() else {
380            return;
381        };
382        let stats_sig: Signal<GyroLiquidStats> = sig.get_stats();
383        let prev: GyroLiquidStats = stats_sig.get_untracked();
384        let state_changed: bool = prev.get_sensor_active() != next.get_sensor_active()
385            || prev.get_particle_count() != next.get_particle_count()
386            || prev.get_buoyant_body_count() != next.get_buoyant_body_count()
387            || prev.get_bubble_count() != next.get_bubble_count()
388            || (prev.get_tilt_angle_deg() - next.get_tilt_angle_deg()).abs() > 0.25
389            || (prev.get_gravity_x() - next.get_gravity_x()).abs() > 0.15
390            || (prev.get_gravity_y() - next.get_gravity_y()).abs() > 0.15
391            || (prev.get_fill_ratio() - next.get_fill_ratio()).abs() > 0.005
392            || (prev.get_kinetic_energy_mj() - next.get_kinetic_energy_mj()).abs() > 0.08;
393        let tick: u8 = self.get_stats_throttle_tick().get().wrapping_add(1);
394        if state_changed || tick >= 10 {
395            self.get_stats_throttle_tick().set(0);
396            let _: bool = stats_sig.set_if_changed(next);
397        } else {
398            self.get_stats_throttle_tick().set(tick);
399        }
400    }
401
402    /// Returns the active `GyroLiquidGameScene`, initializing it lazily on first access.
403    ///
404    /// # Arguments
405    ///
406    /// - `&Self` - Lazy water scene reference.
407    ///
408    /// # Returns
409    ///
410    /// - `GyroLiquidGameScene` - Active shareable liquid physics scene handle.
411    #[must_use]
412    pub(crate) fn ensure_scene(&self) -> GyroLiquidGameScene {
413        if let Some(existing) = self.get_scene_cell().borrow().as_ref() {
414            return existing.clone();
415        }
416        let created: GyroLiquidGameScene = GyroLiquidGameScene::default();
417        *self.get_scene_cell().borrow_mut() = Some(created.clone());
418        created
419    }
420}
421
422/// `GameScene` delegation forwarding fixed physics steps and zero-copy optical rendering to the lazily initialized `GyroLiquidGameScene`.
423impl GameScene for LazyWaterScene {
424    /// Steps the SI PBF liquid simulation and mirrors live `GyroLiquidStats` into `/water` signals.
425    ///
426    /// # Arguments
427    ///
428    /// - `&Self` - Mutable lazy water scene wrapper.
429    /// - `f32` - Fixed simulation timestep in seconds.
430    /// - `&InputState` - Real-time polled pointer and keyboard input state.
431    fn fixed_update(&mut self, dt: f32, input: &InputState) {
432        let mut scene: GyroLiquidGameScene = self.ensure_scene();
433        scene.fixed_update(dt, input);
434        self.sync_water_stats_throttled(scene.stats());
435    }
436
437    /// Renders the optical liquid frame into `ctx` and mirrors updated frame timings into `/water` signals.
438    ///
439    /// # Arguments
440    ///
441    /// - `&Self` - Mutable lazy water scene wrapper.
442    /// - `f32` - Interpolation alpha in `[0.0, 1.0]`.
443    /// - `&mut GameRenderContext<'_>` - Active viewport draw surface.
444    fn render(&mut self, alpha: f32, ctx: &mut GameRenderContext<'_>) {
445        let mut scene: GyroLiquidGameScene = self.ensure_scene();
446        scene.render(alpha, ctx);
447        self.sync_water_stats_throttled(scene.stats());
448    }
449}
450
451/// Construction, lazy signal accessors, async preloaders, and lifecycle helpers for `ShowcaseState`.
452impl ShowcaseState {
453    /// Initializes a minimal-boot `ShowcaseState` using a fresh `DynamicUpdateHub` and synchronous lazy route hydration.
454    ///
455    /// # Returns
456    ///
457    /// - `Self` - Initialized reactive showcase state.
458    #[must_use]
459    pub fn new() -> Self {
460        Self::new_with_hub(DynamicUpdateHub::new(), false)
461    }
462
463    /// Initializes a minimal-boot `ShowcaseState` bound directly to `hub` without allocating discarded hubs or managers.
464    ///
465    /// # Arguments
466    ///
467    /// - `DynamicUpdateHub` - Active `App` dynamic update hub to attach directly.
468    /// - `bool` - When `true`, offloads heavy `/media`, `/dynamic`, and `/game3d` route payloads onto background worker threads on native targets.
469    ///
470    /// # Returns
471    ///
472    /// - `Self` - Initialized reactive showcase state with only core shell signals allocated at boot.
473    #[must_use]
474    pub fn new_with_hub(hub: DynamicUpdateHub, bg_workers: bool) -> Self {
475        let (state_scope, _): (Scope, ()) = Scope::run(|_: Scope| {});
476        let arena: DemoPhysicsScene = DemoPhysicsScene::create_lazy_arena();
477        let game_host: GameEngineHost = GameEngineHost::new(arena, 1.0 / 60.0);
478        game_host.set_paused(true);
479        let engine3d_signals: Rc<Cell<Option<Engine3dSignals>>> = Rc::new(Cell::new(None));
480        let bg_workers_enabled: Rc<Cell<bool>> = Rc::new(Cell::new(bg_workers));
481        let scene3d: DemoOpenWorld3DScene = DemoOpenWorld3DScene::create_lazy_city_deferred(
482            engine3d_signals.clone(),
483            state_scope,
484            bg_workers_enabled.clone(),
485        );
486        let game3d_host: GameEngineHost = GameEngineHost::new(scene3d, 1.0 / 60.0);
487        game3d_host.set_paused(true);
488        let water_scene_cell: Rc<RefCell<Option<GyroLiquidGameScene>>> =
489            Rc::new(RefCell::new(None));
490        let water_signals: Rc<Cell<Option<WaterSignals>>> = Rc::new(Cell::new(None));
491        let lazy_water: LazyWaterScene =
492            LazyWaterScene::create_deferred(water_scene_cell.clone(), water_signals.clone());
493        let water_host: GameEngineHost = GameEngineHost::new(lazy_water, 1.0 / 60.0);
494        water_host.set_paused(true);
495        let router: EuvRouter = EuvRouter::new(ROUTE_OVERVIEW)
496            .with_default_retention(PageRetention::Freeze)
497            .with_dynamic_hub(hub.clone());
498        let wasm_registry: RegistryWasmFetcher = RegistryWasmFetcher::default();
499        let wasm_manager: WasmDynamicManager = WasmDynamicManager::new(
500            hub.clone(),
501            Rc::new(wasm_registry.clone()),
502            WasmSandboxConfig::default(),
503        );
504        let (
505            default_active_backend,
506            default_rec_backend,
507            default_cpu_mirror,
508            default_timing,
509            default_upload,
510        ): (&str, &str, bool, &str, &str) =
511            Self::default_adaptive_render_profile(current_platform());
512        let state: Self = Self {
513            route: Signal::new(ROUTE_OVERVIEW.to_string()),
514            state_scope,
515            theme: UiThemeState::new(active_feature_scheme(), ThemeMode::Light),
516            game_host,
517            game3d_host,
518            water_host,
519            water_scene_cell,
520            dynamic_hub: hub,
521            wasm_registry,
522            wasm_manager,
523            cmd_palette_open: Signal::new(false),
524            cmd_palette_query: Signal::new(String::new()),
525            auto_hide_chrome: Signal::new(true),
526            show_fps_hud: Signal::new(true),
527            swipe_routing: Signal::new(true),
528            reduced_motion: Signal::new(false),
529            adaptive_auto_switch: Signal::new(false),
530            adaptive_active_backend: Signal::new(default_active_backend.to_string()),
531            adaptive_recommended_backend: Signal::new(default_rec_backend.to_string()),
532            adaptive_cpu_mirror_active: Signal::new(default_cpu_mirror),
533            adaptive_present_timing_source: Signal::new(default_timing.to_string()),
534            adaptive_upload_strategy: Signal::new(default_upload.to_string()),
535            adaptive_handoff_attempts: Signal::new(0),
536            adaptive_handoff_successes: Signal::new(0),
537            adaptive_handoff_aborts: Signal::new(0),
538            router,
539            router_ready: Rc::new(Cell::new(false)),
540            lifecycle_mounts: Signal::new(0),
541            lifecycle_freezes: Signal::new(0),
542            lifecycle_resumes: Signal::new(0),
543            lifecycle_destroys: Signal::new(0),
544            lifecycle_last_event: Signal::new(DEFAULT_LIFECYCLE_BOOT.to_string()),
545            system_event_log: Signal::new(vec![DEFAULT_SYS_EVENT_LOG.to_string()]),
546            system_event_count: Signal::new(0),
547            bg_frozen: Signal::new(false),
548            bg_freeze_count: Signal::new(0),
549            bg_restore_count: Signal::new(0),
550            bg_snap_game2d_running: Rc::new(Cell::new(false)),
551            bg_snap_game3d_running: Rc::new(Cell::new(false)),
552            bg_snap_water_running: Rc::new(Cell::new(false)),
553            bg_snap_gif_playing: Rc::new(Cell::new(false)),
554            bg_snap_live_playing: Rc::new(Cell::new(false)),
555            bg_snap_video_playing: Rc::new(Cell::new(false)),
556            bg_snap_audio_playing: Rc::new(Cell::new(false)),
557            media_loaded: Rc::new(Cell::new(false)),
558            wasm_registry_loaded: Rc::new(Cell::new(false)),
559            stress_loaded: Rc::new(Cell::new(false)),
560            charts_loaded: Rc::new(Cell::new(false)),
561            bg_workers_enabled,
562            default_host_plat_idx: Rc::new(Cell::new(0)),
563            reactive_signals: Rc::new(Cell::new(None)),
564            render_window_signals: Rc::new(Cell::new(None)),
565            forms_signals: Rc::new(Cell::new(None)),
566            overlays_signals: Rc::new(Cell::new(None)),
567            data_signals: Rc::new(Cell::new(None)),
568            engine3d_signals,
569            dynamic_signals: Rc::new(Cell::new(None)),
570            lab_signals: Rc::new(Cell::new(None)),
571            media_signals: Rc::new(Cell::new(None)),
572            markdown_signals: Rc::new(Cell::new(None)),
573            stress_signals: Rc::new(Cell::new(None)),
574            charts_signals: Rc::new(Cell::new(None)),
575            water_signals,
576        };
577        state.wire_dynamic_hub_actions();
578        state
579    }
580
581    /// Records the host platform index without eagerly materializing `/window` signals at boot.
582    ///
583    /// # Arguments
584    ///
585    /// - `&Self` - Reactive showcase state reference.
586    /// - `usize` - Host platform index (`0..7`).
587    pub fn set_default_host_platform_idx(&self, idx: usize) {
588        self.get_default_host_plat_idx().set(idx);
589        if let Some(rw) = self.get_render_window_signals().get() {
590            let _: bool = rw.get_os_target_platform_idx().set_if_changed(idx);
591        }
592    }
593
594    /// Enables or disables off-main-thread background worker loading for heavy showcase routes.
595    ///
596    /// # Arguments
597    ///
598    /// - `&Self` - Reactive showcase state reference.
599    /// - `bool` - `true` to enable background worker threads on native targets.
600    pub fn set_bg_workers_enabled(&self, enabled: bool) {
601        self.get_bg_workers_enabled().set(enabled);
602    }
603
604    /// Resolves honest baseline adaptive render diagnostics for `platform` without faking unverified GPU direct present or hardware compositor timing.
605    ///
606    /// # Arguments
607    ///
608    /// - `PlatformKind` - Active host platform classification.
609    ///
610    /// # Returns
611    ///
612    /// - `(&'static str, &'static str, bool, &'static str, &'static str)` - `(active_backend, recommended_backend, cpu_mirror_active, timing_source, upload_strategy)`.
613    #[must_use]
614    fn default_adaptive_render_profile(
615        platform: PlatformKind,
616    ) -> (&'static str, &'static str, bool, &'static str, &'static str) {
617        let config_spec: RenderConfig = RenderConfig::default();
618        let direct_gpu: bool = config_spec.get_direct_gpu_present();
619        match platform {
620            PlatformKind::MacOs | PlatformKind::Ios | PlatformKind::IpadOs => {
621                if direct_gpu {
622                    (
623                        ADAPTIVE_BACKEND_METAL_DIRECT,
624                        ADAPTIVE_BACKEND_METAL_DIRECT,
625                        false,
626                        ADAPTIVE_TIMING_COMPOSITOR,
627                        ADAPTIVE_UPLOAD_DIRECT_GPU,
628                    )
629                } else {
630                    (
631                        ADAPTIVE_BACKEND_SOFTWARE_CPU,
632                        ADAPTIVE_BACKEND_METAL_DIRECT,
633                        true,
634                        ADAPTIVE_TIMING_PROXY,
635                        ADAPTIVE_UPLOAD_MULTI_RECT,
636                    )
637                }
638            }
639            PlatformKind::Android | PlatformKind::HarmonyOs => {
640                if direct_gpu {
641                    (
642                        ADAPTIVE_BACKEND_GLES3_DIRECT,
643                        ADAPTIVE_BACKEND_GLES3_DIRECT,
644                        false,
645                        ADAPTIVE_TIMING_COMPOSITOR,
646                        ADAPTIVE_UPLOAD_DIRECT_GPU,
647                    )
648                } else {
649                    (
650                        ADAPTIVE_BACKEND_SOFTWARE_CPU,
651                        ADAPTIVE_BACKEND_GLES3_DIRECT,
652                        true,
653                        ADAPTIVE_TIMING_PROXY,
654                        ADAPTIVE_UPLOAD_MULTI_RECT,
655                    )
656                }
657            }
658            PlatformKind::Windows => {
659                if direct_gpu {
660                    (
661                        ADAPTIVE_BACKEND_D3D11_DIRECT,
662                        ADAPTIVE_BACKEND_D3D11_DIRECT,
663                        false,
664                        ADAPTIVE_TIMING_COMPOSITOR,
665                        ADAPTIVE_UPLOAD_DIRECT_GPU,
666                    )
667                } else {
668                    (
669                        ADAPTIVE_BACKEND_SOFTWARE_CPU,
670                        ADAPTIVE_BACKEND_D3D11_DIRECT,
671                        true,
672                        ADAPTIVE_TIMING_PROXY,
673                        ADAPTIVE_UPLOAD_MULTI_RECT,
674                    )
675                }
676            }
677            PlatformKind::Linux => {
678                if direct_gpu {
679                    (
680                        ADAPTIVE_BACKEND_VULKAN_DIRECT,
681                        ADAPTIVE_BACKEND_VULKAN_DIRECT,
682                        false,
683                        ADAPTIVE_TIMING_COMPOSITOR,
684                        ADAPTIVE_UPLOAD_DIRECT_GPU,
685                    )
686                } else {
687                    (
688                        ADAPTIVE_BACKEND_SOFTWARE_CPU,
689                        ADAPTIVE_BACKEND_VULKAN_DIRECT,
690                        true,
691                        ADAPTIVE_TIMING_PROXY,
692                        ADAPTIVE_UPLOAD_MULTI_RECT,
693                    )
694                }
695            }
696            PlatformKind::Web => (
697                ADAPTIVE_BACKEND_WEBGL2_UPLOAD,
698                ADAPTIVE_BACKEND_WEBGL2_UPLOAD,
699                true,
700                ADAPTIVE_TIMING_PROXY,
701                ADAPTIVE_UPLOAD_MULTI_RECT,
702            ),
703            PlatformKind::Terminal | PlatformKind::TerminalCli => (
704                ADAPTIVE_BACKEND_TERMINAL,
705                ADAPTIVE_BACKEND_TERMINAL,
706                false,
707                ADAPTIVE_TIMING_UNOBSERVABLE,
708                ADAPTIVE_UPLOAD_NONE,
709            ),
710            PlatformKind::Wearable
711            | PlatformKind::MiniApp
712            | PlatformKind::QuickApp
713            | PlatformKind::Headless => (
714                ADAPTIVE_BACKEND_SOFTWARE_CPU,
715                ADAPTIVE_BACKEND_SOFTWARE_CPU,
716                true,
717                ADAPTIVE_TIMING_PROXY,
718                ADAPTIVE_UPLOAD_MULTI_RECT,
719            ),
720        }
721    }
722
723    /// Synchronizes live adaptive render router telemetry into reactive `/settings` diagnostics signals.
724    ///
725    /// # Arguments
726    ///
727    /// - `&Self` - Reactive showcase state reference.
728    /// - `&str` - Active backend display label.
729    /// - `&str` - Recommended backend display label.
730    /// - `bool` - Whether a CPU software mirror is active.
731    /// - `&str` - Honest presentation timing source label.
732    /// - `&str` - Active upload/submission strategy label.
733    /// - `(u64, u64, u64)` - `(attempts, successes, aborts)` handoff counters.
734    pub fn sync_adaptive_render_diagnostics(
735        &self,
736        active_backend: &str,
737        recommended_backend: &str,
738        cpu_mirror_active: bool,
739        timing_source: &str,
740        upload_strategy: &str,
741        handoff_counts: (u64, u64, u64),
742    ) {
743        let _: bool = self
744            .get_adaptive_active_backend()
745            .set_if_changed(active_backend.to_string());
746        let _: bool = self
747            .get_adaptive_recommended_backend()
748            .set_if_changed(recommended_backend.to_string());
749        let _: bool = self
750            .get_adaptive_cpu_mirror_active()
751            .set_if_changed(cpu_mirror_active);
752        let _: bool = self
753            .get_adaptive_present_timing_source()
754            .set_if_changed(timing_source.to_string());
755        let _: bool = self
756            .get_adaptive_upload_strategy()
757            .set_if_changed(upload_strategy.to_string());
758        let _: bool = self
759            .get_adaptive_handoff_attempts()
760            .set_if_changed(handoff_counts.0);
761        let _: bool = self
762            .get_adaptive_handoff_successes()
763            .set_if_changed(handoff_counts.1);
764        let _: bool = self
765            .get_adaptive_handoff_aborts()
766            .set_if_changed(handoff_counts.2);
767    }
768
769    /// Formats a human-readable backend label from a `(GraphicsBackend, RenderBackendCandidate)` pair.
770    ///
771    /// # Arguments
772    ///
773    /// - `GraphicsBackend` - Active low-level graphics API backend.
774    /// - `RenderBackendCandidate` - Active or recommended adaptive render candidate.
775    ///
776    /// # Returns
777    ///
778    /// - `&'static str` - Canonical truthful backend label.
779    #[must_use]
780    fn adaptive_candidate_label(
781        backend: GraphicsBackend,
782        candidate: RenderBackendCandidate,
783    ) -> &'static str {
784        match candidate {
785            RenderBackendCandidate::GpuDirect => match backend {
786                GraphicsBackend::Metal => ADAPTIVE_BACKEND_METAL_DIRECT,
787                GraphicsBackend::Vulkan => ADAPTIVE_BACKEND_VULKAN_DIRECT,
788                GraphicsBackend::Direct3D11 | GraphicsBackend::Direct3D12 => {
789                    ADAPTIVE_BACKEND_D3D11_DIRECT
790                }
791                GraphicsBackend::OpenGlEs => ADAPTIVE_BACKEND_GLES3_DIRECT,
792                GraphicsBackend::WebGpu | GraphicsBackend::WebGl2 => ADAPTIVE_BACKEND_WEBGL2_DIRECT,
793                GraphicsBackend::Canvas2d => ADAPTIVE_BACKEND_CANVAS2D,
794                GraphicsBackend::SoftwareCpu | GraphicsBackend::Headless => {
795                    ADAPTIVE_BACKEND_SOFTWARE_CPU
796                }
797            },
798            RenderBackendCandidate::GpuUpload => match backend {
799                GraphicsBackend::Metal => ADAPTIVE_BACKEND_METAL_UPLOAD,
800                GraphicsBackend::WebGpu | GraphicsBackend::WebGl2 => ADAPTIVE_BACKEND_WEBGL2_UPLOAD,
801                GraphicsBackend::Vulkan => ADAPTIVE_BACKEND_VULKAN_DIRECT,
802                GraphicsBackend::Direct3D11 | GraphicsBackend::Direct3D12 => {
803                    ADAPTIVE_BACKEND_D3D11_DIRECT
804                }
805                GraphicsBackend::OpenGlEs => ADAPTIVE_BACKEND_GLES3_DIRECT,
806                GraphicsBackend::Canvas2d => ADAPTIVE_BACKEND_CANVAS2D,
807                GraphicsBackend::SoftwareCpu | GraphicsBackend::Headless => {
808                    ADAPTIVE_BACKEND_SOFTWARE_CPU
809                }
810            },
811            RenderBackendCandidate::Hybrid => ADAPTIVE_BACKEND_HYBRID_SPARSE,
812            RenderBackendCandidate::Software => {
813                if backend == GraphicsBackend::Canvas2d {
814                    ADAPTIVE_BACKEND_CANVAS2D
815                } else {
816                    ADAPTIVE_BACKEND_SOFTWARE_CPU
817                }
818            }
819            RenderBackendCandidate::Terminal => ADAPTIVE_BACKEND_TERMINAL,
820        }
821    }
822
823    /// Synchronizes `/settings` adaptive rollout toggle into `app`'s live `AdaptiveRenderRouter` and mirrors real `AdaptiveFrameMetrics` back into reactive signals.
824    ///
825    /// # Arguments
826    ///
827    /// - `&Self` - Reactive showcase state reference.
828    /// - `&mut App` - Active application owning the live `Renderer` and `AdaptiveRenderRouter`.
829    pub fn sync_adaptive_from_app(&self, app: &mut App) {
830        let desired_mode: AdaptiveSwitchMode = if self.get_adaptive_auto_switch().get_untracked() {
831            AdaptiveSwitchMode::AutoSwitch
832        } else {
833            AdaptiveSwitchMode::RecommendOnly
834        };
835        if app.adaptive_switch_mode() != desired_mode {
836            app.set_adaptive_switch_mode(desired_mode);
837        }
838        let metrics: AdaptiveFrameMetrics = app.adaptive_frame_metrics();
839        let snap: AdaptiveRouterSnapshot = metrics.get_adaptive_router();
840        let backend: GraphicsBackend = app.get_renderer().get_active_backend();
841        let active_label: &str =
842            Self::adaptive_candidate_label(backend, snap.get_active_candidate());
843        let rec_label: &str =
844            Self::adaptive_candidate_label(backend, snap.get_recommended_candidate());
845        let timing_label: &str = match metrics.get_present_timing_source() {
846            PresentTimingSource::CompositorMeasured => ADAPTIVE_TIMING_COMPOSITOR,
847            PresentTimingSource::SubmissionProxy => ADAPTIVE_TIMING_PROXY,
848            PresentTimingSource::Unobservable => ADAPTIVE_TIMING_UNOBSERVABLE,
849        };
850        let upload_label: &str = match metrics.get_upload_strategy() {
851            UploadStrategy::DirectGpu => ADAPTIVE_UPLOAD_DIRECT_GPU,
852            UploadStrategy::MultiRect => ADAPTIVE_UPLOAD_MULTI_RECT,
853            UploadStrategy::MergedBbox => ADAPTIVE_UPLOAD_MERGED_BBOX,
854            UploadStrategy::FullFrame => ADAPTIVE_UPLOAD_FULL_FRAME,
855            UploadStrategy::None => ADAPTIVE_UPLOAD_NONE,
856        };
857        let successes: u64 = snap.get_seamless_handoff_successes();
858        let aborts: u64 = snap.get_handoff_aborts();
859        let attempts: u64 = successes.saturating_add(aborts);
860        self.sync_adaptive_render_diagnostics(
861            active_label,
862            rec_label,
863            metrics.get_cpu_mirror_active(),
864            timing_label,
865            upload_label,
866            (attempts, successes, aborts),
867        );
868    }
869
870    /// Synchronizes `/settings` adaptive rollout toggle into `app`'s live `AdaptiveRenderRouter` and combines it with live Web dual-canvas handoff and `SubmissionProxy` telemetry.
871    ///
872    /// # Arguments
873    ///
874    /// - `&Self` - Reactive showcase state reference.
875    /// - `&mut App` - Active WebAssembly application owning the live `Renderer` and `AdaptiveRenderRouter`.
876    /// - `&ShowcaseWebDualCanvasCoordinator` - Live stacked dual-canvas coordinator snapshot.
877    pub fn sync_adaptive_from_web_coordinator(
878        &self,
879        app: &mut App,
880        coord: &ShowcaseWebDualCanvasCoordinator,
881    ) {
882        self.sync_adaptive_from_app(app);
883        let active_path: ShowcaseWebPresentationPath = coord.get_active().get_path();
884        let active_label: &str = match active_path {
885            ShowcaseWebPresentationPath::GpuDirect => ADAPTIVE_BACKEND_WEBGL2_DIRECT,
886            ShowcaseWebPresentationPath::GpuUpload => ADAPTIVE_BACKEND_WEBGL2_UPLOAD,
887            ShowcaseWebPresentationPath::Canvas2d => ADAPTIVE_BACKEND_CANVAS2D,
888        };
889        let upload_label: &str = match active_path {
890            ShowcaseWebPresentationPath::GpuDirect => ADAPTIVE_UPLOAD_DIRECT_GPU,
891            ShowcaseWebPresentationPath::GpuUpload => ADAPTIVE_UPLOAD_MULTI_RECT,
892            ShowcaseWebPresentationPath::Canvas2d => ADAPTIVE_UPLOAD_FULL_FRAME,
893        };
894        let timing_label: &str = match coord.get_timing_source() {
895            ShowcaseWebTimingSource::SubmissionProxy => ADAPTIVE_TIMING_PROXY,
896            ShowcaseWebTimingSource::Unobservable => ADAPTIVE_TIMING_UNOBSERVABLE,
897        };
898        let snap: AdaptiveRouterSnapshot = app.adaptive_router_snapshot();
899        let successes: u64 = snap
900            .get_seamless_handoff_successes()
901            .saturating_add(coord.get_completed_swaps());
902        let aborts: u64 = snap
903            .get_handoff_aborts()
904            .saturating_add(coord.get_aborted_swaps());
905        let attempts: u64 = successes.saturating_add(aborts);
906        self.sync_adaptive_render_diagnostics(
907            active_label,
908            active_label,
909            coord.get_cpu_mirror_active(),
910            timing_label,
911            upload_label,
912            (attempts, successes, aborts),
913        );
914    }
915
916    /// Resets all reactive shell and runtime preferences to canonical showcase defaults.
917    ///
918    /// # Arguments
919    ///
920    /// - `&Self` - Reactive showcase state reference.
921    pub fn reset_preferences_to_defaults(&self) {
922        let _: bool = self.get_auto_hide_chrome().set_if_changed(true);
923        let _: bool = self.get_show_fps_hud().set_if_changed(true);
924        let _: bool = self.get_swipe_routing().set_if_changed(true);
925        let _: bool = self.get_reduced_motion().set_if_changed(false);
926        let _: bool = self.get_adaptive_auto_switch().set_if_changed(false);
927        let _: bool = self
928            .get_theme()
929            .get_scheme()
930            .set_if_changed(active_feature_scheme());
931        let _: bool = self.get_theme().get_mode().set_if_changed(ThemeMode::Light);
932    }
933
934    /// Returns the lazily initialized `/reactive` signal group.
935    ///
936    /// # Arguments
937    ///
938    /// - `&Self` - Reactive showcase state reference.
939    ///
940    /// # Returns
941    ///
942    /// - `ReactiveSignals` - Active `/reactive` signal group.
943    fn reactive_group(&self) -> ReactiveSignals {
944        if let Some(existing) = self.get_reactive_signals().get() {
945            return existing;
946        }
947        let created: ReactiveSignals = self.get_state_scope().enter(ReactiveSignals::create);
948        self.get_reactive_signals().set(Some(created));
949        created
950    }
951
952    /// Returns the lazily initialized `/render` and `/window` signal group.
953    ///
954    /// # Arguments
955    ///
956    /// - `&Self` - Reactive showcase state reference.
957    ///
958    /// # Returns
959    ///
960    /// - `RenderWindowSignals` - Active `/render` and `/window` signal group.
961    fn render_window_group(&self) -> RenderWindowSignals {
962        if let Some(existing) = self.get_render_window_signals().get() {
963            return existing;
964        }
965        let default_plat: usize = self.get_default_host_plat_idx().get();
966        let created: RenderWindowSignals = self
967            .get_state_scope()
968            .enter(|| RenderWindowSignals::create(default_plat));
969        self.get_render_window_signals().set(Some(created));
970        created
971    }
972
973    /// Returns the lazily initialized `/forms` signal group.
974    ///
975    /// # Arguments
976    ///
977    /// - `&Self` - Reactive showcase state reference.
978    ///
979    /// # Returns
980    ///
981    /// - `FormsSignals` - Active `/forms` signal group.
982    fn forms_group(&self) -> FormsSignals {
983        if let Some(existing) = self.get_forms_signals().get() {
984            return existing;
985        }
986        let created: FormsSignals = self.get_state_scope().enter(FormsSignals::create);
987        self.get_forms_signals().set(Some(created));
988        created
989    }
990
991    /// Returns the lazily initialized `/overlays` signal group.
992    ///
993    /// # Arguments
994    ///
995    /// - `&Self` - Reactive showcase state reference.
996    ///
997    /// # Returns
998    ///
999    /// - `OverlaysSignals` - Active `/overlays` signal group.
1000    fn overlays_group(&self) -> OverlaysSignals {
1001        if let Some(existing) = self.get_overlays_signals().get() {
1002            return existing;
1003        }
1004        let created: OverlaysSignals = self.get_state_scope().enter(OverlaysSignals::create);
1005        self.get_overlays_signals().set(Some(created));
1006        created
1007    }
1008
1009    /// Returns the lazily initialized `/data` signal group.
1010    ///
1011    /// # Arguments
1012    ///
1013    /// - `&Self` - Reactive showcase state reference.
1014    ///
1015    /// # Returns
1016    ///
1017    /// - `DataSignals` - Active `/data` signal group.
1018    fn data_group(&self) -> DataSignals {
1019        if let Some(existing) = self.get_data_signals().get() {
1020            return existing;
1021        }
1022        let created: DataSignals = self.get_state_scope().enter(DataSignals::create);
1023        self.get_data_signals().set(Some(created));
1024        created
1025    }
1026
1027    /// Returns the lazily initialized `/game3d` signal group.
1028    ///
1029    /// # Arguments
1030    ///
1031    /// - `&Self` - Reactive showcase state reference.
1032    ///
1033    /// # Returns
1034    ///
1035    /// - `Engine3dSignals` - Active `/game3d` signal group.
1036    fn engine3d_group(&self) -> Engine3dSignals {
1037        Engine3dSignals::get_or_init(self.get_engine3d_signals().as_ref(), self.get_state_scope())
1038    }
1039
1040    /// Returns the lazily initialized `/dynamic` signal group.
1041    ///
1042    /// # Arguments
1043    ///
1044    /// - `&Self` - Reactive showcase state reference.
1045    ///
1046    /// # Returns
1047    ///
1048    /// - `DynamicSignals` - Active `/dynamic` signal group.
1049    fn dynamic_group(&self) -> DynamicSignals {
1050        DynamicSignals::get_or_init(self.get_dynamic_signals().as_ref(), self.get_state_scope())
1051    }
1052
1053    /// Returns the lazily initialized `/lab` signal group.
1054    ///
1055    /// # Arguments
1056    ///
1057    /// - `&Self` - Reactive showcase state reference.
1058    ///
1059    /// # Returns
1060    ///
1061    /// - `LabSignals` - Active `/lab` signal group.
1062    fn lab_group(&self) -> LabSignals {
1063        if let Some(existing) = self.get_lab_signals().get() {
1064            return existing;
1065        }
1066        let created: LabSignals = self.get_state_scope().enter(LabSignals::create);
1067        self.get_lab_signals().set(Some(created));
1068        created
1069    }
1070
1071    /// Returns the lazily initialized `/media` signal group.
1072    ///
1073    /// # Arguments
1074    ///
1075    /// - `&Self` - Reactive showcase state reference.
1076    ///
1077    /// # Returns
1078    ///
1079    /// - `MediaSignals` - Active `/media` signal group.
1080    fn media_group(&self) -> MediaSignals {
1081        if let Some(existing) = self.get_media_signals().get() {
1082            return existing;
1083        }
1084        let created: MediaSignals = self.get_state_scope().enter(MediaSignals::create);
1085        self.get_media_signals().set(Some(created));
1086        created
1087    }
1088
1089    /// Returns the lazily initialized `/markdown` signal group.
1090    ///
1091    /// # Arguments
1092    ///
1093    /// - `&Self` - Reactive showcase state reference.
1094    ///
1095    /// # Returns
1096    ///
1097    /// - `MarkdownSignals` - Active `/markdown` signal group.
1098    fn markdown_group(&self) -> MarkdownSignals {
1099        if let Some(existing) = self.get_markdown_signals().get() {
1100            return existing;
1101        }
1102        let created: MarkdownSignals = self.get_state_scope().enter(MarkdownSignals::create);
1103        self.get_markdown_signals().set(Some(created));
1104        created
1105    }
1106
1107    /// Returns the lazily initialized `/stress` signal group.
1108    ///
1109    /// # Arguments
1110    ///
1111    /// - `&Self` - Reactive showcase state reference.
1112    ///
1113    /// # Returns
1114    ///
1115    /// - `StressSignals` - Active `/stress` signal group.
1116    fn stress_group(&self) -> StressSignals {
1117        if let Some(existing) = self.get_stress_signals().get() {
1118            return existing;
1119        }
1120        let created: StressSignals = self.get_state_scope().enter(StressSignals::create);
1121        self.get_stress_signals().set(Some(created));
1122        created
1123    }
1124
1125    /// Returns the lazily initialized `/charts` signal group.
1126    ///
1127    /// # Arguments
1128    ///
1129    /// - `&Self` - Reactive showcase state reference.
1130    ///
1131    /// # Returns
1132    ///
1133    /// - `ChartsSignals` - Active `/charts` signal group.
1134    fn charts_group(&self) -> ChartsSignals {
1135        if let Some(existing) = self.get_charts_signals().get() {
1136            return existing;
1137        }
1138        let created: ChartsSignals = self.get_state_scope().enter(ChartsSignals::create);
1139        self.get_charts_signals().set(Some(created));
1140        created
1141    }
1142
1143    /// Returns the lazily initialized `/water` signal group.
1144    ///
1145    /// # Arguments
1146    ///
1147    /// - `&Self` - Reactive showcase state reference.
1148    ///
1149    /// # Returns
1150    ///
1151    /// - `WaterSignals` - Active `/water` signal group.
1152    fn water_group(&self) -> WaterSignals {
1153        if let Some(existing) = self.get_water_signals().get() {
1154            return existing;
1155        }
1156        let created: WaterSignals = self.get_state_scope().enter(WaterSignals::create);
1157        self.get_water_signals().set(Some(created));
1158        created
1159    }
1160
1161    /// Returns `true` when the `/water` `GyroLiquidGameScene` has been lazily initialized.
1162    ///
1163    /// # Arguments
1164    ///
1165    /// - `&Self` - Reactive showcase state reference.
1166    ///
1167    /// # Returns
1168    ///
1169    /// - `bool` - Whether the liquid simulation handle is materialized.
1170    #[must_use]
1171    pub fn has_water_scene_initialized(&self) -> bool {
1172        self.get_water_scene_cell().borrow().is_some()
1173    }
1174
1175    /// Returns the shared `GyroLiquidGameScene`, materializing it lazily on first `/water` visit.
1176    ///
1177    /// # Arguments
1178    ///
1179    /// - `&Self` - Reactive showcase state reference.
1180    ///
1181    /// # Returns
1182    ///
1183    /// - `GyroLiquidGameScene` - Active shareable liquid physics scene handle.
1184    #[must_use]
1185    pub fn get_or_init_water_scene(&self) -> GyroLiquidGameScene {
1186        if let Some(existing) = self.get_water_scene_cell().borrow().as_ref() {
1187            return existing.clone();
1188        }
1189        let created: GyroLiquidGameScene = GyroLiquidGameScene::default();
1190        *self.get_water_scene_cell().borrow_mut() = Some(created.clone());
1191        let _: bool = self
1192            .water_group()
1193            .get_stats()
1194            .set_if_changed(created.stats());
1195        created
1196    }
1197
1198    /// Returns the `/water` liquid fill percentage signal (`25.0..=80.0`).
1199    ///
1200    /// # Arguments
1201    ///
1202    /// - `&Self` - Reactive showcase state reference.
1203    ///
1204    /// # Returns
1205    ///
1206    /// - `Signal<f32>` - Fill level percentage signal handle.
1207    #[must_use]
1208    pub fn get_water_fill_pct(&self) -> Signal<f32> {
1209        self.water_group().get_fill_pct()
1210    }
1211
1212    /// Returns the `/water` viscosity preset index signal (`0=Water`, `1=Light Oil`, `2=Honey`).
1213    ///
1214    /// # Arguments
1215    ///
1216    /// - `&Self` - Reactive showcase state reference.
1217    ///
1218    /// # Returns
1219    ///
1220    /// - `Signal<usize>` - Viscosity preset index signal handle.
1221    #[must_use]
1222    pub fn get_water_viscosity_idx(&self) -> Signal<usize> {
1223        self.water_group().get_viscosity_idx()
1224    }
1225
1226    /// Returns the `/water` buoyant floating bodies toggle signal.
1227    ///
1228    /// # Arguments
1229    ///
1230    /// - `&Self` - Reactive showcase state reference.
1231    ///
1232    /// # Returns
1233    ///
1234    /// - `Signal<bool>` - Buoyant bodies toggle signal handle.
1235    #[must_use]
1236    pub fn get_water_buoyant_enabled(&self) -> Signal<bool> {
1237        self.water_group().get_buoyant_enabled()
1238    }
1239
1240    /// Returns the `/water` fullscreen portal open signal.
1241    ///
1242    /// # Arguments
1243    ///
1244    /// - `&Self` - Reactive showcase state reference.
1245    ///
1246    /// # Returns
1247    ///
1248    /// - `Signal<bool>` - Fullscreen portal open signal handle.
1249    #[must_use]
1250    pub fn get_water_fullscreen_open(&self) -> Signal<bool> {
1251        self.water_group().get_fullscreen_open()
1252    }
1253
1254    /// Returns the `/water` motion sensor permission status message signal.
1255    ///
1256    /// # Arguments
1257    ///
1258    /// - `&Self` - Reactive showcase state reference.
1259    ///
1260    /// # Returns
1261    ///
1262    /// - `Signal<String>` - Motion sensor status signal handle.
1263    #[must_use]
1264    pub fn get_water_sensor_perm_status(&self) -> Signal<String> {
1265        self.water_group().get_sensor_perm_status()
1266    }
1267
1268    /// Returns the `/water` live physics telemetry snapshot signal.
1269    ///
1270    /// # Arguments
1271    ///
1272    /// - `&Self` - Reactive showcase state reference.
1273    ///
1274    /// # Returns
1275    ///
1276    /// - `Signal<GyroLiquidStats>` - Live liquid physics telemetry signal handle.
1277    #[must_use]
1278    pub fn get_water_stats(&self) -> Signal<GyroLiquidStats> {
1279        self.water_group().get_stats()
1280    }
1281
1282    /// Returns the interactive counter signal for `/reactive`.
1283    ///
1284    /// # Arguments
1285    ///
1286    /// - `&Self` - Reactive showcase state reference.
1287    ///
1288    /// # Returns
1289    ///
1290    /// - `Signal<i32>` - Counter signal handle.
1291    #[must_use]
1292    pub fn get_counter(&self) -> Signal<i32> {
1293        self.reactive_group().get_counter()
1294    }
1295
1296    /// Returns the derived `counter * 2` memo for `/reactive`.
1297    ///
1298    /// # Arguments
1299    ///
1300    /// - `&Self` - Reactive showcase state reference.
1301    ///
1302    /// # Returns
1303    ///
1304    /// - `Memo<i32>` - Doubled counter memo handle.
1305    #[must_use]
1306    pub fn get_doubled(&self) -> Memo<i32> {
1307        self.reactive_group().get_doubled()
1308    }
1309
1310    /// Returns the component-scoped demo render pipeline preview index signal.
1311    ///
1312    /// # Arguments
1313    ///
1314    /// - `&Self` - Reactive showcase state reference.
1315    ///
1316    /// # Returns
1317    ///
1318    /// - `Signal<usize>` - Render mode index signal handle.
1319    #[must_use]
1320    pub fn get_render_mode_index(&self) -> Signal<usize> {
1321        self.render_window_group().get_render_mode_index()
1322    }
1323
1324    /// Returns the component-scoped demo FPS cap index signal on `/window`.
1325    ///
1326    /// # Arguments
1327    ///
1328    /// - `&Self` - Reactive showcase state reference.
1329    ///
1330    /// # Returns
1331    ///
1332    /// - `Signal<usize>` - FPS cap index signal handle.
1333    #[must_use]
1334    pub fn get_demo_fps_cap_index(&self) -> Signal<usize> {
1335        self.render_window_group().get_demo_fps_cap_index()
1336    }
1337
1338    /// Returns the controlled fullscreen toggle signal.
1339    ///
1340    /// # Arguments
1341    ///
1342    /// - `&Self` - Reactive showcase state reference.
1343    ///
1344    /// # Returns
1345    ///
1346    /// - `Signal<bool>` - Fullscreen signal handle.
1347    #[must_use]
1348    pub fn get_fullscreen(&self) -> Signal<bool> {
1349        self.render_window_group().get_fullscreen()
1350    }
1351
1352    /// Returns the Dynamic Island active state signal.
1353    ///
1354    /// # Arguments
1355    ///
1356    /// - `&Self` - Reactive showcase state reference.
1357    ///
1358    /// # Returns
1359    ///
1360    /// - `Signal<bool>` - Island active signal handle.
1361    #[must_use]
1362    pub fn get_island_active(&self) -> Signal<bool> {
1363        self.render_window_group().get_island_active()
1364    }
1365
1366    /// Returns the Dynamic Island progress signal (`0..=100`).
1367    ///
1368    /// # Arguments
1369    ///
1370    /// - `&Self` - Reactive showcase state reference.
1371    ///
1372    /// # Returns
1373    ///
1374    /// - `Signal<u8>` - Island progress signal handle.
1375    #[must_use]
1376    pub fn get_island_progress(&self) -> Signal<u8> {
1377        self.render_window_group().get_island_progress()
1378    }
1379
1380    /// Returns the camera permission status readout signal.
1381    ///
1382    /// # Arguments
1383    ///
1384    /// - `&Self` - Reactive showcase state reference.
1385    ///
1386    /// # Returns
1387    ///
1388    /// - `Signal<String>` - Camera permission status signal handle.
1389    #[must_use]
1390    pub fn get_camera_perm_status(&self) -> Signal<String> {
1391        self.render_window_group().get_camera_perm_status()
1392    }
1393
1394    /// Returns the protocol registration status readout signal.
1395    ///
1396    /// # Arguments
1397    ///
1398    /// - `&Self` - Reactive showcase state reference.
1399    ///
1400    /// # Returns
1401    ///
1402    /// - `Signal<String>` - Protocol status signal handle.
1403    #[must_use]
1404    pub fn get_protocol_status(&self) -> Signal<String> {
1405        self.render_window_group().get_protocol_status()
1406    }
1407
1408    /// Returns the accessibility live announcement counter signal.
1409    ///
1410    /// # Arguments
1411    ///
1412    /// - `&Self` - Reactive showcase state reference.
1413    ///
1414    /// # Returns
1415    ///
1416    /// - `Signal<u32>` - Accessibility counter signal handle.
1417    #[must_use]
1418    pub fn get_a11y_announcements(&self) -> Signal<u32> {
1419        self.render_window_group().get_a11y_announcements()
1420    }
1421
1422    /// Returns the haptic pulse counter signal.
1423    ///
1424    /// # Arguments
1425    ///
1426    /// - `&Self` - Reactive showcase state reference.
1427    ///
1428    /// # Returns
1429    ///
1430    /// - `Signal<u32>` - Haptic counter signal handle.
1431    #[must_use]
1432    pub fn get_haptic_pulses(&self) -> Signal<u32> {
1433        self.render_window_group().get_haptic_pulses()
1434    }
1435
1436    /// Returns the simulated target platform index signal on `/window`.
1437    ///
1438    /// # Arguments
1439    ///
1440    /// - `&Self` - Reactive showcase state reference.
1441    ///
1442    /// # Returns
1443    ///
1444    /// - `Signal<usize>` - Target platform index signal handle.
1445    #[must_use]
1446    pub fn get_os_target_platform_idx(&self) -> Signal<usize> {
1447        self.render_window_group().get_os_target_platform_idx()
1448    }
1449
1450    /// Returns the Dynamic Island presentation mode index signal.
1451    ///
1452    /// # Arguments
1453    ///
1454    /// - `&Self` - Reactive showcase state reference.
1455    ///
1456    /// # Returns
1457    ///
1458    /// - `Signal<usize>` - Island presentation mode index signal handle.
1459    #[must_use]
1460    pub fn get_island_mode_idx(&self) -> Signal<usize> {
1461        self.render_window_group().get_island_mode_idx()
1462    }
1463
1464    /// Returns the live system notifications stack signal.
1465    ///
1466    /// # Arguments
1467    ///
1468    /// - `&Self` - Reactive showcase state reference.
1469    ///
1470    /// # Returns
1471    ///
1472    /// - `Signal<Vec<(String, String)>>` - System notifications signal handle.
1473    #[must_use]
1474    pub fn get_system_notifications(&self) -> Signal<Vec<(String, String)>> {
1475        self.render_window_group().get_system_notifications()
1476    }
1477
1478    /// Returns the per-permission status vector signal on `/window`.
1479    ///
1480    /// # Arguments
1481    ///
1482    /// - `&Self` - Reactive showcase state reference.
1483    ///
1484    /// # Returns
1485    ///
1486    /// - `Signal<Vec<PermissionStatus>>` - Permission statuses signal handle.
1487    #[must_use]
1488    pub fn get_permission_statuses(&self) -> Signal<Vec<PermissionStatus>> {
1489        self.render_window_group().get_permission_statuses()
1490    }
1491
1492    /// Returns the controlled username input signal.
1493    ///
1494    /// # Arguments
1495    ///
1496    /// - `&Self` - Reactive showcase state reference.
1497    ///
1498    /// # Returns
1499    ///
1500    /// - `Signal<String>` - Username signal handle.
1501    #[must_use]
1502    pub fn get_username(&self) -> Signal<String> {
1503        self.forms_group().get_username()
1504    }
1505
1506    /// Returns the controlled multi-line bio textarea signal.
1507    ///
1508    /// # Arguments
1509    ///
1510    /// - `&Self` - Reactive showcase state reference.
1511    ///
1512    /// # Returns
1513    ///
1514    /// - `Signal<String>` - Bio signal handle.
1515    #[must_use]
1516    pub fn get_bio(&self) -> Signal<String> {
1517        self.forms_group().get_bio()
1518    }
1519
1520    /// Returns the controlled numeric stepper signal.
1521    ///
1522    /// # Arguments
1523    ///
1524    /// - `&Self` - Reactive showcase state reference.
1525    ///
1526    /// # Returns
1527    ///
1528    /// - `Signal<i64>` - Stepper value signal handle.
1529    #[must_use]
1530    pub fn get_stepper_value(&self) -> Signal<i64> {
1531        self.forms_group().get_stepper_value()
1532    }
1533
1534    /// Returns the controlled radio group selection index signal.
1535    ///
1536    /// # Arguments
1537    ///
1538    /// - `&Self` - Reactive showcase state reference.
1539    ///
1540    /// # Returns
1541    ///
1542    /// - `Signal<usize>` - Radio index signal handle.
1543    #[must_use]
1544    pub fn get_radio_index(&self) -> Signal<usize> {
1545        self.forms_group().get_radio_index()
1546    }
1547
1548    /// Returns the controlled continuous slider value signal.
1549    ///
1550    /// # Arguments
1551    ///
1552    /// - `&Self` - Reactive showcase state reference.
1553    ///
1554    /// # Returns
1555    ///
1556    /// - `Signal<f32>` - Slider value signal handle.
1557    #[must_use]
1558    pub fn get_slider_value(&self) -> Signal<f32> {
1559        self.forms_group().get_slider_value()
1560    }
1561
1562    /// Returns the controlled select dropdown index signal.
1563    ///
1564    /// # Arguments
1565    ///
1566    /// - `&Self` - Reactive showcase state reference.
1567    ///
1568    /// # Returns
1569    ///
1570    /// - `Signal<usize>` - Select index signal handle.
1571    #[must_use]
1572    pub fn get_select_index(&self) -> Signal<usize> {
1573        self.forms_group().get_select_index()
1574    }
1575
1576    /// Returns the controlled select dropdown open flag signal.
1577    ///
1578    /// # Arguments
1579    ///
1580    /// - `&Self` - Reactive showcase state reference.
1581    ///
1582    /// # Returns
1583    ///
1584    /// - `Signal<bool>` - Select open signal handle.
1585    #[must_use]
1586    pub fn get_select_open(&self) -> Signal<bool> {
1587        self.forms_group().get_select_open()
1588    }
1589
1590    /// Returns the controlled star rating value signal.
1591    ///
1592    /// # Arguments
1593    ///
1594    /// - `&Self` - Reactive showcase state reference.
1595    ///
1596    /// # Returns
1597    ///
1598    /// - `Signal<usize>` - Rating value signal handle.
1599    #[must_use]
1600    pub fn get_rating_value(&self) -> Signal<usize> {
1601        self.forms_group().get_rating_value()
1602    }
1603
1604    /// Returns the controlled toggle pill pressed state signal.
1605    ///
1606    /// # Arguments
1607    ///
1608    /// - `&Self` - Reactive showcase state reference.
1609    ///
1610    /// # Returns
1611    ///
1612    /// - `Signal<bool>` - Pin toggled signal handle.
1613    #[must_use]
1614    pub fn get_pin_toggled(&self) -> Signal<bool> {
1615        self.forms_group().get_pin_toggled()
1616    }
1617
1618    /// Returns the controlled hardware acceleration toggle switch signal.
1619    ///
1620    /// # Arguments
1621    ///
1622    /// - `&Self` - Reactive showcase state reference.
1623    ///
1624    /// # Returns
1625    ///
1626    /// - `Signal<bool>` - Hardware acceleration signal handle.
1627    #[must_use]
1628    pub fn get_hardware_accel(&self) -> Signal<bool> {
1629        self.forms_group().get_hardware_accel()
1630    }
1631
1632    /// Returns the controlled terms checkbox signal.
1633    ///
1634    /// # Arguments
1635    ///
1636    /// - `&Self` - Reactive showcase state reference.
1637    ///
1638    /// # Returns
1639    ///
1640    /// - `Signal<bool>` - Terms checkbox signal handle.
1641    #[must_use]
1642    pub fn get_agree_terms(&self) -> Signal<bool> {
1643        self.forms_group().get_agree_terms()
1644    }
1645
1646    /// Returns the controlled tab bar index signal.
1647    ///
1648    /// # Arguments
1649    ///
1650    /// - `&Self` - Reactive showcase state reference.
1651    ///
1652    /// # Returns
1653    ///
1654    /// - `Signal<usize>` - Active tab signal handle.
1655    #[must_use]
1656    pub fn get_active_tab(&self) -> Signal<usize> {
1657        self.forms_group().get_active_tab()
1658    }
1659
1660    /// Returns the controlled pagination page number signal.
1661    ///
1662    /// # Arguments
1663    ///
1664    /// - `&Self` - Reactive showcase state reference.
1665    ///
1666    /// # Returns
1667    ///
1668    /// - `Signal<usize>` - Page index signal handle.
1669    #[must_use]
1670    pub fn get_page_index(&self) -> Signal<usize> {
1671        self.forms_group().get_page_index()
1672    }
1673
1674    /// Returns the controlled steps indicator index signal.
1675    ///
1676    /// # Arguments
1677    ///
1678    /// - `&Self` - Reactive showcase state reference.
1679    ///
1680    /// # Returns
1681    ///
1682    /// - `Signal<usize>` - Step index signal handle.
1683    #[must_use]
1684    pub fn get_step_index(&self) -> Signal<usize> {
1685        self.forms_group().get_step_index()
1686    }
1687
1688    /// Returns the controlled accordion expanded index signal.
1689    ///
1690    /// # Arguments
1691    ///
1692    /// - `&Self` - Reactive showcase state reference.
1693    ///
1694    /// # Returns
1695    ///
1696    /// - `Signal<Option<usize>>` - Accordion open index signal handle.
1697    #[must_use]
1698    pub fn get_accordion_open(&self) -> Signal<Option<usize>> {
1699        self.forms_group().get_accordion_open()
1700    }
1701
1702    /// Returns the controlled accent color picker signal.
1703    ///
1704    /// # Arguments
1705    ///
1706    /// - `&Self` - Reactive showcase state reference.
1707    ///
1708    /// # Returns
1709    ///
1710    /// - `Signal<Color>` - Picker color signal handle.
1711    #[must_use]
1712    pub fn get_picker_color(&self) -> Signal<Color> {
1713        self.forms_group().get_picker_color()
1714    }
1715
1716    /// Returns the controlled 24-hour time picker signal.
1717    ///
1718    /// # Arguments
1719    ///
1720    /// - `&Self` - Reactive showcase state reference.
1721    ///
1722    /// # Returns
1723    ///
1724    /// - `Signal<(u8, u8)>` - Picker time signal handle.
1725    #[must_use]
1726    pub fn get_picker_time(&self) -> Signal<(u8, u8)> {
1727        self.forms_group().get_picker_time()
1728    }
1729
1730    /// Returns the controlled dynamic tag input list signal.
1731    ///
1732    /// # Arguments
1733    ///
1734    /// - `&Self` - Reactive showcase state reference.
1735    ///
1736    /// # Returns
1737    ///
1738    /// - `Signal<Vec<String>>` - Tag items signal handle.
1739    #[must_use]
1740    pub fn get_tag_items(&self) -> Signal<Vec<String>> {
1741        self.forms_group().get_tag_items()
1742    }
1743
1744    /// Returns the controlled interactive tree selected label signal.
1745    ///
1746    /// # Arguments
1747    ///
1748    /// - `&Self` - Reactive showcase state reference.
1749    ///
1750    /// # Returns
1751    ///
1752    /// - `Signal<Option<String>>` - Tree selection signal handle.
1753    #[must_use]
1754    pub fn get_tree_selected(&self) -> Signal<Option<String>> {
1755        self.forms_group().get_tree_selected()
1756    }
1757
1758    /// Returns the controlled breadcrumb active index signal.
1759    ///
1760    /// # Arguments
1761    ///
1762    /// - `&Self` - Reactive showcase state reference.
1763    ///
1764    /// # Returns
1765    ///
1766    /// - `Signal<usize>` - Breadcrumb index signal handle.
1767    #[must_use]
1768    pub fn get_breadcrumb_active(&self) -> Signal<usize> {
1769        self.forms_group().get_breadcrumb_active()
1770    }
1771
1772    /// Returns the controlled modal open signal on `/overlays`.
1773    ///
1774    /// # Arguments
1775    ///
1776    /// - `&Self` - Reactive showcase state reference.
1777    ///
1778    /// # Returns
1779    ///
1780    /// - `Signal<bool>` - Modal open signal handle.
1781    #[must_use]
1782    pub fn get_modal_open(&self) -> Signal<bool> {
1783        self.overlays_group().get_modal_open()
1784    }
1785
1786    /// Returns the controlled drawer open signal on `/overlays`.
1787    ///
1788    /// # Arguments
1789    ///
1790    /// - `&Self` - Reactive showcase state reference.
1791    ///
1792    /// # Returns
1793    ///
1794    /// - `Signal<bool>` - Drawer open signal handle.
1795    #[must_use]
1796    pub fn get_drawer_open(&self) -> Signal<bool> {
1797        self.overlays_group().get_drawer_open()
1798    }
1799
1800    /// Returns the controlled sheet open signal on `/overlays`.
1801    ///
1802    /// # Arguments
1803    ///
1804    /// - `&Self` - Reactive showcase state reference.
1805    ///
1806    /// # Returns
1807    ///
1808    /// - `Signal<bool>` - Sheet open signal handle.
1809    #[must_use]
1810    pub fn get_sheet_open(&self) -> Signal<bool> {
1811        self.overlays_group().get_sheet_open()
1812    }
1813
1814    /// Returns the controlled popover open signal on `/overlays`.
1815    ///
1816    /// # Arguments
1817    ///
1818    /// - `&Self` - Reactive showcase state reference.
1819    ///
1820    /// # Returns
1821    ///
1822    /// - `Signal<bool>` - Popover open signal handle.
1823    #[must_use]
1824    pub fn get_popover_open(&self) -> Signal<bool> {
1825        self.overlays_group().get_popover_open()
1826    }
1827
1828    /// Returns the controlled dropdown open signal on `/overlays`.
1829    ///
1830    /// # Arguments
1831    ///
1832    /// - `&Self` - Reactive showcase state reference.
1833    ///
1834    /// # Returns
1835    ///
1836    /// - `Signal<bool>` - Dropdown open signal handle.
1837    #[must_use]
1838    pub fn get_dropdown_open(&self) -> Signal<bool> {
1839        self.overlays_group().get_dropdown_open()
1840    }
1841
1842    /// Returns the controlled dropdown selected index signal on `/overlays`.
1843    ///
1844    /// # Arguments
1845    ///
1846    /// - `&Self` - Reactive showcase state reference.
1847    ///
1848    /// # Returns
1849    ///
1850    /// - `Signal<Option<usize>>` - Dropdown selected index signal handle.
1851    #[must_use]
1852    pub fn get_dropdown_selected(&self) -> Signal<Option<usize>> {
1853        self.overlays_group().get_dropdown_selected()
1854    }
1855
1856    /// Returns the controlled toast banner visibility signal on `/overlays`.
1857    ///
1858    /// # Arguments
1859    ///
1860    /// - `&Self` - Reactive showcase state reference.
1861    ///
1862    /// # Returns
1863    ///
1864    /// - `Signal<bool>` - Toast visibility signal handle.
1865    #[must_use]
1866    pub fn get_toast_visible(&self) -> Signal<bool> {
1867        self.overlays_group().get_toast_visible()
1868    }
1869
1870    /// Returns the controlled notification visibility signal on `/overlays`.
1871    ///
1872    /// # Arguments
1873    ///
1874    /// - `&Self` - Reactive showcase state reference.
1875    ///
1876    /// # Returns
1877    ///
1878    /// - `Signal<bool>` - Notification visibility signal handle.
1879    #[must_use]
1880    pub fn get_notif_visible(&self) -> Signal<bool> {
1881        self.overlays_group().get_notif_visible()
1882    }
1883
1884    /// Returns the controlled loading overlay active signal on `/overlays`.
1885    ///
1886    /// # Arguments
1887    ///
1888    /// - `&Self` - Reactive showcase state reference.
1889    ///
1890    /// # Returns
1891    ///
1892    /// - `Signal<bool>` - Loading active signal handle.
1893    #[must_use]
1894    pub fn get_loading_active(&self) -> Signal<bool> {
1895        self.overlays_group().get_loading_active()
1896    }
1897
1898    /// Returns the vertical scroll offset signal driving the 10,000-row virtualized list on `/data`.
1899    ///
1900    /// # Arguments
1901    ///
1902    /// - `&Self` - Reactive showcase state reference.
1903    ///
1904    /// # Returns
1905    ///
1906    /// - `Signal<f32>` - Virtual list scroll offset signal handle.
1907    #[must_use]
1908    pub fn get_list_scroll_y(&self) -> Signal<f32> {
1909        self.data_group().get_list_scroll_y()
1910    }
1911
1912    /// Returns the live 3D quality and ray-tracing configuration signal.
1913    ///
1914    /// # Arguments
1915    ///
1916    /// - `&Self` - Reactive showcase state reference.
1917    ///
1918    /// # Returns
1919    ///
1920    /// - `Signal<RenderQualityConfig>` - 3D quality configuration signal handle.
1921    #[must_use]
1922    pub fn get_engine3d_quality(&self) -> Signal<RenderQualityConfig> {
1923        self.engine3d_group().get_engine3d_quality()
1924    }
1925
1926    /// Returns the live 3D quality preset index signal.
1927    ///
1928    /// # Arguments
1929    ///
1930    /// - `&Self` - Reactive showcase state reference.
1931    ///
1932    /// # Returns
1933    ///
1934    /// - `Signal<usize>` - 3D quality preset index signal handle.
1935    #[must_use]
1936    pub fn get_engine3d_preset_idx(&self) -> Signal<usize> {
1937        self.engine3d_group().get_engine3d_preset_idx()
1938    }
1939
1940    /// Returns the live 3D ray-tracing mode index signal.
1941    ///
1942    /// # Arguments
1943    ///
1944    /// - `&Self` - Reactive showcase state reference.
1945    ///
1946    /// # Returns
1947    ///
1948    /// - `Signal<usize>` - 3D ray-tracing mode index signal handle.
1949    #[must_use]
1950    pub fn get_engine3d_rt_idx(&self) -> Signal<usize> {
1951        self.engine3d_group().get_engine3d_rt_idx()
1952    }
1953
1954    /// Returns the live 3D internal resolution scale percentage signal.
1955    ///
1956    /// # Arguments
1957    ///
1958    /// - `&Self` - Reactive showcase state reference.
1959    ///
1960    /// # Returns
1961    ///
1962    /// - `Signal<f32>` - 3D resolution scale signal handle.
1963    #[must_use]
1964    pub fn get_engine3d_res_scale(&self) -> Signal<f32> {
1965        self.engine3d_group().get_engine3d_res_scale()
1966    }
1967
1968    /// Returns the live 3D sun time-of-day signal.
1969    ///
1970    /// # Arguments
1971    ///
1972    /// - `&Self` - Reactive showcase state reference.
1973    ///
1974    /// # Returns
1975    ///
1976    /// - `Signal<f32>` - 3D time-of-day signal handle.
1977    #[must_use]
1978    pub fn get_engine3d_time_of_day(&self) -> Signal<f32> {
1979        self.engine3d_group().get_engine3d_time_of_day()
1980    }
1981
1982    /// Returns the monotonic 3D model import request signal.
1983    ///
1984    /// # Arguments
1985    ///
1986    /// - `&Self` - Reactive showcase state reference.
1987    ///
1988    /// # Returns
1989    ///
1990    /// - `Signal<u64>` - 3D import queue signal handle.
1991    #[must_use]
1992    pub fn get_engine3d_import_queue(&self) -> Signal<u64> {
1993        self.engine3d_group().get_engine3d_import_queue()
1994    }
1995
1996    /// Returns the live 3D model import status readout signal.
1997    ///
1998    /// # Arguments
1999    ///
2000    /// - `&Self` - Reactive showcase state reference.
2001    ///
2002    /// # Returns
2003    ///
2004    /// - `Signal<String>` - 3D import status signal handle.
2005    #[must_use]
2006    pub fn get_engine3d_import_status(&self) -> Signal<String> {
2007        self.engine3d_group().get_engine3d_import_status()
2008    }
2009
2010    /// Returns the active 3D camera mode signal.
2011    ///
2012    /// # Arguments
2013    ///
2014    /// - `&Self` - Reactive showcase state reference.
2015    ///
2016    /// # Returns
2017    ///
2018    /// - `Signal<u8>` - 3D camera mode signal handle.
2019    #[must_use]
2020    pub fn get_engine3d_camera_mode(&self) -> Signal<u8> {
2021        self.engine3d_group().get_engine3d_camera_mode()
2022    }
2023
2024    /// Returns the active 3D TSR upscaling mode index signal.
2025    ///
2026    /// # Returns
2027    ///
2028    /// - `Signal<usize>` - 3D TSR mode index signal (`0=Native, 1=TSR 67%, 2=TSR 50%`).
2029    #[must_use]
2030    pub fn get_engine3d_tsr_idx(&self) -> Signal<usize> {
2031        self.engine3d_group().get_engine3d_tsr_idx()
2032    }
2033
2034    /// Returns the active 3D atmosphere mood preset index signal.
2035    ///
2036    /// # Returns
2037    ///
2038    /// - `Signal<usize>` - 3D atmosphere preset signal (`0=Sunset, 1=Rainy Night, 2=Noon, 3=Midnight`).
2039    #[must_use]
2040    pub fn get_engine3d_atmosphere_idx(&self) -> Signal<usize> {
2041        self.engine3d_group().get_engine3d_atmosphere_idx()
2042    }
2043
2044    /// Returns the preserved sibling counter signal on `/dynamic`.
2045    ///
2046    /// # Arguments
2047    ///
2048    /// - `&Self` - Reactive showcase state reference.
2049    ///
2050    /// # Returns
2051    ///
2052    /// - `Signal<i32>` - Sibling counter signal handle.
2053    #[must_use]
2054    pub fn get_sibling_counter(&self) -> Signal<i32> {
2055        self.dynamic_group().get_sibling_counter()
2056    }
2057
2058    /// Returns the latest dynamic OTA action log readout signal.
2059    ///
2060    /// # Arguments
2061    ///
2062    /// - `&Self` - Reactive showcase state reference.
2063    ///
2064    /// # Returns
2065    ///
2066    /// - `Signal<String>` - Dynamic action log signal handle.
2067    #[must_use]
2068    pub fn get_dynamic_action_log(&self) -> Signal<String> {
2069        self.dynamic_group().get_dynamic_action_log()
2070    }
2071
2072    /// Returns the simulated offline mode toggle signal for dynamic WASM tests.
2073    ///
2074    /// # Arguments
2075    ///
2076    /// - `&Self` - Reactive showcase state reference.
2077    ///
2078    /// # Returns
2079    ///
2080    /// - `Signal<bool>` - WASM offline flag signal handle.
2081    #[must_use]
2082    pub fn get_wasm_offline(&self) -> Signal<bool> {
2083        self.dynamic_group().get_wasm_offline()
2084    }
2085
2086    /// Returns the live dynamic WASM download and fault readout signal.
2087    ///
2088    /// # Arguments
2089    ///
2090    /// - `&Self` - Reactive showcase state reference.
2091    ///
2092    /// # Returns
2093    ///
2094    /// - `Signal<String>` - WASM fault status signal handle.
2095    #[must_use]
2096    pub fn get_wasm_fault_status(&self) -> Signal<String> {
2097        self.dynamic_group().get_wasm_fault_status()
2098    }
2099
2100    /// Returns the `EuvAlertDialog` open state signal on `/lab`.
2101    ///
2102    /// # Arguments
2103    ///
2104    /// - `&Self` - Reactive showcase state reference.
2105    ///
2106    /// # Returns
2107    ///
2108    /// - `Signal<bool>` - Alert dialog open signal handle.
2109    #[must_use]
2110    pub fn get_alert_dialog_open(&self) -> Signal<bool> {
2111        self.lab_group().get_alert_dialog_open()
2112    }
2113
2114    /// Returns the `EuvAlertDialog` confirmed flag signal on `/lab`.
2115    ///
2116    /// # Arguments
2117    ///
2118    /// - `&Self` - Reactive showcase state reference.
2119    ///
2120    /// # Returns
2121    ///
2122    /// - `Signal<bool>` - Alert dialog confirmed signal handle.
2123    #[must_use]
2124    pub fn get_alert_dialog_confirmed(&self) -> Signal<bool> {
2125        self.lab_group().get_alert_dialog_confirmed()
2126    }
2127
2128    /// Returns the `EuvCollapsible` expanded flag signal on `/lab`.
2129    ///
2130    /// # Arguments
2131    ///
2132    /// - `&Self` - Reactive showcase state reference.
2133    ///
2134    /// # Returns
2135    ///
2136    /// - `Signal<bool>` - Collapsible open signal handle.
2137    #[must_use]
2138    pub fn get_collapsible_open(&self) -> Signal<bool> {
2139        self.lab_group().get_collapsible_open()
2140    }
2141
2142    /// Returns the `EuvToggleGroup` active option index signal on `/lab`.
2143    ///
2144    /// # Arguments
2145    ///
2146    /// - `&Self` - Reactive showcase state reference.
2147    ///
2148    /// # Returns
2149    ///
2150    /// - `Signal<usize>` - Toggle group index signal handle.
2151    #[must_use]
2152    pub fn get_toggle_group_index(&self) -> Signal<usize> {
2153        self.lab_group().get_toggle_group_index()
2154    }
2155
2156    /// Returns the `EuvInputOtp` passcode string signal on `/lab`.
2157    ///
2158    /// # Arguments
2159    ///
2160    /// - `&Self` - Reactive showcase state reference.
2161    ///
2162    /// # Returns
2163    ///
2164    /// - `Signal<String>` - OTP code signal handle.
2165    #[must_use]
2166    pub fn get_otp_code(&self) -> Signal<String> {
2167        self.lab_group().get_otp_code()
2168    }
2169
2170    /// Returns the `EuvCommand` query string signal on `/lab`.
2171    ///
2172    /// # Arguments
2173    ///
2174    /// - `&Self` - Reactive showcase state reference.
2175    ///
2176    /// # Returns
2177    ///
2178    /// - `Signal<String>` - Command query signal handle.
2179    #[must_use]
2180    pub fn get_command_query(&self) -> Signal<String> {
2181        self.lab_group().get_command_query()
2182    }
2183
2184    /// Returns the `EuvCommand` selected index signal on `/lab`.
2185    ///
2186    /// # Arguments
2187    ///
2188    /// - `&Self` - Reactive showcase state reference.
2189    ///
2190    /// # Returns
2191    ///
2192    /// - `Signal<Option<usize>>` - Command selected index signal handle.
2193    #[must_use]
2194    pub fn get_command_selected(&self) -> Signal<Option<usize>> {
2195        self.lab_group().get_command_selected()
2196    }
2197
2198    /// Returns the `EuvHoverCard` open flag signal on `/lab`.
2199    ///
2200    /// # Arguments
2201    ///
2202    /// - `&Self` - Reactive showcase state reference.
2203    ///
2204    /// # Returns
2205    ///
2206    /// - `Signal<bool>` - Hover card open signal handle.
2207    #[must_use]
2208    pub fn get_hover_card_open(&self) -> Signal<bool> {
2209        self.lab_group().get_hover_card_open()
2210    }
2211
2212    /// Returns the `EuvCalendar` selected day signal on `/lab`.
2213    ///
2214    /// # Arguments
2215    ///
2216    /// - `&Self` - Reactive showcase state reference.
2217    ///
2218    /// # Returns
2219    ///
2220    /// - `Signal<u32>` - Calendar day signal handle.
2221    #[must_use]
2222    pub fn get_calendar_day(&self) -> Signal<u32> {
2223        self.lab_group().get_calendar_day()
2224    }
2225
2226    /// Returns the `EuvMenubar` active menu index signal on `/lab`.
2227    ///
2228    /// # Arguments
2229    ///
2230    /// - `&Self` - Reactive showcase state reference.
2231    ///
2232    /// # Returns
2233    ///
2234    /// - `Signal<Option<usize>>` - Menubar active index signal handle.
2235    #[must_use]
2236    pub fn get_menubar_active(&self) -> Signal<Option<usize>> {
2237        self.lab_group().get_menubar_active()
2238    }
2239
2240    /// Returns the `EuvCarousel` active slide index signal on `/lab`.
2241    ///
2242    /// # Arguments
2243    ///
2244    /// - `&Self` - Reactive showcase state reference.
2245    ///
2246    /// # Returns
2247    ///
2248    /// - `Signal<usize>` - Carousel index signal handle.
2249    #[must_use]
2250    pub fn get_carousel_index(&self) -> Signal<usize> {
2251        self.lab_group().get_carousel_index()
2252    }
2253
2254    /// Returns the `EuvCombobox` search query signal on `/lab`.
2255    ///
2256    /// # Arguments
2257    ///
2258    /// - `&Self` - Reactive showcase state reference.
2259    ///
2260    /// # Returns
2261    ///
2262    /// - `Signal<String>` - Combobox query signal handle.
2263    #[must_use]
2264    pub fn get_lab_combobox_query(&self) -> Signal<String> {
2265        self.lab_group().get_lab_combobox_query()
2266    }
2267
2268    /// Returns the `EuvCombobox` selected index signal on `/lab`.
2269    ///
2270    /// # Arguments
2271    ///
2272    /// - `&Self` - Reactive showcase state reference.
2273    ///
2274    /// # Returns
2275    ///
2276    /// - `Signal<usize>` - Combobox selected index signal handle.
2277    #[must_use]
2278    pub fn get_lab_combobox_selected(&self) -> Signal<usize> {
2279        self.lab_group().get_lab_combobox_selected()
2280    }
2281
2282    /// Returns the `EuvCombobox` open flag signal on `/lab`.
2283    ///
2284    /// # Arguments
2285    ///
2286    /// - `&Self` - Reactive showcase state reference.
2287    ///
2288    /// # Returns
2289    ///
2290    /// - `Signal<bool>` - Combobox open signal handle.
2291    #[must_use]
2292    pub fn get_lab_combobox_open(&self) -> Signal<bool> {
2293        self.lab_group().get_lab_combobox_open()
2294    }
2295
2296    /// Returns the `EuvDataTable` filter string signal on `/lab`.
2297    ///
2298    /// # Arguments
2299    ///
2300    /// - `&Self` - Reactive showcase state reference.
2301    ///
2302    /// # Returns
2303    ///
2304    /// - `Signal<String>` - Data table filter signal handle.
2305    #[must_use]
2306    pub fn get_lab_table_filter(&self) -> Signal<String> {
2307        self.lab_group().get_lab_table_filter()
2308    }
2309
2310    /// Returns the `EuvDataTable` ascending sort flag signal on `/lab`.
2311    ///
2312    /// # Arguments
2313    ///
2314    /// - `&Self` - Reactive showcase state reference.
2315    ///
2316    /// # Returns
2317    ///
2318    /// - `Signal<bool>` - Data table sort flag signal handle.
2319    #[must_use]
2320    pub fn get_lab_table_sort_asc(&self) -> Signal<bool> {
2321        self.lab_group().get_lab_table_sort_asc()
2322    }
2323
2324    /// Returns the `EuvDataTable` selected row index signal on `/lab`.
2325    ///
2326    /// # Arguments
2327    ///
2328    /// - `&Self` - Reactive showcase state reference.
2329    ///
2330    /// # Returns
2331    ///
2332    /// - `Signal<Option<usize>>` - Data table selected row signal handle.
2333    #[must_use]
2334    pub fn get_lab_table_selected(&self) -> Signal<Option<usize>> {
2335        self.lab_group().get_lab_table_selected()
2336    }
2337
2338    /// Returns the `EuvDatePicker` selected day signal on `/lab`.
2339    ///
2340    /// # Arguments
2341    ///
2342    /// - `&Self` - Reactive showcase state reference.
2343    ///
2344    /// # Returns
2345    ///
2346    /// - `Signal<u32>` - Date picker day signal handle.
2347    #[must_use]
2348    pub fn get_lab_date_day(&self) -> Signal<u32> {
2349        self.lab_group().get_lab_date_day()
2350    }
2351
2352    /// Returns the `EuvDatePicker` open flag signal on `/lab`.
2353    ///
2354    /// # Arguments
2355    ///
2356    /// - `&Self` - Reactive showcase state reference.
2357    ///
2358    /// # Returns
2359    ///
2360    /// - `Signal<bool>` - Date picker open signal handle.
2361    #[must_use]
2362    pub fn get_lab_date_open(&self) -> Signal<bool> {
2363        self.lab_group().get_lab_date_open()
2364    }
2365
2366    /// Returns the `EuvInputGroup` domain input value signal on `/lab`.
2367    ///
2368    /// # Arguments
2369    ///
2370    /// - `&Self` - Reactive showcase state reference.
2371    ///
2372    /// # Returns
2373    ///
2374    /// - `Signal<String>` - Input group value signal handle.
2375    #[must_use]
2376    pub fn get_lab_input_group_val(&self) -> Signal<String> {
2377        self.lab_group().get_lab_input_group_val()
2378    }
2379
2380    /// Returns the `EuvNativeSelect` selected index signal on `/lab`.
2381    ///
2382    /// # Arguments
2383    ///
2384    /// - `&Self` - Reactive showcase state reference.
2385    ///
2386    /// # Returns
2387    ///
2388    /// - `Signal<usize>` - Native select index signal handle.
2389    #[must_use]
2390    pub fn get_lab_native_select_idx(&self) -> Signal<usize> {
2391        self.lab_group().get_lab_native_select_idx()
2392    }
2393
2394    /// Returns the `EuvNavigationMenu` active dropdown index signal on `/lab`.
2395    ///
2396    /// # Arguments
2397    ///
2398    /// - `&Self` - Reactive showcase state reference.
2399    ///
2400    /// # Returns
2401    ///
2402    /// - `Signal<Option<usize>>` - Navigation menu active index signal handle.
2403    #[must_use]
2404    pub fn get_lab_nav_menu_active(&self) -> Signal<Option<usize>> {
2405        self.lab_group().get_lab_nav_menu_active()
2406    }
2407
2408    /// Returns the `EuvResizable` split ratio signal on `/lab`.
2409    ///
2410    /// # Arguments
2411    ///
2412    /// - `&Self` - Reactive showcase state reference.
2413    ///
2414    /// # Returns
2415    ///
2416    /// - `Signal<f32>` - Split ratio signal handle.
2417    #[must_use]
2418    pub fn get_lab_split_ratio(&self) -> Signal<f32> {
2419        self.lab_group().get_lab_split_ratio()
2420    }
2421
2422    /// Returns the nested scroll-chaining block toggle signal on `/lab`.
2423    ///
2424    /// # Arguments
2425    ///
2426    /// - `&Self` - Reactive showcase state reference.
2427    ///
2428    /// # Returns
2429    ///
2430    /// - `Signal<bool>` - Scroll chain toggle signal handle.
2431    #[must_use]
2432    pub fn get_lab_block_scroll_chain(&self) -> Signal<bool> {
2433        self.lab_group().get_lab_block_scroll_chain()
2434    }
2435
2436    /// Returns the click event bubbling stop toggle signal on `/lab`.
2437    ///
2438    /// # Arguments
2439    ///
2440    /// - `&Self` - Reactive showcase state reference.
2441    ///
2442    /// # Returns
2443    ///
2444    /// - `Signal<bool>` - Click bubble toggle signal handle.
2445    #[must_use]
2446    pub fn get_lab_stop_click_bubble(&self) -> Signal<bool> {
2447        self.lab_group().get_lab_stop_click_bubble()
2448    }
2449
2450    /// Returns the outer parent card click counter signal on `/lab`.
2451    ///
2452    /// # Arguments
2453    ///
2454    /// - `&Self` - Reactive showcase state reference.
2455    ///
2456    /// # Returns
2457    ///
2458    /// - `Signal<u32>` - Parent click counter signal handle.
2459    #[must_use]
2460    pub fn get_lab_parent_clicks(&self) -> Signal<u32> {
2461        self.lab_group().get_lab_parent_clicks()
2462    }
2463
2464    /// Returns the inner child button click counter signal on `/lab`.
2465    ///
2466    /// # Arguments
2467    ///
2468    /// - `&Self` - Reactive showcase state reference.
2469    ///
2470    /// # Returns
2471    ///
2472    /// - `Signal<u32>` - Child click counter signal handle.
2473    #[must_use]
2474    pub fn get_lab_child_clicks(&self) -> Signal<u32> {
2475        self.lab_group().get_lab_child_clicks()
2476    }
2477
2478    /// Returns the resize state-preservation counter signal on `/lab`.
2479    ///
2480    /// # Arguments
2481    ///
2482    /// - `&Self` - Reactive showcase state reference.
2483    ///
2484    /// # Returns
2485    ///
2486    /// - `Signal<u32>` - Resize preserve counter signal handle.
2487    #[must_use]
2488    pub fn get_lab_resize_preserve_count(&self) -> Signal<u32> {
2489        self.lab_group().get_lab_resize_preserve_count()
2490    }
2491
2492    /// Returns the RTL direction mode toggle signal on `/lab`.
2493    ///
2494    /// # Arguments
2495    ///
2496    /// - `&Self` - Reactive showcase state reference.
2497    ///
2498    /// # Returns
2499    ///
2500    /// - `Signal<bool>` - RTL mode signal handle.
2501    #[must_use]
2502    pub fn get_lab_rtl_mode(&self) -> Signal<bool> {
2503        self.lab_group().get_lab_rtl_mode()
2504    }
2505
2506    /// Returns the animated GIF playback signal on `/media`.
2507    ///
2508    /// # Arguments
2509    ///
2510    /// - `&Self` - Reactive showcase state reference.
2511    ///
2512    /// # Returns
2513    ///
2514    /// - `Signal<GifAnimation>` - GIF animation signal handle.
2515    #[must_use]
2516    pub fn get_media_gif(&self) -> Signal<GifAnimation> {
2517        self.media_group().get_media_gif()
2518    }
2519
2520    /// Returns the LIVE Photo asset signal on `/media`.
2521    ///
2522    /// # Arguments
2523    ///
2524    /// - `&Self` - Reactive showcase state reference.
2525    ///
2526    /// # Returns
2527    ///
2528    /// - `Signal<LivePhotoAsset>` - LIVE Photo signal handle.
2529    #[must_use]
2530    pub fn get_media_live(&self) -> Signal<LivePhotoAsset> {
2531        self.media_group().get_media_live()
2532    }
2533
2534    /// Returns the cross-platform video track signal on `/media`.
2535    ///
2536    /// # Arguments
2537    ///
2538    /// - `&Self` - Reactive showcase state reference.
2539    ///
2540    /// # Returns
2541    ///
2542    /// - `Signal<VideoTrack>` - Video track signal handle.
2543    #[must_use]
2544    pub fn get_media_video(&self) -> Signal<VideoTrack> {
2545        self.media_group().get_media_video()
2546    }
2547
2548    /// Returns the WAV audio waveform track signal on `/media`.
2549    ///
2550    /// # Arguments
2551    ///
2552    /// - `&Self` - Reactive showcase state reference.
2553    ///
2554    /// # Returns
2555    ///
2556    /// - `Signal<AudioTrack>` - Audio track signal handle.
2557    #[must_use]
2558    pub fn get_media_audio(&self) -> Signal<AudioTrack> {
2559        self.media_group().get_media_audio()
2560    }
2561
2562    /// Returns the multi-page PDF document signal on `/media`.
2563    ///
2564    /// # Arguments
2565    ///
2566    /// - `&Self` - Reactive showcase state reference.
2567    ///
2568    /// # Returns
2569    ///
2570    /// - `Signal<PdfDocument>` - PDF document signal handle.
2571    #[must_use]
2572    pub fn get_media_pdf(&self) -> Signal<PdfDocument> {
2573        self.media_group().get_media_pdf()
2574    }
2575
2576    /// Returns the Media Studio HTML link click log signal.
2577    ///
2578    /// # Arguments
2579    ///
2580    /// - `&Self` - Reactive showcase state reference.
2581    ///
2582    /// # Returns
2583    ///
2584    /// - `Signal<String>` - Media HTML link log signal handle.
2585    #[must_use]
2586    pub fn get_media_html_link_log(&self) -> Signal<String> {
2587        self.media_group().get_media_html_link_log()
2588    }
2589
2590    /// Returns the Media Studio background-decode loading state signal.
2591    ///
2592    /// # Arguments
2593    ///
2594    /// - `&Self` - Reactive showcase state reference.
2595    ///
2596    /// # Returns
2597    ///
2598    /// - `Signal<bool>` - Media loading state signal handle.
2599    #[must_use]
2600    pub fn get_media_loading(&self) -> Signal<bool> {
2601        self.media_group().get_media_loading()
2602    }
2603
2604    /// Returns the Markdown code block copy telemetry signal.
2605    ///
2606    /// # Arguments
2607    ///
2608    /// - `&Self` - Reactive showcase state reference.
2609    ///
2610    /// # Returns
2611    ///
2612    /// - `Signal<String>` - Markdown copy log signal handle.
2613    #[must_use]
2614    pub fn get_markdown_copy_log(&self) -> Signal<String> {
2615        self.markdown_group().get_markdown_copy_log()
2616    }
2617
2618    /// Returns the Markdown hyperlink click telemetry signal.
2619    ///
2620    /// # Arguments
2621    ///
2622    /// - `&Self` - Reactive showcase state reference.
2623    ///
2624    /// # Returns
2625    ///
2626    /// - `Signal<String>` - Markdown link log signal handle.
2627    #[must_use]
2628    pub fn get_markdown_link_log(&self) -> Signal<String> {
2629        self.markdown_group().get_markdown_link_log()
2630    }
2631
2632    /// Returns the Markdown GFM task toggle counter signal.
2633    ///
2634    /// # Arguments
2635    ///
2636    /// - `&Self` - Reactive showcase state reference.
2637    ///
2638    /// # Returns
2639    ///
2640    /// - `Signal<u32>` - Markdown tasks toggled signal handle.
2641    #[must_use]
2642    pub fn get_markdown_tasks_toggled(&self) -> Signal<u32> {
2643        self.markdown_group().get_markdown_tasks_toggled()
2644    }
2645
2646    /// Returns the Markdown code example language tab index signal.
2647    ///
2648    /// # Arguments
2649    ///
2650    /// - `&Self` - Reactive showcase state reference.
2651    ///
2652    /// # Returns
2653    ///
2654    /// - `Signal<usize>` - Markdown language tab signal handle.
2655    #[must_use]
2656    pub fn get_markdown_lang_tab(&self) -> Signal<usize> {
2657        self.markdown_group().get_markdown_lang_tab()
2658    }
2659
2660    /// Returns the Markdown selectable text toggle signal.
2661    ///
2662    /// # Arguments
2663    ///
2664    /// - `&Self` - Reactive showcase state reference.
2665    ///
2666    /// # Returns
2667    ///
2668    /// - `Signal<bool>` - Markdown selectable signal handle.
2669    #[must_use]
2670    pub fn get_markdown_selectable(&self) -> Signal<bool> {
2671        self.markdown_group().get_markdown_selectable()
2672    }
2673
2674    /// Returns the Stress Lab benchmark results list signal.
2675    ///
2676    /// # Arguments
2677    ///
2678    /// - `&Self` - Reactive showcase state reference.
2679    ///
2680    /// # Returns
2681    ///
2682    /// - `Signal<Vec<StressCaseResult>>` - Stress results signal handle.
2683    #[must_use]
2684    pub fn get_stress_results(&self) -> Signal<Vec<StressCaseResult>> {
2685        self.stress_group().get_stress_results()
2686    }
2687
2688    /// Returns the Stress Lab summary readout signal.
2689    ///
2690    /// # Arguments
2691    ///
2692    /// - `&Self` - Reactive showcase state reference.
2693    ///
2694    /// # Returns
2695    ///
2696    /// - `Signal<String>` - Stress summary signal handle.
2697    #[must_use]
2698    pub fn get_stress_summary(&self) -> Signal<String> {
2699        self.stress_group().get_stress_summary()
2700    }
2701
2702    /// Returns the ECharts Studio category filter index signal.
2703    ///
2704    /// # Arguments
2705    ///
2706    /// - `&Self` - Reactive showcase state reference.
2707    ///
2708    /// # Returns
2709    ///
2710    /// - `Signal<usize>` - Charts category index signal handle.
2711    #[must_use]
2712    pub fn get_charts_category_idx(&self) -> Signal<usize> {
2713        self.charts_group().get_charts_category_idx()
2714    }
2715
2716    /// Returns the ECharts Studio live interaction readout signal.
2717    ///
2718    /// # Arguments
2719    ///
2720    /// - `&Self` - Reactive showcase state reference.
2721    ///
2722    /// # Returns
2723    ///
2724    /// - `Signal<String>` - Charts event log signal handle.
2725    #[must_use]
2726    pub fn get_charts_event_log(&self) -> Signal<String> {
2727        self.charts_group().get_charts_event_log()
2728    }
2729
2730    /// Lazily hydrates Media Studio sample assets on first `/media` visit, using a background worker thread on interactive native apps.
2731    ///
2732    /// # Arguments
2733    ///
2734    /// - `&Self` - Reactive showcase state reference.
2735    pub fn ensure_media_loaded(&self) {
2736        if self.get_media_loaded().replace(true) {
2737            return;
2738        }
2739        if self.get_bg_workers_enabled().get() {
2740            let group: MediaSignals = self.media_group();
2741            let _: bool = group.get_media_loading().set_if_changed(true);
2742            let task: BackgroundTask<MediaSampleBundle> =
2743                BackgroundTask::spawn(Self::build_media_sample_bundle);
2744            let _: bool = group.get_media_bg_task().set(Some(task));
2745            return;
2746        }
2747        let bundle: MediaSampleBundle = Self::build_media_sample_bundle();
2748        self.commit_media_sample_bundle(bundle);
2749    }
2750
2751    /// Builds the complete Media Studio sample codec bundle (GIF89a, LIVE Photo, MP4, WAV, PDF).
2752    ///
2753    /// # Returns
2754    ///
2755    /// - `MediaSampleBundle` - Decoded sample media assets ready for signal commit.
2756    fn build_media_sample_bundle() -> MediaSampleBundle {
2757        MediaSampleBundle {
2758            gif: Self::build_decoded_sample_gif(),
2759            live: LivePhotoAsset::sample_live_photo(),
2760            video: Self::build_decoded_sample_mp4(),
2761            audio: AudioTrack::sample_synth_wav(),
2762            pdf: PdfDocument::sample_pdf(),
2763        }
2764    }
2765
2766    /// Commits a decoded `MediaSampleBundle` into the reactive Media Studio signals on the UI thread.
2767    ///
2768    /// # Arguments
2769    ///
2770    /// - `&Self` - Reactive showcase state reference.
2771    /// - `MediaSampleBundle` - Decoded sample media assets.
2772    fn commit_media_sample_bundle(&self, bundle: MediaSampleBundle) {
2773        let group: MediaSignals = self.media_group();
2774        let MediaSampleBundle {
2775            gif,
2776            live,
2777            video,
2778            audio,
2779            pdf,
2780        } = bundle;
2781        let _: bool = group.get_media_gif().set(gif);
2782        let _: bool = group.get_media_live().set(live);
2783        let _: bool = group.get_media_video().set(video);
2784        let _: bool = group.get_media_audio().set(audio);
2785        let _: bool = group.get_media_pdf().set(pdf);
2786        let _: bool = group.get_media_loading().set_if_changed(false);
2787    }
2788
2789    /// Encodes and decodes a real LZW-compressed GIF89a sample stream through `GifEncoder` and `MediaCodecRegistry::decode_gif`.
2790    ///
2791    /// # Returns
2792    ///
2793    /// - `GifAnimation` - Decoded animated GIF ready for Media Studio playback.
2794    fn build_decoded_sample_gif() -> GifAnimation {
2795        let width: u16 = 220;
2796        let height: u16 = 124;
2797        let palette: [[u8; 3]; 8] = [
2798            [17, 24, 39],
2799            [30, 41, 59],
2800            [56, 189, 248],
2801            [168, 85, 247],
2802            [244, 63, 94],
2803            [52, 211, 153],
2804            [226, 232, 240],
2805            [15, 23, 42],
2806        ];
2807        let pixel_count: usize = (width as usize) * (height as usize);
2808        let mut inputs: Vec<GifEncodeFrameInput> = Vec::with_capacity(8);
2809        for frame_idx in 0..8usize {
2810            let accent_idx: u8 = (2 + (frame_idx % 4)) as u8;
2811            let bar_x: usize = (frame_idx * 24) % (width as usize);
2812            let mut indices: Vec<u8> = vec![0u8; pixel_count];
2813            for pos_y in 0..(height as usize) {
2814                let row_off: usize = pos_y * (width as usize);
2815                let is_band: bool = (42..82).contains(&pos_y);
2816                for pos_x in 0..(width as usize) {
2817                    let dist: usize = pos_x.abs_diff(bar_x);
2818                    let color_idx: u8 = if is_band && dist < 18 {
2819                        accent_idx
2820                    } else if (pos_x / 16 + pos_y / 16 + frame_idx) % 2 == 0 {
2821                        1
2822                    } else {
2823                        7
2824                    };
2825                    indices[row_off + pos_x] = color_idx;
2826                }
2827            }
2828            let mut frame: GifEncodeFrameInput = GifEncodeFrameInput::default();
2829            frame
2830                .set_width(width)
2831                .set_height(height)
2832                .set_disposal(GifDisposalMethod::Keep)
2833                .set_delay_cs(12)
2834                .set_indices(indices);
2835            inputs.push(frame);
2836        }
2837        let encoded: Vec<u8> = GifEncoder::encode(width, height, &palette, Some(0), &inputs);
2838        MediaCodecRegistry::decode_gif(&encoded, MEDIA_GIF_TITLE)
2839            .unwrap_or_else(|_: String| GifAnimation::sample_neon_gif())
2840    }
2841
2842    /// Builds and decodes a real ISOBMFF MP4 stream through `Mp4ContainerBuilder` and `VideoTrack::from_mp4_bytes`.
2843    ///
2844    /// # Returns
2845    ///
2846    /// - `VideoTrack` - Decoded HDR MP4 video track ready for Media Studio playback.
2847    fn build_decoded_sample_mp4() -> VideoTrack {
2848        let width: u32 = 280;
2849        let height: u32 = 158;
2850        let accents: [Color; 4] = [
2851            Color::hex(0x22D3EE),
2852            Color::hex(0x6366F1),
2853            Color::hex(0xEC4899),
2854            Color::hex(0x10B981),
2855        ];
2856        let mut samples: Vec<Mp4BuilderSample> = Vec::with_capacity(12);
2857        for idx in 0..12usize {
2858            let img: ImageBuffer = MediaCodecRegistry::synthesize_frame(
2859                width,
2860                height,
2861                Color::hex(0x090D16),
2862                accents[idx % accents.len()],
2863                idx + 1,
2864            );
2865            let payload: Vec<u8> =
2866                SoftwareVideoDecoder::encode_intra_rgba_packet(width, height, img.get_pixels());
2867            let mut sample: Mp4BuilderSample = Mp4BuilderSample::default();
2868            sample
2869                .set_duration_ticks(1_000)
2870                .set_composition_offset_ticks(0)
2871                .set_is_keyframe(idx % 4 == 0)
2872                .set_payload(payload);
2873            samples.push(sample);
2874        }
2875        let mp4_bytes: Vec<u8> = Mp4ContainerBuilder::build_video_mp4(
2876            width,
2877            height,
2878            1_000,
2879            VideoCodec::H264,
2880            VideoColorInfo::hdr10_bt2020_pq(1000, 400),
2881            &samples,
2882        );
2883        match VideoTrack::from_mp4_bytes(mp4_bytes, MEDIA_VIDEO_TITLE) {
2884            Ok(mut track) => {
2885                let captions: Vec<String> = MEDIA_VIDEO_CAPTIONS
2886                    .iter()
2887                    .map(|line: &&str| (*line).to_string())
2888                    .collect();
2889                track.set_captions(captions);
2890                track
2891            }
2892            Err(_) => VideoTrack::sample_hdr_video(),
2893        }
2894    }
2895
2896    /// Lazily populates the in-memory `.wasm` OTA registry on first `/dynamic` visit, offloading payload assembly to a background worker on interactive native apps.
2897    ///
2898    /// # Arguments
2899    ///
2900    /// - `&Self` - Reactive showcase state reference.
2901    pub fn ensure_wasm_registry_loaded(&self) {
2902        if self.get_wasm_registry_loaded().replace(true) {
2903            return;
2904        }
2905        if self.get_bg_workers_enabled().get() {
2906            let group: DynamicSignals = self.dynamic_group();
2907            let _: bool = group
2908                .get_wasm_fault_status()
2909                .set_if_changed(STATUS_WASM_LOADING.to_string());
2910            let task: BackgroundTask<WasmSampleBundle> =
2911                BackgroundTask::spawn(Self::build_wasm_sample_bundle);
2912            let _: bool = group.get_wasm_bg_task().set(Some(task));
2913            return;
2914        }
2915        Self::populate_wasm_registry(self.get_wasm_registry());
2916    }
2917
2918    /// Commits any pending in-flight background WASM registry build synchronously so interactive clicks never race the worker.
2919    ///
2920    /// # Arguments
2921    ///
2922    /// - `&Self` - Reactive showcase state reference.
2923    pub fn ensure_wasm_registry_ready_now(&self) {
2924        self.ensure_wasm_registry_loaded();
2925        if let Some(group) = self.get_dynamic_signals().get()
2926            && let Some(task) = group.get_wasm_bg_task().get_untracked()
2927            && let Some(bundle) = task.take_blocking()
2928        {
2929            Self::commit_wasm_sample_bundle(self.get_wasm_registry(), bundle);
2930            let _: bool = group.get_wasm_bg_task().set(None);
2931            let _: bool = group
2932                .get_wasm_fault_status()
2933                .set_if_changed(DEFAULT_WASM_STATUS.to_string());
2934        }
2935    }
2936
2937    /// Polls any active background worker tasks (`/media`, `/dynamic`) and commits finished payloads atomically onto the UI thread.
2938    ///
2939    /// # Arguments
2940    ///
2941    /// - `&Self` - Reactive showcase state reference.
2942    ///
2943    /// # Returns
2944    ///
2945    /// - `bool` - `true` if any background payload committed on this frame.
2946    pub fn poll_async_loads(&self) -> bool {
2947        let mut committed: bool = false;
2948        if let Some(media) = self.get_media_signals().get()
2949            && let Some(task) = media.get_media_bg_task().get_untracked()
2950            && let Some(bundle) = task.try_take()
2951        {
2952            let _: bool = media.get_media_bg_task().set(None);
2953            self.commit_media_sample_bundle(bundle);
2954            committed = true;
2955        }
2956        if let Some(dyn_group) = self.get_dynamic_signals().get()
2957            && let Some(task) = dyn_group.get_wasm_bg_task().get_untracked()
2958            && let Some(bundle) = task.try_take()
2959        {
2960            let _: bool = dyn_group.get_wasm_bg_task().set(None);
2961            Self::commit_wasm_sample_bundle(self.get_wasm_registry(), bundle);
2962            let _: bool = dyn_group
2963                .get_wasm_fault_status()
2964                .set_if_changed(DEFAULT_WASM_STATUS.to_string());
2965            committed = true;
2966        }
2967        committed
2968    }
2969
2970    /// Lazily initializes the Stress Lab workload descriptors on first `/stress` visit.
2971    ///
2972    /// # Arguments
2973    ///
2974    /// - `&Self` - Reactive showcase state reference.
2975    pub fn ensure_stress_loaded(&self) {
2976        if self.get_stress_loaded().replace(true) {
2977            return;
2978        }
2979        let _: bool = self.get_stress_results().set(default_stress_results());
2980    }
2981
2982    /// Lazily marks ECharts Studio hydrated on first `/charts` visit so Frame 1 incurs zero chart option allocations.
2983    ///
2984    /// # Arguments
2985    ///
2986    /// - `&Self` - Reactive showcase state reference.
2987    pub fn ensure_charts_loaded(&self) {
2988        let _: bool = self.get_charts_loaded().replace(true);
2989    }
2990
2991    /// Assembles all genuine executable partial, global, and fault-case `.wasm` binary entries into a `Send` bundle.
2992    ///
2993    /// # Returns
2994    ///
2995    /// - `WasmSampleBundle` - Pre-built `.wasm` registry entries.
2996    fn build_wasm_sample_bundle() -> WasmSampleBundle {
2997        let p_v1: Vec<u8> = build_partial_widget_wasm(TITLE_WASM_PARTIAL_V1, 1, 0x2563EB);
2998        let p_v2: Vec<u8> = build_partial_widget_wasm(WASM_TITLE_PARTIAL_V2, 2, 0x7C3AED);
2999        let g_v1: Vec<u8> = build_global_app_wasm(WASM_TITLE_GLOBAL_V1, 1);
3000        let g_v2: Vec<u8> = build_global_app_wasm(WASM_TITLE_GLOBAL_V2, 2);
3001        let entries: Vec<WasmRegistryEntry> = vec![
3002            WasmRegistryEntry {
3003                url: URL_WASM_PARTIAL_V1.to_string(),
3004                bytes: p_v1.clone(),
3005                etag: WASM_ETAG_P1.to_string(),
3006                fault: WasmFaultKind::None,
3007            },
3008            WasmRegistryEntry {
3009                url: URL_WASM_PARTIAL_V2.to_string(),
3010                bytes: p_v2,
3011                etag: WASM_ETAG_P2.to_string(),
3012                fault: WasmFaultKind::None,
3013            },
3014            WasmRegistryEntry {
3015                url: URL_WASM_GLOBAL_V1.to_string(),
3016                bytes: g_v1,
3017                etag: WASM_ETAG_G1.to_string(),
3018                fault: WasmFaultKind::None,
3019            },
3020            WasmRegistryEntry {
3021                url: URL_WASM_GLOBAL_V2.to_string(),
3022                bytes: g_v2,
3023                etag: WASM_ETAG_G2.to_string(),
3024                fault: WasmFaultKind::None,
3025            },
3026            WasmRegistryEntry {
3027                url: URL_WASM_TIMEOUT_RETRY.to_string(),
3028                bytes: p_v1.clone(),
3029                etag: WASM_ETAG_RETRY.to_string(),
3030                fault: WasmFaultKind::TimeoutOnceThenSucceed,
3031            },
3032            WasmRegistryEntry {
3033                url: URL_WASM_HTTP_500.to_string(),
3034                bytes: p_v1.clone(),
3035                etag: WASM_ETAG_500.to_string(),
3036                fault: WasmFaultKind::Http500,
3037            },
3038            WasmRegistryEntry {
3039                url: URL_WASM_CORRUPTED.to_string(),
3040                bytes: build_faulty_wasm(WasmFaultKind::CorruptedMagic),
3041                etag: WASM_ETAG_CORRUPT.to_string(),
3042                fault: WasmFaultKind::None,
3043            },
3044            WasmRegistryEntry {
3045                url: URL_WASM_TAMPERED.to_string(),
3046                bytes: p_v1,
3047                etag: WASM_ETAG_TAMPER.to_string(),
3048                fault: WasmFaultKind::TamperedChecksum,
3049            },
3050            WasmRegistryEntry {
3051                url: URL_WASM_BAD_ABI.to_string(),
3052                bytes: build_faulty_wasm(WasmFaultKind::AbiMismatch),
3053                etag: WASM_ETAG_ABI.to_string(),
3054                fault: WasmFaultKind::None,
3055            },
3056            WasmRegistryEntry {
3057                url: URL_WASM_MISSING_EXPORT.to_string(),
3058                bytes: build_faulty_wasm(WasmFaultKind::MissingExport),
3059                etag: WASM_ETAG_NOEXP.to_string(),
3060                fault: WasmFaultKind::None,
3061            },
3062            WasmRegistryEntry {
3063                url: URL_WASM_FUEL_BOMB.to_string(),
3064                bytes: build_faulty_wasm(WasmFaultKind::InfiniteLoopOutOfFuel),
3065                etag: WASM_ETAG_FUEL.to_string(),
3066                fault: WasmFaultKind::None,
3067            },
3068            WasmRegistryEntry {
3069                url: URL_WASM_TRAP.to_string(),
3070                bytes: build_faulty_wasm(WasmFaultKind::ExecutionTrap),
3071                etag: WASM_ETAG_TRAP.to_string(),
3072                fault: WasmFaultKind::None,
3073            },
3074            WasmRegistryEntry {
3075                url: URL_WASM_OVERSIZED.to_string(),
3076                bytes: build_faulty_wasm(WasmFaultKind::OversizedBinary),
3077                etag: WASM_ETAG_BIG.to_string(),
3078                fault: WasmFaultKind::None,
3079            },
3080        ];
3081        WasmSampleBundle { entries }
3082    }
3083
3084    /// Commits a pre-built `WasmSampleBundle` into `registry`.
3085    ///
3086    /// # Arguments
3087    ///
3088    /// - `&RegistryWasmFetcher` - Target CDN registry fetcher.
3089    /// - `WasmSampleBundle` - Pre-built registry entries.
3090    fn commit_wasm_sample_bundle(registry: &RegistryWasmFetcher, bundle: WasmSampleBundle) {
3091        let WasmSampleBundle { entries } = bundle;
3092        for entry in entries.into_iter() {
3093            let WasmRegistryEntry {
3094                url,
3095                bytes,
3096                etag,
3097                fault,
3098            } = entry;
3099            registry.register(url, bytes, etag, fault);
3100        }
3101    }
3102
3103    /// Registers genuine executable partial, global, and fault-case `.wasm` binaries into `registry`.
3104    ///
3105    /// # Arguments
3106    ///
3107    /// - `&RegistryWasmFetcher` - Target CDN registry fetcher.
3108    pub fn populate_wasm_registry(registry: &RegistryWasmFetcher) {
3109        let bundle: WasmSampleBundle = Self::build_wasm_sample_bundle();
3110        Self::commit_wasm_sample_bundle(registry, bundle);
3111    }
3112
3113    /// Formats a concise single-line top navbar title for `route`.
3114    ///
3115    /// # Arguments
3116    ///
3117    /// - `&str` - Active route path.
3118    ///
3119    /// # Returns
3120    ///
3121    /// - `String` - Concise 1-2 word page title for the top navigation bar.
3122    #[must_use]
3123    pub fn breadcrumb_for_route(route: &str) -> String {
3124        SHOWCASE_ROUTES
3125            .iter()
3126            .find(|spec: &&ShowcaseRouteSpec| spec.get_path() == route)
3127            .map(|spec: &ShowcaseRouteSpec| spec.get_title())
3128            .unwrap_or(route)
3129            .to_string()
3130    }
3131
3132    /// Registers dynamic OTA and WASM event handlers on `self.dynamic_hub` without eagerly allocating `/dynamic` signals.
3133    ///
3134    /// # Arguments
3135    ///
3136    /// - `&Self` - Reactive showcase state reference.
3137    fn wire_dynamic_hub_actions(&self) {
3138        let route_sig: Signal<String> = self.get_route();
3139        let dyn_cell: Rc<Cell<Option<DynamicSignals>>> = self.get_dynamic_signals().clone();
3140        let owner_scope: Scope = self.get_state_scope();
3141        let mgr_act: WasmDynamicManager = self.get_wasm_manager().clone();
3142        self.get_dynamic_hub()
3143            .on_action(move |ui_event: &DynamicActionEvent| {
3144                let dyn_group: DynamicSignals =
3145                    DynamicSignals::get_or_init(dyn_cell.as_ref(), owner_scope);
3146                let action_log: Signal<String> = dyn_group.get_dynamic_action_log();
3147                let wasm_status: Signal<String> = dyn_group.get_wasm_fault_status();
3148                let summary: String = format!(
3149                    "{} from {} ({})",
3150                    ui_event.get_action(),
3151                    ui_event.get_source_id(),
3152                    ui_event.get_payload()
3153                );
3154                let _: bool = action_log.set_if_changed(summary);
3155                if let Some(target_route) = ui_event.get_action().strip_prefix("navigate:") {
3156                    let _: bool = route_sig.set_if_changed(target_route.to_string());
3157                } else if ui_event.get_action().as_str() == "return_dynamic" {
3158                    let _: bool = route_sig.set_if_changed(ROUTE_DYNAMIC.to_string());
3159                } else if ui_event.get_action().as_str() == "wasm_interact" {
3160                    let scope: WasmDynamicScope = WasmDynamicScope::Partial {
3161                        slot_id: SLOT_WASM_WIDGET.to_string(),
3162                    };
3163                    match mgr_act.dispatch_wasm_event(&scope, 1) {
3164                        Ok(next_st) => {
3165                            let _: bool = wasm_status.set(format!(
3166                                "WASM euv_on_event executed inside sandbox -> next_state={next_st} (native UI re-rendered)"
3167                            ));
3168                        }
3169                        Err(err) => {
3170                            let _: bool = wasm_status.set(format!("WASM event error: {err}"));
3171                        }
3172                    }
3173                } else if ui_event.get_action().as_str() == "global_wasm_action" {
3174                    match mgr_act.dispatch_wasm_event(&WasmDynamicScope::Global, 1) {
3175                        Ok(next_st) => {
3176                            let _: bool = wasm_status.set(format!(
3177                                "Global WASM euv_on_event executed live -> state={next_st} (full shell re-rendered)"
3178                            ));
3179                        }
3180                        Err(err) => {
3181                            let _: bool =
3182                                wasm_status.set(format!("Global WASM event error: {err}"));
3183                        }
3184                    }
3185                } else if ui_event.get_action().as_str() == "global_wasm_rollback" {
3186                    match mgr_act.rollback_global("user rollback") {
3187                        Ok(ver) => {
3188                            let _: bool = wasm_status.set(format!(
3189                                "Rolled back Global WASM shell to v{ver} (0 = native shell)"
3190                            ));
3191                        }
3192                        Err(_) => {
3193                            mgr_act.restore_native_global();
3194                            let _: bool =
3195                                wasm_status.set(STATUS_RESTORED_NATIVE_SHELL.to_string());
3196                        }
3197                    }
3198                } else if ui_event.get_action().as_str() == "global_wasm_restore" {
3199                    mgr_act.restore_native_global();
3200                    let _: bool = wasm_status.set(STATUS_RESTORED_NATIVE_SHELL.to_string());
3201                }
3202            });
3203    }
3204
3205    /// Rebinds `hub` onto this state and updates `wasm_manager` and router integration.
3206    ///
3207    /// # Arguments
3208    ///
3209    /// - `&Self` - Mutable showcase state.
3210    /// - `DynamicUpdateHub` - Shared dynamic update hub owned by `App`.
3211    pub fn attach_dynamic_hub(&mut self, hub: DynamicUpdateHub) {
3212        let wasm_mgr: WasmDynamicManager = WasmDynamicManager::new(
3213            hub.clone(),
3214            Rc::new(self.get_wasm_registry().clone()),
3215            WasmSandboxConfig::default(),
3216        );
3217        let Self {
3218            dynamic_hub,
3219            wasm_manager,
3220            router,
3221            ..
3222        } = self;
3223        let _: EuvRouter = router.clone().with_dynamic_hub(hub.clone());
3224        *dynamic_hub = hub;
3225        *wasm_manager = wasm_mgr;
3226        self.wire_dynamic_hub_actions();
3227    }
3228
3229    /// Builds `AiAppHooks` bridging route, theme, and 3D/2D game engine telemetry and controls to AI Schema v1 without eagerly allocating `/game3d` signals.
3230    ///
3231    /// # Arguments
3232    ///
3233    /// - `&Self` - Reactive showcase state reference.
3234    ///
3235    /// # Returns
3236    ///
3237    /// - `AiAppHooks` - Configured AI automation hooks bound to this state.
3238    #[cfg(any(debug_assertions, test))]
3239    #[must_use]
3240    pub fn build_ai_hooks(&self) -> AiAppHooks {
3241        let route_get: Signal<String> = self.get_route();
3242        let route_set: Signal<String> = self.get_route();
3243        let theme_get: UiThemeState = self.get_theme().clone();
3244        let theme_set: UiThemeState = self.get_theme().clone();
3245        let e3d_stats_cell: Rc<Cell<Option<Engine3dSignals>>> = self.get_engine3d_signals().clone();
3246        let e3d_ctrl_cell: Rc<Cell<Option<Engine3dSignals>>> = self.get_engine3d_signals().clone();
3247        let owner_scope: Scope = self.get_state_scope();
3248        AiAppHooks::new()
3249            .on_route(move || route_get.get_untracked())
3250            .on_scheme(move || theme_get.get_scheme().get_untracked().as_str().to_string())
3251            .on_game_stats(move || {
3252                let green_val: Engine3dSignals =
3253                    Engine3dSignals::get_or_init(e3d_stats_cell.as_ref(), owner_scope);
3254                let raw: String = format!(
3255                    "{{\"preset_idx\":{},\"rt_idx\":{},\"resolution_scale_pct\":{:.1},\"time_of_day\":{:.2},\"camera_mode\":{},\"import_status\":{:?}}}",
3256                    green_val.get_engine3d_preset_idx().get_untracked(),
3257                    green_val.get_engine3d_rt_idx().get_untracked(),
3258                    green_val.get_engine3d_res_scale().get_untracked(),
3259                    green_val.get_engine3d_time_of_day().get_untracked(),
3260                    green_val.get_engine3d_camera_mode().get_untracked(),
3261                    green_val.get_engine3d_import_status().get_untracked()
3262                );
3263                AiSchemaProtocol::parse_json_value(&raw)
3264            })
3265            .on_navigate(move |target: &str| {
3266                let _: bool = route_set.set_if_changed(target.to_string());
3267                Ok(())
3268            })
3269            .on_set_theme(move |scheme_opt: Option<&str>, mode_opt: Option<&str>| {
3270                if let Some(s_name) = scheme_opt {
3271                    let matched: Option<DesignScheme> = DesignScheme::all()
3272                        .into_iter()
3273                        .find(|ds: &DesignScheme| ds.as_str().eq_ignore_ascii_case(s_name));
3274                    match matched {
3275                        Some(ds) => theme_set.select_scheme(ds),
3276                        None => return Err(format!("Unknown design scheme: {s_name}")),
3277                    }
3278                }
3279                if let Some(m_name) = mode_opt {
3280                    let next_mode: ThemeMode = if m_name.eq_ignore_ascii_case("Dark") {
3281                        ThemeMode::Dark
3282                    } else if m_name.eq_ignore_ascii_case("Light") {
3283                        ThemeMode::Light
3284                    } else {
3285                        return Err(format!("Unknown theme mode: {m_name}"));
3286                    };
3287                    let _: bool = theme_set.get_mode().set_if_changed(next_mode);
3288                }
3289                Ok(())
3290            })
3291            .on_game_control(move |cmd: &str, payload: &Value| {
3292                let geometry_val: Engine3dSignals =
3293                    Engine3dSignals::get_or_init(e3d_ctrl_cell.as_ref(), owner_scope);
3294                let num_val: f64 = payload
3295                    .as_f64()
3296                    .or_else(|| payload.get("value").and_then(|item_val: &Value| item_val.as_f64()))
3297                    .unwrap_or(0.0);
3298                match cmd {
3299                    "camera_mode" => {
3300                        let next_cam: u8 = (num_val.round() as u8).min(3);
3301                        let _: bool = geometry_val.get_engine3d_camera_mode().set_if_changed(next_cam);
3302                        Ok(AiSchemaProtocol::parse_json_value(&format!(
3303                            "{{\"camera_mode\":{next_cam}}}"
3304                        )))
3305                    }
3306                    "preset" => {
3307                        let next_p: usize = (num_val.round() as usize).min(4);
3308                        let _: bool = geometry_val.get_engine3d_preset_idx().set_if_changed(next_p);
3309                        Ok(AiSchemaProtocol::parse_json_value(&format!(
3310                            "{{\"preset_idx\":{next_p}}}"
3311                        )))
3312                    }
3313                    "ray_tracing" => {
3314                        let next_rt: usize = (num_val.round() as usize).min(3);
3315                        let _: bool = geometry_val.get_engine3d_rt_idx().set_if_changed(next_rt);
3316                        Ok(AiSchemaProtocol::parse_json_value(&format!(
3317                            "{{\"rt_idx\":{next_rt}}}"
3318                        )))
3319                    }
3320                    "resolution_scale" => {
3321                        let next_s: f32 = (num_val as f32).clamp(40.0, 125.0);
3322                        let _: bool = geometry_val.get_engine3d_res_scale().set_if_changed(next_s);
3323                        Ok(AiSchemaProtocol::parse_json_value(&format!(
3324                            "{{\"resolution_scale_pct\":{next_s:.1}}}"
3325                        )))
3326                    }
3327                    "time_of_day" => {
3328                        let next_t: f32 = (num_val as f32).clamp(6.0, 23.0);
3329                        let _: bool = geometry_val.get_engine3d_time_of_day().set_if_changed(next_t);
3330                        Ok(AiSchemaProtocol::parse_json_value(&format!(
3331                            "{{\"time_of_day\":{next_t:.2}}}"
3332                        )))
3333                    }
3334                    "import_model" => {
3335                        let next_q: u64 = geometry_val
3336                            .get_engine3d_import_queue()
3337                            .get_untracked()
3338                            .saturating_add(1);
3339                        let _: bool = geometry_val.get_engine3d_import_queue().set_if_changed(next_q);
3340                        Ok(AiSchemaProtocol::parse_json_value(&format!(
3341                            "{{\"import_queue\":{next_q}}}"
3342                        )))
3343                    }
3344                    other => Err(format!("Unknown game control command: {other}")),
3345                }
3346            })
3347            .on_set_config({
3348                let node_style: ShowcaseState = self.clone();
3349                move |key: &str, value: &Value| {
3350                    let as_bool = |tex_v: &Value| -> Result<bool, String> {
3351                        tex_v.as_bool()
3352                            .ok_or_else(|| format!("Config key '{key}' expects a boolean value"))
3353                    };
3354                    let as_usize = |bary_v: &Value| -> Result<usize, String> {
3355                        bary_v.as_u64()
3356                            .map(|item_count: u64| item_count as usize)
3357                            .ok_or_else(|| format!("Config key '{key}' expects an unsigned integer"))
3358                    };
3359                    let as_f32 = |sample_val: &Value| -> Result<f32, String> {
3360                        sample_val.as_f64()
3361                            .map(|node_entry: f64| node_entry as f32)
3362                            .ok_or_else(|| format!("Config key '{key}' expects a numeric value"))
3363                    };
3364                    match key {
3365                        "route" => {
3366                            let target: &str = value.as_str().ok_or_else(|| {
3367                                "Config key 'route' expects a string path".to_string()
3368                            })?;
3369                            let _: bool = node_style.get_route().set_if_changed(target.to_string());
3370                            Ok(Value::String(target.to_string()))
3371                        }
3372                        "theme.scheme" => {
3373                            let s_name: &str = value.as_str().ok_or_else(|| {
3374                                "Config key 'theme.scheme' expects a string".to_string()
3375                            })?;
3376                            let matched: Option<DesignScheme> = DesignScheme::all()
3377                                .into_iter()
3378                                .find(|ds: &DesignScheme| ds.as_str().eq_ignore_ascii_case(s_name));
3379                            match matched {
3380                                Some(ds) => {
3381                                    node_style.get_theme().select_scheme(ds);
3382                                    Ok(Value::String(ds.as_str().to_string()))
3383                                }
3384                                None => Err(format!("Unknown design scheme: {s_name}")),
3385                            }
3386                        }
3387                        "theme.mode" => {
3388                            let m_name: &str = value.as_str().ok_or_else(|| {
3389                                "Config key 'theme.mode' expects 'Light' or 'Dark'".to_string()
3390                            })?;
3391                            let next_mode: ThemeMode = if m_name.eq_ignore_ascii_case("Dark") {
3392                                ThemeMode::Dark
3393                            } else if m_name.eq_ignore_ascii_case("Light") {
3394                                ThemeMode::Light
3395                            } else {
3396                                return Err(format!("Unknown theme mode: {m_name}"));
3397                            };
3398                            let _: bool = node_style.get_theme().get_mode().set_if_changed(next_mode);
3399                            Ok(Value::String(
3400                                if next_mode == ThemeMode::Dark {
3401                                    "Dark"
3402                                } else {
3403                                    "Light"
3404                                }
3405                                .to_string(),
3406                            ))
3407                        }
3408                        "shell.auto_hide_chrome" => {
3409                            let flag_value: bool = as_bool(value)?;
3410                            let _: bool = node_style.get_auto_hide_chrome().set_if_changed(flag_value);
3411                            Ok(Value::Bool(flag_value))
3412                        }
3413                        "shell.show_fps_hud" => {
3414                            let is_matched: bool = as_bool(value)?;
3415                            let _: bool = node_style.get_show_fps_hud().set_if_changed(is_matched);
3416                            Ok(Value::Bool(is_matched))
3417                        }
3418                        "shell.swipe_routing" => {
3419                            let blue_val: bool = as_bool(value)?;
3420                            let _: bool = node_style.get_swipe_routing().set_if_changed(blue_val);
3421                            Ok(Value::Bool(blue_val))
3422                        }
3423                        "shell.reduced_motion" => {
3424                            let byte_val: bool = as_bool(value)?;
3425                            let _: bool = node_style.get_reduced_motion().set_if_changed(byte_val);
3426                            Ok(Value::Bool(byte_val))
3427                        }
3428                        "shell.cmd_palette_open" => {
3429                            let bounds_val: bool = as_bool(value)?;
3430                            let _: bool = node_style.get_cmd_palette_open().set_if_changed(bounds_val);
3431                            Ok(Value::Bool(bounds_val))
3432                        }
3433                        "render.adaptive_auto_switch" => {
3434                            let second_val: bool = as_bool(value)?;
3435                            let _: bool = node_style.get_adaptive_auto_switch().set_if_changed(second_val);
3436                            Ok(Value::Bool(second_val))
3437                        }
3438                        "render.mode_index" => {
3439                            let idx: usize = if let Some(source_val) = value.as_str() {
3440                                if source_val.eq_ignore_ascii_case("Software") {
3441                                    1
3442                                } else if source_val.eq_ignore_ascii_case("Hardware") {
3443                                    2
3444                                } else if source_val.eq_ignore_ascii_case("Hybrid") {
3445                                    3
3446                                } else {
3447                                    0
3448                                }
3449                            } else {
3450                                as_usize(value)?.min(3)
3451                            };
3452                            let _: bool = node_style.get_render_mode_index().set_if_changed(idx);
3453                            Ok(Value::from(idx as u64))
3454                        }
3455                        "window.fullscreen" => {
3456                            let flag_value_primary: bool = as_bool(value)?;
3457                            let _: bool = node_style.get_fullscreen().set_if_changed(flag_value_primary);
3458                            Ok(Value::Bool(flag_value_primary))
3459                        }
3460                        "window.demo_fps_cap_index" => {
3461                            let idx: usize = as_usize(value)?.min(6);
3462                            let _: bool = node_style.get_demo_fps_cap_index().set_if_changed(idx);
3463                            Ok(Value::from(idx as u64))
3464                        }
3465                        "markdown.selectable" => {
3466                            let flag_value_secondary: bool = as_bool(value)?;
3467                            let _: bool = node_style.get_markdown_selectable().set_if_changed(flag_value_secondary);
3468                            Ok(Value::Bool(flag_value_secondary))
3469                        }
3470                        "markdown.lang_tab" => {
3471                            let idx: usize = as_usize(value)?.min(3);
3472                            let _: bool = node_style.get_markdown_lang_tab().set_if_changed(idx);
3473                            Ok(Value::from(idx as u64))
3474                        }
3475                        "charts.category_idx" => {
3476                            let idx: usize = as_usize(value)?.min(5);
3477                            let _: bool = node_style.get_charts_category_idx().set_if_changed(idx);
3478                            Ok(Value::from(idx as u64))
3479                        }
3480                        "lab.rtl" => {
3481                            let flag_value_next: bool = as_bool(value)?;
3482                            let _: bool = node_style.get_lab_rtl_mode().set_if_changed(flag_value_next);
3483                            Ok(Value::Bool(flag_value_next))
3484                        }
3485                        "lab.block_scroll_chain" => {
3486                            let flag_value_alt: bool = as_bool(value)?;
3487                            let _: bool = node_style.get_lab_block_scroll_chain().set_if_changed(flag_value_alt);
3488                            Ok(Value::Bool(flag_value_alt))
3489                        }
3490                        "lab.stop_click_bubble" => {
3491                            let flag_value_inner: bool = as_bool(value)?;
3492                            let _: bool = node_style.get_lab_stop_click_bubble().set_if_changed(flag_value_inner);
3493                            Ok(Value::Bool(flag_value_inner))
3494                        }
3495                        "overlays.modal_open" => {
3496                            let flag_value_local: bool = as_bool(value)?;
3497                            let _: bool = node_style.get_modal_open().set_if_changed(flag_value_local);
3498                            Ok(Value::Bool(flag_value_local))
3499                        }
3500                        "overlays.drawer_open" => {
3501                            let flag_value_cur: bool = as_bool(value)?;
3502                            let _: bool = node_style.get_drawer_open().set_if_changed(flag_value_cur);
3503                            Ok(Value::Bool(flag_value_cur))
3504                        }
3505                        "overlays.sheet_open" => {
3506                            let flag_value_slot: bool = as_bool(value)?;
3507                            let _: bool = node_style.get_sheet_open().set_if_changed(flag_value_slot);
3508                            Ok(Value::Bool(flag_value_slot))
3509                        }
3510                        "overlays.popover_open" => {
3511                            let flag_value_2: bool = as_bool(value)?;
3512                            let _: bool = node_style.get_popover_open().set_if_changed(flag_value_2);
3513                            Ok(Value::Bool(flag_value_2))
3514                        }
3515                        "overlays.toast_visible" => {
3516                            let flag_value_3: bool = as_bool(value)?;
3517                            let _: bool = node_style.get_toast_visible().set_if_changed(flag_value_3);
3518                            Ok(Value::Bool(flag_value_3))
3519                        }
3520                        "overlays.loading_active" => {
3521                            let flag_value_4: bool = as_bool(value)?;
3522                            let _: bool = node_style.get_loading_active().set_if_changed(flag_value_4);
3523                            Ok(Value::Bool(flag_value_4))
3524                        }
3525                        "water.fill_pct" => {
3526                            let pct: f32 = as_f32(value)?.clamp(25.0, 80.0);
3527                            let _: bool = node_style.get_water_fill_pct().set_if_changed(pct);
3528                            Ok(Value::from(pct))
3529                        }
3530                        "water.viscosity_idx" => {
3531                            let idx: usize = as_usize(value)?.min(2);
3532                            let _: bool = node_style.get_water_viscosity_idx().set_if_changed(idx);
3533                            Ok(Value::from(idx as u64))
3534                        }
3535                        "water.buoyant_enabled" => {
3536                            let flag_value_5: bool = as_bool(value)?;
3537                            let _: bool = node_style.get_water_buoyant_enabled().set_if_changed(flag_value_5);
3538                            Ok(Value::Bool(flag_value_5))
3539                        }
3540                        "engine3d.preset_idx" => {
3541                            let idx: usize = as_usize(value)?.min(4);
3542                            let _: bool = node_style.get_engine3d_preset_idx().set_if_changed(idx);
3543                            Ok(Value::from(idx as u64))
3544                        }
3545                        "engine3d.rt_idx" => {
3546                            let idx: usize = as_usize(value)?.min(3);
3547                            let _: bool = node_style.get_engine3d_rt_idx().set_if_changed(idx);
3548                            Ok(Value::from(idx as u64))
3549                        }
3550                        "engine3d.res_scale" => {
3551                            let scale: f32 = as_f32(value)?.clamp(40.0, 125.0);
3552                            let _: bool = node_style.get_engine3d_res_scale().set_if_changed(scale);
3553                            Ok(Value::from(scale))
3554                        }
3555                        "engine3d.time_of_day" => {
3556                            let tod: f32 = as_f32(value)?.clamp(6.0, 23.0);
3557                            let _: bool = node_style.get_engine3d_time_of_day().set_if_changed(tod);
3558                            Ok(Value::from(tod))
3559                        }
3560                        "engine3d.camera_mode" => {
3561                            let mode: u8 = (as_usize(value)? as u8).min(3);
3562                            let _: bool = node_style.get_engine3d_camera_mode().set_if_changed(mode);
3563                            Ok(Value::from(mode))
3564                        }
3565                        "reset_defaults" => {
3566                            let flag_value_6: bool = as_bool(value)?;
3567                            if flag_value_6 {
3568                                node_style.reset_preferences_to_defaults();
3569                            }
3570                            Ok(Value::Bool(flag_value_6))
3571                        }
3572                        other => Err(format!("Unknown showcase config key: {other}")),
3573                    }
3574                }
3575            })
3576            .on_get_config({
3577                let active_style: ShowcaseState = self.clone();
3578                move |_keys: &[String]| {
3579                    let mode_str: &str = if active_style.get_theme().get_mode().get_untracked()
3580                        == ThemeMode::Dark
3581                    {
3582                        "Dark"
3583                    } else {
3584                        "Light"
3585                    };
3586                    let mut parts: Vec<String> = vec![
3587                        format!("\"route\":{:?}", active_style.get_route().get_untracked()),
3588                        format!(
3589                            "\"theme.scheme\":{:?}",
3590                            active_style.get_theme().get_scheme().get_untracked().as_str()
3591                        ),
3592                        format!("\"theme.mode\":{:?}", mode_str),
3593                        format!(
3594                            "\"shell.auto_hide_chrome\":{}",
3595                            active_style.get_auto_hide_chrome().get_untracked()
3596                        ),
3597                        format!(
3598                            "\"shell.show_fps_hud\":{}",
3599                            active_style.get_show_fps_hud().get_untracked()
3600                        ),
3601                        format!(
3602                            "\"shell.swipe_routing\":{}",
3603                            active_style.get_swipe_routing().get_untracked()
3604                        ),
3605                        format!(
3606                            "\"shell.reduced_motion\":{}",
3607                            active_style.get_reduced_motion().get_untracked()
3608                        ),
3609                        format!(
3610                            "\"shell.cmd_palette_open\":{}",
3611                            active_style.get_cmd_palette_open().get_untracked()
3612                        ),
3613                        format!(
3614                            "\"render.adaptive_auto_switch\":{}",
3615                            active_style.get_adaptive_auto_switch().get_untracked()
3616                        ),
3617                    ];
3618                    if let Some(rw) = active_style.get_render_window_signals().get() {
3619                        parts.push(format!(
3620                            "\"render.mode_index\":{}",
3621                            rw.get_render_mode_index().get_untracked()
3622                        ));
3623                        parts.push(format!(
3624                            "\"window.fullscreen\":{}",
3625                            rw.get_fullscreen().get_untracked()
3626                        ));
3627                        parts.push(format!(
3628                            "\"window.demo_fps_cap_index\":{}",
3629                            rw.get_demo_fps_cap_index().get_untracked()
3630                        ));
3631                    }
3632                    if let Some(md) = active_style.get_markdown_signals().get() {
3633                        parts.push(format!(
3634                            "\"markdown.selectable\":{}",
3635                            md.get_markdown_selectable().get_untracked()
3636                        ));
3637                        parts.push(format!(
3638                            "\"markdown.lang_tab\":{}",
3639                            md.get_markdown_lang_tab().get_untracked()
3640                        ));
3641                    }
3642                    if let Some(ch) = active_style.get_charts_signals().get() {
3643                        parts.push(format!(
3644                            "\"charts.category_idx\":{}",
3645                            ch.get_charts_category_idx().get_untracked()
3646                        ));
3647                    }
3648                    if let Some(lab) = active_style.get_lab_signals().get() {
3649                        parts.push(format!(
3650                            "\"lab.rtl\":{}",
3651                            lab.get_lab_rtl_mode().get_untracked()
3652                        ));
3653                        parts.push(format!(
3654                            "\"lab.block_scroll_chain\":{}",
3655                            lab.get_lab_block_scroll_chain().get_untracked()
3656                        ));
3657                        parts.push(format!(
3658                            "\"lab.stop_click_bubble\":{}",
3659                            lab.get_lab_stop_click_bubble().get_untracked()
3660                        ));
3661                    }
3662                    if let Some(overflow_mode) = active_style.get_overlays_signals().get() {
3663                        parts.push(format!(
3664                            "\"overlays.modal_open\":{}",
3665                            overflow_mode.get_modal_open().get_untracked()
3666                        ));
3667                        parts.push(format!(
3668                            "\"overlays.drawer_open\":{}",
3669                            overflow_mode.get_drawer_open().get_untracked()
3670                        ));
3671                        parts.push(format!(
3672                            "\"overlays.sheet_open\":{}",
3673                            overflow_mode.get_sheet_open().get_untracked()
3674                        ));
3675                    }
3676                    if let Some(width_val) = active_style.get_water_signals().get() {
3677                        parts.push(format!(
3678                            "\"water.fill_pct\":{:.1}",
3679                            width_val.get_fill_pct().get_untracked()
3680                        ));
3681                        parts.push(format!(
3682                            "\"water.viscosity_idx\":{}",
3683                            width_val.get_viscosity_idx().get_untracked()
3684                        ));
3685                        parts.push(format!(
3686                            "\"water.buoyant_enabled\":{}",
3687                            width_val.get_buoyant_enabled().get_untracked()
3688                        ));
3689                    }
3690                    if let Some(e3d) = active_style.get_engine3d_signals().get() {
3691                        parts.push(format!(
3692                            "\"engine3d.preset_idx\":{}",
3693                            e3d.get_engine3d_preset_idx().get_untracked()
3694                        ));
3695                        parts.push(format!(
3696                            "\"engine3d.rt_idx\":{}",
3697                            e3d.get_engine3d_rt_idx().get_untracked()
3698                        ));
3699                        parts.push(format!(
3700                            "\"engine3d.res_scale\":{:.1}",
3701                            e3d.get_engine3d_res_scale().get_untracked()
3702                        ));
3703                        parts.push(format!(
3704                            "\"engine3d.time_of_day\":{:.2}",
3705                            e3d.get_engine3d_time_of_day().get_untracked()
3706                        ));
3707                        parts.push(format!(
3708                            "\"engine3d.camera_mode\":{}",
3709                            e3d.get_engine3d_camera_mode().get_untracked()
3710                        ));
3711                    }
3712                    AiSchemaProtocol::parse_json_value(&format!("{{{}}}", parts.join(",")))
3713                }
3714            })
3715    }
3716
3717    /// Returns the categorized sidebar navigation items grouped in Linear/Vercel/shadcn hierarchy.
3718    ///
3719    /// # Returns
3720    ///
3721    /// - `Vec<EuvNavItem>` - Categorized list of showcase routes.
3722    #[must_use]
3723    pub fn nav_items() -> Vec<EuvNavItem> {
3724        SHOWCASE_ROUTES
3725            .iter()
3726            .map(|spec: &ShowcaseRouteSpec| {
3727                EuvNavItem::new(spec.get_path().to_string(), spec.get_label().to_string())
3728                    .section(spec.get_section())
3729            })
3730            .collect()
3731    }
3732
3733    /// Resolves the currently selected component-scoped demo `RenderMode` from `render_mode_index`.
3734    ///
3735    /// # Arguments
3736    ///
3737    /// - `&Self` - State reference.
3738    ///
3739    /// # Returns
3740    ///
3741    /// - `RenderMode` - Component-scoped demo render pipeline mode.
3742    #[must_use]
3743    pub fn selected_render_mode(&self) -> RenderMode {
3744        match self.get_render_mode_index().get_untracked() {
3745            1 => RenderMode::Software,
3746            2 => RenderMode::Hardware,
3747            3 => RenderMode::Hybrid,
3748            _ => RenderMode::Auto,
3749        }
3750    }
3751
3752    /// Resolves the currently selected component-scoped demo FPS cap from `demo_fps_cap_index`.
3753    ///
3754    /// # Arguments
3755    ///
3756    /// - `&Self` - State reference.
3757    ///
3758    /// # Returns
3759    ///
3760    /// - `Option<u32>` - Demo card FPS target (`None` = Native Uncapped).
3761    #[must_use]
3762    pub fn selected_demo_fps_cap(&self) -> Option<u32> {
3763        match self.get_demo_fps_cap_index().get_untracked() {
3764            1 => Some(30),
3765            2 => Some(60),
3766            3 => Some(120),
3767            4 => Some(144),
3768            5 => Some(240),
3769            6 => Some(360),
3770            _ => None,
3771        }
3772    }
3773
3774    /// Cycles to the next `DesignScheme` in `DesignScheme::all()`.
3775    ///
3776    /// # Arguments
3777    ///
3778    /// - `&Self` - State reference.
3779    pub fn next_scheme(&self) {
3780        let all: [DesignScheme; 17] = DesignScheme::all();
3781        let current: DesignScheme = self.get_theme().get_scheme().get_untracked();
3782        let pos: usize = all
3783            .iter()
3784            .position(|source_val: &DesignScheme| *source_val == current)
3785            .unwrap_or(0);
3786        let next: DesignScheme = all[(pos + 1) % all.len()];
3787        let _: bool = self.get_theme().get_scheme().set_if_changed(next);
3788    }
3789
3790    /// Toggles between light and dark theme modes.
3791    ///
3792    /// # Arguments
3793    ///
3794    /// - `&Self` - State reference.
3795    pub fn toggle_theme_mode(&self) {
3796        let cur: ThemeMode = self.get_theme().get_mode().get_untracked();
3797        let next: ThemeMode = match cur {
3798            ThemeMode::Light => ThemeMode::Dark,
3799            ThemeMode::Dark => ThemeMode::Light,
3800        };
3801        let _: bool = self.get_theme().get_mode().set_if_changed(next);
3802    }
3803
3804    /// Snapshots active running/playing state across all 15 showcase pages and freezes 2D/3D engines and media players for background.
3805    ///
3806    /// # Arguments
3807    ///
3808    /// - `&Self` - State reference.
3809    pub fn freeze_for_background(&self) {
3810        if self.get_bg_frozen().get_untracked() {
3811            return;
3812        }
3813        let game2d_running: bool = !self.get_game_host().is_paused();
3814        self.get_bg_snap_game2d_running().set(game2d_running);
3815        self.get_game_host().set_paused(true);
3816        let game3d_running: bool = !self.get_game3d_host().is_paused();
3817        self.get_bg_snap_game3d_running().set(game3d_running);
3818        self.get_game3d_host().set_paused(true);
3819        let water_running: bool = !self.get_water_host().is_paused();
3820        self.get_bg_snap_water_running().set(water_running);
3821        self.get_water_host().set_paused(true);
3822        if self.get_media_loaded().get() {
3823            let gif_playing: bool = self.get_media_gif().get_untracked().get_playing();
3824            self.get_bg_snap_gif_playing().set(gif_playing);
3825            if gif_playing {
3826                let _: bool = {
3827                    if let Some(mut updated_value) = (self.get_media_gif()).try_get_untracked() {
3828                        {
3829                            let gif: &mut GifAnimation = &mut updated_value;
3830                            gif.set_playing(false);
3831                        }
3832                        (self.get_media_gif()).set(updated_value)
3833                    } else {
3834                        false
3835                    }
3836                };
3837            }
3838            let live_playing: bool = self.get_media_live().get_untracked().get_active_motion();
3839            self.get_bg_snap_live_playing().set(live_playing);
3840            if live_playing {
3841                let _: bool = {
3842                    if let Some(mut updated_value) = (self.get_media_live()).try_get_untracked() {
3843                        {
3844                            let live: &mut LivePhotoAsset = &mut updated_value;
3845                            live.set_motion_playing(false);
3846                        }
3847                        (self.get_media_live()).set(updated_value)
3848                    } else {
3849                        false
3850                    }
3851                };
3852            }
3853            let video_playing: bool =
3854                self.get_media_video().get_untracked().get_state() == PlaybackState::Playing;
3855            self.get_bg_snap_video_playing().set(video_playing);
3856            if video_playing {
3857                let _: bool = {
3858                    if let Some(mut updated_value) = (self.get_media_video()).try_get_untracked() {
3859                        {
3860                            let video: &mut VideoTrack = &mut updated_value;
3861                            video.set_state(PlaybackState::Paused);
3862                        }
3863                        (self.get_media_video()).set(updated_value)
3864                    } else {
3865                        false
3866                    }
3867                };
3868            }
3869            let audio_playing: bool =
3870                self.get_media_audio().get_untracked().get_state() == PlaybackState::Playing;
3871            self.get_bg_snap_audio_playing().set(audio_playing);
3872            if audio_playing {
3873                let _: bool = {
3874                    if let Some(mut updated_value) = (self.get_media_audio()).try_get_untracked() {
3875                        {
3876                            let audio: &mut AudioTrack = &mut updated_value;
3877                            audio.set_state(PlaybackState::Paused);
3878                        }
3879                        (self.get_media_audio()).set(updated_value)
3880                    } else {
3881                        false
3882                    }
3883                };
3884            }
3885        }
3886        let _: bool = self.get_bg_frozen().set_if_changed(true);
3887        let _: bool = {
3888            if let Some(mut updated_value) = (self.get_bg_freeze_count()).try_get_untracked() {
3889                {
3890                    let count: &mut u32 = &mut updated_value;
3891                    *count = count.saturating_add(1);
3892                }
3893                (self.get_bg_freeze_count()).set(updated_value)
3894            } else {
3895                false
3896            }
3897        };
3898    }
3899
3900    /// Restores the exact pre-background running/playing flags across all showcase game hosts and media players on foreground return.
3901    ///
3902    /// # Arguments
3903    ///
3904    /// - `&Self` - State reference.
3905    pub fn restore_from_foreground(&self) {
3906        if !self.get_bg_frozen().get_untracked() {
3907            return;
3908        }
3909        let active_route: String = self.get_route().get_untracked();
3910        if self.get_bg_snap_game2d_running().replace(false) && active_route == ROUTE_GAME {
3911            self.get_game_host().set_paused(false);
3912        }
3913        if self.get_bg_snap_game3d_running().replace(false) && active_route == ROUTE_GAME_3D {
3914            self.get_game3d_host().set_paused(false);
3915        }
3916        if self.get_bg_snap_water_running().replace(false) && active_route == ROUTE_WATER {
3917            self.get_water_host().set_paused(false);
3918        }
3919        if self.get_bg_snap_gif_playing().replace(false) {
3920            let _: bool = {
3921                if let Some(mut updated_value) = (self.get_media_gif()).try_get_untracked() {
3922                    {
3923                        let gif: &mut GifAnimation = &mut updated_value;
3924                        gif.set_playing(true);
3925                    }
3926                    (self.get_media_gif()).set(updated_value)
3927                } else {
3928                    false
3929                }
3930            };
3931        }
3932        if self.get_bg_snap_live_playing().replace(false) {
3933            let _: bool = {
3934                if let Some(mut updated_value) = (self.get_media_live()).try_get_untracked() {
3935                    {
3936                        let live: &mut LivePhotoAsset = &mut updated_value;
3937                        live.set_motion_playing(true);
3938                    }
3939                    (self.get_media_live()).set(updated_value)
3940                } else {
3941                    false
3942                }
3943            };
3944        }
3945        if self.get_bg_snap_video_playing().replace(false) {
3946            let _: bool = {
3947                if let Some(mut updated_value) = (self.get_media_video()).try_get_untracked() {
3948                    {
3949                        let video: &mut VideoTrack = &mut updated_value;
3950                        video.set_state(PlaybackState::Playing);
3951                    }
3952                    (self.get_media_video()).set(updated_value)
3953                } else {
3954                    false
3955                }
3956            };
3957        }
3958        if self.get_bg_snap_audio_playing().replace(false) {
3959            let _: bool = {
3960                if let Some(mut updated_value) = (self.get_media_audio()).try_get_untracked() {
3961                    {
3962                        let audio: &mut AudioTrack = &mut updated_value;
3963                        audio.set_state(PlaybackState::Playing);
3964                    }
3965                    (self.get_media_audio()).set(updated_value)
3966                } else {
3967                    false
3968                }
3969            };
3970        }
3971        let _: bool = self.get_bg_frozen().set_if_changed(false);
3972        let _: bool = {
3973            if let Some(mut updated_value) = (self.get_bg_restore_count()).try_get_untracked() {
3974                {
3975                    let count: &mut u32 = &mut updated_value;
3976                    *count = count.saturating_add(1);
3977                }
3978                (self.get_bg_restore_count()).set(updated_value)
3979            } else {
3980                false
3981            }
3982        };
3983    }
3984}
3985
3986/// Default `ShowcaseState` delegating to `ShowcaseState::new`.
3987impl Default for ShowcaseState {
3988    /// Creates a default `ShowcaseState`.
3989    ///
3990    /// # Returns
3991    ///
3992    /// - `Self` - Initialized state.
3993    fn default() -> Self {
3994        Self::new()
3995    }
3996}
3997
3998/// Arena setup and gameplay helper methods for `DemoPhysicsScene`.
3999impl DemoPhysicsScene {
4000    /// Creates an empty zero-allocation 2D arena placeholder that hydrates lazily on first active tick or render.
4001    ///
4002    /// # Returns
4003    ///
4004    /// - `Self` - Uninitialized lazy arena placeholder.
4005    #[must_use]
4006    pub fn create_lazy_arena() -> Self {
4007        Self {
4008            world: GameWorld::default(),
4009            physics: PhysicsWorld2D::default(),
4010            camera: Camera2D::default(),
4011            particles: ParticleSystem::default(),
4012            tilemap: TileMap::empty(0, 0, 48.0),
4013            actions: ActionMap::default(),
4014            audio: AudioBus::default(),
4015            player_id: EntityId::default(),
4016            fire_cooldown: 0.0,
4017            dash_cooldown: 0.0,
4018            score: 0,
4019            wave: 1,
4020            show_colliders: false,
4021            smoothed_fps: 0.0,
4022            ticks: 0,
4023            viewport_size: Size::new(820.0, 340.0),
4024            initialized: false,
4025            snapshots: DoubleBufferedSnapshot::new(World2DSnapshot::default()),
4026            to_despawn_scratch: Vec::new(),
4027            last_sampled_tick: u64::MAX,
4028            last_sampled_alpha_milli: i32::MIN,
4029            cached_interp: None,
4030            shockwaves: [(0.0, 0.0, 0.0, 0.0); 8],
4031        }
4032    }
4033
4034    /// Hydrates the full 2D arena tilemap, entities, and particle pool once on first active simulation or render.
4035    ///
4036    /// # Arguments
4037    ///
4038    /// - `&Self` - Mutable arena scene.
4039    fn ensure_initialized(&mut self) {
4040        if self.get_initialized() {
4041            return;
4042        }
4043        *self = Self::create_arena();
4044    }
4045
4046    /// Builds a playable 1280x720 tiled neon arena with player ship, obstacles, and initial enemy wave.
4047    ///
4048    /// # Returns
4049    ///
4050    /// - `Self` - Initialized playable arena scene.
4051    #[must_use]
4052    pub fn create_arena() -> Self {
4053        let mut tilemap: TileMap = TileMap::empty(24, 14, 48.0);
4054        let floor_a: u16 = tilemap.add_palette_entry(TilePaletteEntry::new(
4055            Color::hex(0x0B1120),
4056            Color::rgba(30, 41, 59, 90),
4057            false,
4058        ));
4059        let floor_b: u16 = tilemap.add_palette_entry(TilePaletteEntry::new(
4060            Color::hex(0x0F172A),
4061            Color::rgba(30, 41, 59, 90),
4062            false,
4063        ));
4064        let wall_tile: u16 = tilemap.add_palette_entry(TilePaletteEntry::new(
4065            Color::hex(0x1E293B),
4066            Color::hex(0x38BDF8),
4067            true,
4068        ));
4069        for row in 0..tilemap.get_rows() {
4070            for col in 0..tilemap.get_columns() {
4071                let is_border: bool = row == 0
4072                    || col == 0
4073                    || row + 1 == tilemap.get_rows()
4074                    || col + 1 == tilemap.get_columns();
4075                let tid: u16 = if is_border {
4076                    wall_tile
4077                } else if (row + col) % 2 == 0 {
4078                    floor_a
4079                } else {
4080                    floor_b
4081                };
4082                tilemap.set_tile(col, row, tid);
4083            }
4084        }
4085        let world_rect: Rect = tilemap.world_bounds();
4086        let inner_arena: Rect = Rect::new(
4087            78.0,
4088            78.0,
4089            (world_rect.get_width() - 156.0).max(200.0),
4090            (world_rect.get_height() - 156.0).max(200.0),
4091        );
4092        let mut world: GameWorld = GameWorld::with_capacity(256);
4093        let center: Point = Point::new(world_rect.get_width() * 0.5, world_rect.get_height() * 0.5);
4094        let player_id: EntityId = world.spawn(EntityTag::Player, center);
4095        if let Some(player) = world.get_entity_mut(player_id) {
4096            player.set_body(Some(RigidBody2D::dynamic(1.0, 0.4, 3.2)));
4097            player.set_collider(Some(Collider2D::circle(
4098                14.0,
4099                COLLISION_LAYER_PLAYER,
4100                COLLISION_MASK_PLAYER_DEFAULT,
4101                false,
4102            )));
4103            player.set_sprite(Some(Sprite2D::new(
4104                EntityVisualShape::Triangle,
4105                Size::new(30.0, 26.0),
4106                Color::hex(0x38BDF8),
4107                Color::hex(0xE0F2FE),
4108                10,
4109                0.0,
4110                true,
4111            )));
4112        }
4113        let pillars: [(f32, f32); 4] = [
4114            (368.0, 224.0),
4115            (784.0, 224.0),
4116            (368.0, 448.0),
4117            (784.0, 448.0),
4118        ];
4119        for (px, py) in pillars.into_iter() {
4120            let pid: EntityId = world.spawn(EntityTag::Obstacle, Point::new(px, py));
4121            if let Some(obs) = world.get_entity_mut(pid) {
4122                obs.set_body(Some(RigidBody2D::static_body(0.85)));
4123                obs.set_collider(Some(Collider2D::axis_aligned_box(
4124                    52.0,
4125                    52.0,
4126                    COLLISION_LAYER_WORLD,
4127                    COLLISION_LAYER_ALL,
4128                    false,
4129                )));
4130                obs.set_sprite(Some(Sprite2D::new(
4131                    EntityVisualShape::Rect,
4132                    Size::new(52.0, 52.0),
4133                    Color::hex(0x1E293B),
4134                    Color::hex(0x6366F1),
4135                    2,
4136                    8.0,
4137                    true,
4138                )));
4139            }
4140        }
4141        let bumper_specs: [(f32, f32, f32, f32); 4] = [
4142            (464.0, 266.0, 58.0, -44.0),
4143            (688.0, 266.0, -52.0, 48.0),
4144            (464.0, 406.0, 46.0, 54.0),
4145            (688.0, 406.0, -60.0, -38.0),
4146        ];
4147        for (bx, by, bvx, bvy) in bumper_specs.into_iter() {
4148            let bid: EntityId = world.spawn(EntityTag::Pickup, Point::new(bx, by));
4149            if let Some(orb) = world.get_entity_mut(bid) {
4150                orb.set_velocity(Velocity2D::new(bvx, bvy, 2.2));
4151                orb.set_body(Some(RigidBody2D::dynamic(0.9, 0.98, 0.02)));
4152                orb.set_collider(Some(Collider2D::circle(
4153                    11.0,
4154                    COLLISION_LAYER_ENEMY,
4155                    COLLISION_LAYER_ALL,
4156                    false,
4157                )));
4158                orb.set_sprite(Some(Sprite2D::new(
4159                    EntityVisualShape::Circle,
4160                    Size::new(22.0, 22.0),
4161                    Color::hex(0xA855F7),
4162                    Color::hex(0xE9D5FF),
4163                    5,
4164                    0.0,
4165                    true,
4166                )));
4167            }
4168        }
4169        let mut phys_cfg: PhysicsConfig = PhysicsConfig::default();
4170        phys_cfg.set_arena_bounds(Some(inner_arena));
4171        let mut camera: Camera2D = Camera2D::at(center, 1.0);
4172        camera.set_world_bounds(Some(world_rect));
4173        let mut scene: Self = Self {
4174            world,
4175            physics: PhysicsWorld2D::with_config(phys_cfg),
4176            camera,
4177            particles: ParticleSystem::with_capacity(1024),
4178            tilemap,
4179            actions: ActionMap::default(),
4180            audio: AudioBus::default(),
4181            player_id,
4182            fire_cooldown: 0.0,
4183            dash_cooldown: 0.0,
4184            score: 0,
4185            wave: 1,
4186            show_colliders: false,
4187            smoothed_fps: 0.0,
4188            ticks: 0,
4189            viewport_size: Size::new(820.0, 340.0),
4190            initialized: true,
4191            snapshots: DoubleBufferedSnapshot::new(World2DSnapshot::default()),
4192            to_despawn_scratch: Vec::with_capacity(32),
4193            last_sampled_tick: u64::MAX,
4194            last_sampled_alpha_milli: i32::MIN,
4195            cached_interp: None,
4196            shockwaves: [(0.0, 0.0, 0.0, 0.0); 8],
4197        };
4198        scene.spawn_enemy_wave(8);
4199        let mut boot_glow: ParticleEmitterConfig = ParticleEmitterConfig::default();
4200        boot_glow
4201            .set_min_speed(18.0)
4202            .set_max_speed(72.0)
4203            .set_min_life(0.65)
4204            .set_max_life(1.45)
4205            .set_start_size(3.4)
4206            .set_start_color(Color::hex(0x38BDF8))
4207            .set_end_color(Color::rgba(168, 85, 247, 0));
4208        scene.get_mut_particles().emit_burst(center, 22, boot_glow);
4209        scene.push_shockwave(center, 14.0);
4210        let initial_snap: World2DSnapshot =
4211            World2DSnapshot::capture(scene.get_world(), scene.get_camera(), true, Vec::new());
4212        scene.set_snapshots(DoubleBufferedSnapshot::new(initial_snap));
4213        scene
4214    }
4215
4216    /// Registers an expanding radial neon shockwave ring at world position `origin` using the fixed-capacity ring pool.
4217    ///
4218    /// # Arguments
4219    ///
4220    /// - `Point` - World-space center of the shockwave ring.
4221    /// - `f32` - Initial ring radius in world pixels.
4222    fn push_shockwave(&mut self, origin: Point, initial_radius: f32) {
4223        let Self { shockwaves, .. } = self;
4224        let mut target_slot: usize = 0;
4225        let mut lowest_life: f32 = f32::INFINITY;
4226        for (slot_idx, slot) in shockwaves.iter().enumerate() {
4227            if slot.3 <= 0.001 {
4228                target_slot = slot_idx;
4229                break;
4230            }
4231            if slot.3 < lowest_life {
4232                lowest_life = slot.3;
4233                target_slot = slot_idx;
4234            }
4235        }
4236        shockwaves[target_slot] = (origin.get_x(), origin.get_y(), initial_radius, 1.0);
4237    }
4238
4239    /// Rotates a local offset `(local_x, local_y)` by `(cos_a, sin_a)` around screen `center`.
4240    ///
4241    /// # Arguments
4242    ///
4243    /// - `Point` - Screen-space center point.
4244    /// - `(f32, f32)` - Local offset `(local_x, local_y)` in screen pixels.
4245    /// - `(f32, f32)` - Precomputed `(cos_angle, sin_angle)`.
4246    ///
4247    /// # Returns
4248    ///
4249    /// - `Point` - Rotated screen-space point.
4250    #[must_use]
4251    fn rotate_screen_offset(center: Point, offset: (f32, f32), cs: (f32, f32)) -> Point {
4252        let (ox, oy): (f32, f32) = offset;
4253        let (ca, sa): (f32, f32) = cs;
4254        Point::new(
4255            center.get_x() + ox * ca - oy * sa,
4256            center.get_y() + ox * sa + oy * ca,
4257        )
4258    }
4259
4260    /// Renders the illuminated sci-fi tactical deck grid, parallax starfield, radar rings, and neon perimeter walls.
4261    ///
4262    /// # Arguments
4263    ///
4264    /// - `&mut GameRenderContext<'_>` - Active viewport draw surface.
4265    /// - `&Camera2D` - Interpolated arena camera.
4266    /// - `Size` - Viewport dimensions in logical pixels.
4267    /// - `f32` - Continuous arena clock in seconds for subtle pulsing energy conduits.
4268    fn render_tactical_arena_floor(
4269        &self,
4270        ctx: &mut GameRenderContext<'_>,
4271        cam: &Camera2D,
4272        size: Size,
4273        phase_secs: f32,
4274    ) {
4275        let world_rect: Rect = self.get_tilemap().world_bounds();
4276        let (cam_x, cam_y, zoom, half_w, half_h): (f32, f32, f32, f32, f32) =
4277            cam.projection_params(size);
4278        let vp_w: f32 = size.get_width();
4279        let vp_h: f32 = size.get_height();
4280        for star_idx in 0..28u32 {
4281            let hx: u32 = star_idx.wrapping_mul(73_856_093) ^ 0x5A17_9C3B;
4282            let hy: u32 = star_idx.wrapping_mul(19_349_663) ^ 0x3D91_4F27;
4283            let parallax: f32 = 0.22 + ((star_idx & 3) as f32) * 0.12;
4284            let raw_sx: f32 = ((hx & 0xFFFF) as f32 / 65535.0) * vp_w - cam_x * parallax * 0.25;
4285            let raw_sy: f32 = ((hy & 0xFFFF) as f32 / 65535.0) * vp_h - cam_y * parallax * 0.25;
4286            let sx: f32 = raw_sx.rem_euclid(vp_w.max(1.0));
4287            let sy: f32 = raw_sy.rem_euclid(vp_h.max(1.0));
4288            let star_rad: f32 = 0.9 + ((star_idx % 3) as f32) * 0.45;
4289            let twinkle: f32 = 0.55 + 0.45 * (phase_secs * 2.2 + (star_idx as f32)).sin();
4290            let star_alpha: u8 = ((38.0 + 48.0 * twinkle) as u8).min(110);
4291            let star_col: Color = if star_idx % 4 == 0 {
4292                Color::rgba(56, 189, 248, star_alpha)
4293            } else if star_idx % 4 == 1 {
4294                Color::rgba(168, 85, 247, star_alpha)
4295            } else {
4296                Color::rgba(203, 213, 225, star_alpha)
4297            };
4298            ctx.fill_circle(Point::new(sx, sy), star_rad, star_col);
4299        }
4300        let inner_x0: f32 = (48.0 - cam_x) * zoom + half_w;
4301        let inner_y0: f32 = (48.0 - cam_y) * zoom + half_h;
4302        let inner_w: f32 = (world_rect.get_width() - 96.0) * zoom;
4303        let inner_h: f32 = (world_rect.get_height() - 96.0) * zoom;
4304        ctx.fill_rounded_rect(
4305            Rect::new(inner_x0, inner_y0, inner_w, inner_h),
4306            Color::hex(0x060C1B),
4307            10.0 * zoom,
4308        );
4309        let center_pt: Point = Point::new(
4310            (world_rect.get_width() * 0.5 - cam_x) * zoom + half_w,
4311            (world_rect.get_height() * 0.5 - cam_y) * zoom + half_h,
4312        );
4313        let ring_segs: usize = 32;
4314        let ring_step: f32 = (2.0 * PI) / (ring_segs as f32);
4315        for &(ring_r_world, ring_col) in [
4316            (108.0_f32, Color::rgba(99, 102, 241, 34)),
4317            (196.0_f32, Color::rgba(56, 189, 248, 28)),
4318        ]
4319        .iter()
4320        {
4321            let rr: f32 = ring_r_world * zoom;
4322            for seg in 0..ring_segs {
4323                if seg % 4 == 3 {
4324                    continue;
4325                }
4326                let a0: f32 = (seg as f32) * ring_step;
4327                let a1: f32 = ((seg + 1) as f32) * ring_step;
4328                let p0: Point = Point::new(
4329                    center_pt.get_x() + a0.cos() * rr,
4330                    center_pt.get_y() + a0.sin() * rr,
4331                );
4332                let p1: Point = Point::new(
4333                    center_pt.get_x() + a1.cos() * rr,
4334                    center_pt.get_y() + a1.sin() * rr,
4335                );
4336                ctx.draw_line(p0, p1, 1.0, ring_col);
4337            }
4338        }
4339        let tick_in: f32 = 96.0 * zoom;
4340        let tick_out: f32 = 208.0 * zoom;
4341        for &(dx, dy) in [(1.0_f32, 0.0_f32), (-1.0, 0.0), (0.0, 1.0), (0.0, -1.0)].iter() {
4342            ctx.draw_line(
4343                Point::new(
4344                    center_pt.get_x() + dx * tick_in,
4345                    center_pt.get_y() + dy * tick_in,
4346                ),
4347                Point::new(
4348                    center_pt.get_x() + dx * tick_out,
4349                    center_pt.get_y() + dy * tick_out,
4350                ),
4351                1.0,
4352                Color::rgba(56, 189, 248, 30),
4353            );
4354        }
4355        let cols: usize = self.get_tilemap().get_columns();
4356        let rows: usize = self.get_tilemap().get_rows();
4357        let tile_sz: f32 = self.get_tilemap().get_tile_size();
4358        for col in 1..cols {
4359            let wx: f32 = (col as f32) * tile_sz;
4360            let sx: f32 = (wx - cam_x) * zoom + half_w;
4361            if sx < -2.0 || sx > vp_w + 2.0 {
4362                continue;
4363            }
4364            let major: bool = col % 2 == 0;
4365            let line_col: Color = if major {
4366                Color::rgba(56, 189, 248, 28)
4367            } else {
4368                Color::rgba(30, 58, 138, 22)
4369            };
4370            ctx.draw_line(
4371                Point::new(sx, inner_y0.max(0.0)),
4372                Point::new(sx, (inner_y0 + inner_h).min(vp_h)),
4373                if major { 1.1 } else { 0.8 },
4374                line_col,
4375            );
4376        }
4377        for row in 1..rows {
4378            let wy: f32 = (row as f32) * tile_sz;
4379            let sy: f32 = (wy - cam_y) * zoom + half_h;
4380            if sy < -2.0 || sy > vp_h + 2.0 {
4381                continue;
4382            }
4383            let major: bool = row % 2 == 0;
4384            let line_col: Color = if major {
4385                Color::rgba(56, 189, 248, 28)
4386            } else {
4387                Color::rgba(30, 58, 138, 22)
4388            };
4389            ctx.draw_line(
4390                Point::new(inner_x0.max(0.0), sy),
4391                Point::new((inner_x0 + inner_w).min(vp_w), sy),
4392                if major { 1.1 } else { 0.8 },
4393                line_col,
4394            );
4395        }
4396        let pulse: f32 = 0.72 + 0.28 * (phase_secs * 3.1).sin();
4397        let node_alpha: u8 = (62.0 * pulse) as u8;
4398        for row in (2..rows).step_by(2) {
4399            let sy: f32 = ((row as f32) * tile_sz - cam_y) * zoom + half_h;
4400            if sy < -4.0 || sy > vp_h + 4.0 {
4401                continue;
4402            }
4403            for col in (2..cols).step_by(2) {
4404                let sx: f32 = ((col as f32) * tile_sz - cam_x) * zoom + half_w;
4405                if sx < -4.0 || sx > vp_w + 4.0 {
4406                    continue;
4407                }
4408                ctx.fill_circle(
4409                    Point::new(sx, sy),
4410                    1.8 * zoom,
4411                    Color::rgba(56, 189, 248, node_alpha),
4412                );
4413            }
4414        }
4415        let wall_x0: f32 = inner_x0.clamp(2.0, vp_w - 4.0);
4416        let wall_y0: f32 = inner_y0.clamp(2.0, vp_h - 4.0);
4417        let wall_x1: f32 = (inner_x0 + inner_w).clamp(wall_x0 + 2.0, vp_w - 2.0);
4418        let wall_y1: f32 = (inner_y0 + inner_h).clamp(wall_y0 + 2.0, vp_h - 2.0);
4419        let wall_rect: Rect = Rect::new(wall_x0, wall_y0, wall_x1 - wall_x0, wall_y1 - wall_y0);
4420        ctx.stroke_rect(wall_rect, 5.0 * zoom, Color::rgba(56, 189, 248, 48));
4421        ctx.stroke_rect(wall_rect, 1.8 * zoom, Color::rgba(125, 211, 252, 225));
4422    }
4423
4424    /// Renders all live interpolated 2D arena entities with layered sci-fi silhouettes, dynamic light halos, engine plumes, and specular highlights.
4425    ///
4426    /// # Arguments
4427    ///
4428    /// - `&mut GameRenderContext<'_>` - Active viewport draw surface.
4429    /// - `&World2DSnapshot` - Interpolated snapshot containing live entity poses.
4430    /// - `Size` - Viewport dimensions in logical pixels.
4431    /// - `f32` - Continuous arena animation clock in seconds.
4432    ///
4433    /// # Returns
4434    ///
4435    /// - `usize` - Count of visible entities drawn.
4436    fn render_layered_entities(
4437        &self,
4438        ctx: &mut GameRenderContext<'_>,
4439        snap: &World2DSnapshot,
4440        size: Size,
4441        phase_secs: f32,
4442    ) -> usize {
4443        let cam: Camera2D = snap.get_camera();
4444        let (cam_x, cam_y, zoom, half_w, half_h): (f32, f32, f32, f32, f32) =
4445            cam.projection_params(size);
4446        let vp_w: f32 = size.get_width();
4447        let vp_h: f32 = size.get_height();
4448        let world_ref: &GameWorld = self.get_world();
4449        let mut drawn: usize = 0;
4450        for pose in snap.get_entities().iter() {
4451            if !pose.get_alive() {
4452                continue;
4453            }
4454            let Some(ent) = world_ref.get_entity(pose.get_id()) else {
4455                continue;
4456            };
4457            let tr: EntityTransform = pose.get_transform();
4458            let pos: Point = tr.get_position();
4459            let center: Point = Point::new(
4460                (pos.get_x() - cam_x) * zoom + half_w,
4461                (pos.get_y() - cam_y) * zoom + half_h,
4462            );
4463            let margin: f32 = 64.0 * zoom;
4464            if center.get_x() < -margin
4465                || center.get_x() > vp_w + margin
4466                || center.get_y() < -margin
4467                || center.get_y() > vp_h + margin
4468            {
4469                continue;
4470            }
4471            drawn += 1;
4472            let rot: f32 = tr.get_rotation_rad();
4473            let (sa, ca): (f32, f32) = rot.sin_cos();
4474            let cs: (f32, f32) = (ca, sa);
4475            match ent.get_tag() {
4476                EntityTag::Obstacle => {
4477                    let s_full: f32 = 52.0 * zoom;
4478                    let half_s: f32 = s_full * 0.5;
4479                    let pulse: f32 = 0.78 + 0.22 * (phase_secs * 3.2 + pos.get_x() * 0.02).sin();
4480                    ctx.fill_circle(center, 46.0 * zoom, Color::rgba(99, 102, 241, 24));
4481                    ctx.fill_rounded_rect(
4482                        Rect::new(
4483                            center.get_x() - half_s + 4.0 * zoom,
4484                            center.get_y() - half_s + 5.0 * zoom,
4485                            s_full,
4486                            s_full,
4487                        ),
4488                        Color::rgba(2, 6, 23, 175),
4489                        9.0 * zoom,
4490                    );
4491                    ctx.fill_rounded_rect(
4492                        Rect::new(
4493                            center.get_x() - half_s,
4494                            center.get_y() - half_s,
4495                            s_full,
4496                            s_full,
4497                        ),
4498                        Color::hex(0x0F172A),
4499                        8.0 * zoom,
4500                    );
4501                    ctx.stroke_rect(
4502                        Rect::new(
4503                            center.get_x() - half_s,
4504                            center.get_y() - half_s,
4505                            s_full,
4506                            s_full,
4507                        ),
4508                        1.6 * zoom,
4509                        Color::rgba(99, 102, 241, 190),
4510                    );
4511                    let inner_s: f32 = 34.0 * zoom;
4512                    let inner_h: f32 = inner_s * 0.5;
4513                    ctx.fill_rounded_rect(
4514                        Rect::new(
4515                            center.get_x() - inner_h,
4516                            center.get_y() - inner_h,
4517                            inner_s,
4518                            inner_s,
4519                        ),
4520                        Color::hex(0x1E293B),
4521                        5.0 * zoom,
4522                    );
4523                    ctx.fill_circle(center, 11.5 * zoom * pulse, Color::rgba(56, 189, 248, 52));
4524                    ctx.fill_circle(center, 6.2 * zoom, Color::hex(0x818CF8));
4525                    ctx.fill_circle(center, 2.8 * zoom, Color::hex(0xE0F2FE));
4526                }
4527                EntityTag::Pickup => {
4528                    let pulse: f32 = 0.85 + 0.15 * (phase_secs * 5.0 + pos.get_x()).sin();
4529                    let r_orb: f32 = 11.0 * zoom;
4530                    ctx.fill_circle(center, r_orb * 2.4 * pulse, Color::rgba(168, 85, 247, 30));
4531                    ctx.fill_circle(center, r_orb * 1.45, Color::rgba(56, 189, 248, 48));
4532                    let p_top: Point = Self::rotate_screen_offset(center, (0.0, -r_orb), cs);
4533                    let p_right: Point = Self::rotate_screen_offset(center, (r_orb, 0.0), cs);
4534                    let p_bot: Point = Self::rotate_screen_offset(center, (0.0, r_orb), cs);
4535                    let p_left: Point = Self::rotate_screen_offset(center, (-r_orb, 0.0), cs);
4536                    ctx.fill_triangle(p_top, p_right, p_bot, Color::hex(0xC084FC));
4537                    ctx.fill_triangle(p_top, p_bot, p_left, Color::hex(0x9333EA));
4538                    ctx.fill_circle(center, 4.2 * zoom, Color::hex(0xF5D0FE));
4539                    ctx.fill_circle(center, 2.0 * zoom, COLOR_WHITE);
4540                }
4541                EntityTag::Enemy => {
4542                    let is_interceptor: bool = ent
4543                        .sprite_component()
4544                        .is_some_and(|sp: Sprite2D| sp.get_shape() == EntityVisualShape::Diamond);
4545                    let pulse: f32 = 0.82 + 0.18 * (phase_secs * 6.0 + pos.get_y() * 0.05).sin();
4546                    let sz: f32 = 15.0 * zoom;
4547                    if is_interceptor {
4548                        ctx.fill_circle(center, sz * 2.1, Color::rgba(244, 63, 94, 30));
4549                        ctx.fill_circle(center, sz * 1.3, Color::rgba(251, 113, 133, 46));
4550                        let nose: Point = Self::rotate_screen_offset(center, (sz * 1.35, 0.0), cs);
4551                        let wing_l: Point =
4552                            Self::rotate_screen_offset(center, (-sz * 0.55, -sz * 1.05), cs);
4553                        let wing_r: Point =
4554                            Self::rotate_screen_offset(center, (-sz * 0.55, sz * 1.05), cs);
4555                        let tail: Point = Self::rotate_screen_offset(center, (-sz * 1.05, 0.0), cs);
4556                        ctx.fill_triangle(nose, wing_l, tail, Color::hex(0xE11D48));
4557                        ctx.fill_triangle(nose, tail, wing_r, Color::hex(0xFB7185));
4558                        let core_f: Point =
4559                            Self::rotate_screen_offset(center, (sz * 0.65, 0.0), cs);
4560                        let core_l: Point =
4561                            Self::rotate_screen_offset(center, (-sz * 0.35, -sz * 0.38), cs);
4562                        let core_r: Point =
4563                            Self::rotate_screen_offset(center, (-sz * 0.35, sz * 0.38), cs);
4564                        ctx.fill_triangle(core_f, core_l, core_r, Color::hex(0x1E1B4B));
4565                        ctx.fill_circle(center, 4.4 * zoom * pulse, Color::hex(0xFDE047));
4566                        ctx.fill_circle(center, 2.1 * zoom, COLOR_WHITE);
4567                    } else {
4568                        ctx.fill_circle(center, sz * 2.1, Color::rgba(245, 158, 11, 28));
4569                        ctx.fill_circle(center, sz * 1.3, Color::rgba(251, 191, 36, 42));
4570                        let spin_rot: f32 = rot + phase_secs * 1.8;
4571                        let (sb, cb): (f32, f32) = spin_rot.sin_cos();
4572                        let blade_cs: (f32, f32) = (cb, sb);
4573                        for blade_idx in 0..4usize {
4574                            let angle_off: f32 = (blade_idx as f32) * (PI * 0.5);
4575                            let (s_o, c_o): (f32, f32) = angle_off.sin_cos();
4576                            let b_cs: (f32, f32) = (
4577                                blade_cs.0 * c_o - blade_cs.1 * s_o,
4578                                blade_cs.0 * s_o + blade_cs.1 * c_o,
4579                            );
4580                            let tip: Point =
4581                                Self::rotate_screen_offset(center, (sz * 1.28, 0.0), b_cs);
4582                            let b_l: Point =
4583                                Self::rotate_screen_offset(center, (sz * 0.35, -sz * 0.38), b_cs);
4584                            let b_r: Point =
4585                                Self::rotate_screen_offset(center, (sz * 0.35, sz * 0.38), b_cs);
4586                            ctx.fill_triangle(tip, b_l, b_r, Color::hex(0xD97706));
4587                        }
4588                        ctx.fill_circle(center, sz * 0.78, Color::hex(0x1E293B));
4589                        ctx.fill_circle(center, sz * 0.54, Color::hex(0xF59E0B));
4590                        ctx.fill_circle(center, 4.2 * zoom * pulse, Color::hex(0xFEF08A));
4591                        ctx.fill_circle(center, 2.0 * zoom, COLOR_WHITE);
4592                    }
4593                }
4594                EntityTag::Projectile => {
4595                    let tail: Point = Self::rotate_screen_offset(center, (-16.0 * zoom, 0.0), cs);
4596                    ctx.draw_line(tail, center, 5.5 * zoom, Color::rgba(52, 211, 153, 52));
4597                    ctx.draw_line(tail, center, 2.4 * zoom, Color::rgba(110, 231, 183, 195));
4598                    ctx.fill_circle(center, 9.5 * zoom, Color::rgba(16, 185, 129, 44));
4599                    ctx.fill_circle(center, 4.5 * zoom, Color::hex(0x34D399));
4600                    ctx.fill_circle(center, 2.3 * zoom, COLOR_WHITE);
4601                }
4602                EntityTag::Player => {
4603                    let s_val: f32 = 16.5 * zoom;
4604                    let exhaust_flicker: f32 = 0.84 + 0.28 * (phase_secs * 24.0).sin().abs();
4605                    ctx.fill_circle(center, s_val * 1.45, Color::rgba(56, 189, 248, 20));
4606                    ctx.fill_circle(center, s_val * 0.92, Color::rgba(14, 165, 233, 34));
4607                    for nozzle_y in [-5.4_f32, 5.4_f32] {
4608                        let base_l: Point = Self::rotate_screen_offset(
4609                            center,
4610                            (-s_val * 0.72, (nozzle_y - 2.6) * zoom),
4611                            cs,
4612                        );
4613                        let base_r: Point = Self::rotate_screen_offset(
4614                            center,
4615                            (-s_val * 0.72, (nozzle_y + 2.6) * zoom),
4616                            cs,
4617                        );
4618                        let tip_out: Point = Self::rotate_screen_offset(
4619                            center,
4620                            (-s_val * (1.38 + 0.45 * exhaust_flicker), nozzle_y * zoom),
4621                            cs,
4622                        );
4623                        let tip_in: Point = Self::rotate_screen_offset(
4624                            center,
4625                            (-s_val * (1.05 + 0.25 * exhaust_flicker), nozzle_y * zoom),
4626                            cs,
4627                        );
4628                        ctx.fill_triangle(base_l, base_r, tip_out, Color::rgba(56, 189, 248, 175));
4629                        ctx.fill_triangle(base_l, base_r, tip_in, Color::hex(0xE0F2FE));
4630                    }
4631                    let nose: Point = Self::rotate_screen_offset(center, (s_val * 1.38, 0.0), cs);
4632                    let w_l_out: Point =
4633                        Self::rotate_screen_offset(center, (-s_val * 0.92, -s_val * 1.12), cs);
4634                    let w_r_out: Point =
4635                        Self::rotate_screen_offset(center, (-s_val * 0.92, s_val * 1.12), cs);
4636                    let stern: Point = Self::rotate_screen_offset(center, (-s_val * 0.56, 0.0), cs);
4637                    ctx.fill_triangle(nose, w_l_out, stern, Color::hex(0x0284C7));
4638                    ctx.fill_triangle(nose, stern, w_r_out, Color::hex(0x38BDF8));
4639                    let hull_l: Point =
4640                        Self::rotate_screen_offset(center, (-s_val * 0.68, -s_val * 0.58), cs);
4641                    let hull_r: Point =
4642                        Self::rotate_screen_offset(center, (-s_val * 0.68, s_val * 0.58), cs);
4643                    ctx.fill_triangle(nose, hull_l, hull_r, Color::hex(0x7DD3FC));
4644                    let canopy_f: Point =
4645                        Self::rotate_screen_offset(center, (s_val * 0.66, 0.0), cs);
4646                    let canopy_l: Point =
4647                        Self::rotate_screen_offset(center, (-s_val * 0.12, -s_val * 0.26), cs);
4648                    let canopy_r: Point =
4649                        Self::rotate_screen_offset(center, (-s_val * 0.12, s_val * 0.26), cs);
4650                    ctx.fill_triangle(canopy_f, canopy_l, canopy_r, Color::hex(0x0F172A));
4651                    let glint_pt: Point =
4652                        Self::rotate_screen_offset(center, (s_val * 0.30, -s_val * 0.04), cs);
4653                    ctx.fill_circle(glint_pt, 2.4 * zoom, Color::hex(0xE0F2FE));
4654                }
4655                _ => {}
4656            }
4657        }
4658        drawn
4659    }
4660
4661    /// Spawns `count` patrolling enemy drones around the arena perimeter.
4662    ///
4663    /// # Arguments
4664    ///
4665    /// - `&Self` - Mutable arena scene.
4666    /// - `usize` - Number of enemy drones to spawn.
4667    pub fn spawn_enemy_wave(&mut self, count: usize) {
4668        let bounds: Rect = self.get_tilemap().world_bounds();
4669        let cx: f32 = bounds.get_width() * 0.5;
4670        let cy: f32 = bounds.get_height() * 0.5;
4671        for idx in 0..count {
4672            let angle: f32 = ((idx as f32) / (count.max(1) as f32)) * 6.283_185_5
4673                + (self.get_wave() as f32) * 0.45;
4674            let radius: f32 = 138.0 + ((idx % 3) as f32) * 44.0;
4675            let sx: f32 = (cx + angle.cos() * radius).clamp(96.0, bounds.get_width() - 96.0);
4676            let sy: f32 = (cy + angle.sin() * radius).clamp(96.0, bounds.get_height() - 96.0);
4677            let speed: f32 = 95.0 + ((idx % 4) as f32) * 28.0;
4678            let eid: EntityId = self
4679                .get_mut_world()
4680                .spawn(EntityTag::Enemy, Point::new(sx, sy));
4681            if let Some(enemy) = self.get_mut_world().get_entity_mut(eid) {
4682                enemy.set_velocity(Velocity2D::new(
4683                    -angle.sin() * speed,
4684                    angle.cos() * speed,
4685                    1.5,
4686                ));
4687                enemy.set_body(Some(RigidBody2D::dynamic(1.2, 0.95, 0.05)));
4688                enemy.set_collider(Some(Collider2D::circle(
4689                    13.0,
4690                    COLLISION_LAYER_ENEMY,
4691                    COLLISION_LAYER_ALL,
4692                    false,
4693                )));
4694                enemy.set_sprite(Some(Sprite2D::new(
4695                    if idx % 2 == 0 {
4696                        EntityVisualShape::Diamond
4697                    } else {
4698                        EntityVisualShape::Circle
4699                    },
4700                    Size::new(26.0, 26.0),
4701                    if idx % 2 == 0 {
4702                        Color::hex(0xF43F5E)
4703                    } else {
4704                        Color::hex(0xF59E0B)
4705                    },
4706                    Color::hex(0xFEF08A),
4707                    6,
4708                    0.0,
4709                    true,
4710                )));
4711            }
4712        }
4713    }
4714
4715    /// Fires a fast plasma projectile from the player ship along `aim_angle`.
4716    ///
4717    /// # Arguments
4718    ///
4719    /// - `&Self` - Mutable arena scene.
4720    /// - `Point` - Launch origin in world coordinates.
4721    /// - `f32` - Launch angle in radians.
4722    fn fire_projectile(&mut self, origin: Point, aim_angle: f32) {
4723        let dir_x: f32 = aim_angle.cos();
4724        let dir_y: f32 = aim_angle.sin();
4725        let launch: Point =
4726            Point::new(origin.get_x() + dir_x * 20.0, origin.get_y() + dir_y * 20.0);
4727        let pid: EntityId = self.get_mut_world().spawn(EntityTag::Projectile, launch);
4728        if let Some(proj) = self.get_mut_world().get_entity_mut(pid) {
4729            proj.get_mut_transform().set_rotation_rad(aim_angle);
4730            proj.set_velocity(Velocity2D::new(dir_x * 520.0, dir_y * 520.0, 0.0));
4731            proj.set_body(Some(RigidBody2D::dynamic(0.2, 0.9, 0.0)));
4732            proj.set_collider(Some(Collider2D::circle(
4733                5.0,
4734                COLLISION_LAYER_PROJECTILE,
4735                COLLISION_LAYER_ENEMY | COLLISION_LAYER_WORLD,
4736                true,
4737            )));
4738            proj.set_sprite(Some(Sprite2D::new(
4739                EntityVisualShape::Circle,
4740                Size::new(10.0, 10.0),
4741                Color::hex(0x34D399),
4742                Color::hex(0xFFFFFF),
4743                8,
4744                0.0,
4745                true,
4746            )));
4747            proj.set_ttl_secs(Some(1.4));
4748        }
4749        let mut muzzle: ParticleEmitterConfig = ParticleEmitterConfig::default();
4750        muzzle
4751            .set_base_angle(aim_angle)
4752            .set_spread_rad(0.45)
4753            .set_min_speed(80.0)
4754            .set_max_speed(180.0)
4755            .set_min_life(0.12)
4756            .set_max_life(0.26)
4757            .set_start_size(3.5)
4758            .set_start_color(Color::hex(0x34D399))
4759            .set_end_color(Color::rgba(56, 189, 248, 0));
4760        self.get_mut_particles().emit_burst(launch, 6, muzzle);
4761        self.get_mut_audio().play(SoundCue::Laser, 0.65, 0.0, 1.05);
4762    }
4763}
4764
4765/// Deterministic fixed-timestep 2D game engine simulation and camera-driven HUD rendering for `DemoPhysicsScene`.
4766impl GameScene for DemoPhysicsScene {
4767    /// Steps player controls, ECS physics, collision combat, particles, and camera follow at 60Hz fixed cadence.
4768    ///
4769    /// # Arguments
4770    ///
4771    /// - `&Self` - Mutable arena scene.
4772    /// - `f32` - Fixed simulation delta time in seconds.
4773    /// - `&InputState` - Real-time polled keyboard and pointer state.
4774    fn fixed_update(&mut self, dt: f32, input: &InputState) {
4775        self.ensure_initialized();
4776        let move_vec: Point = self.get_actions().movement_vector(input);
4777        let fire_pressed: bool = self.get_actions().is_active(GameAction::Fire, input);
4778        let dash_pressed: bool = self.get_actions().is_just_pressed(GameAction::Dash, input);
4779        let wave_pressed: bool = self
4780            .get_actions()
4781            .is_just_pressed(GameAction::ActionAlt, input);
4782        if wave_pressed {
4783            let next_wave: u32 = self.get_wave().saturating_add(1);
4784            self.set_wave(next_wave);
4785            self.spawn_enemy_wave(6);
4786        }
4787        let fire_cd: f32 = (self.get_fire_cooldown() - dt).max(0.0);
4788        let dash_cd: f32 = (self.get_dash_cooldown() - dt).max(0.0);
4789        self.set_fire_cooldown(fire_cd);
4790        self.set_dash_cooldown(dash_cd);
4791        let player_id: EntityId = self.get_player_id();
4792        let mut player_pos: Point = Point::new(576.0, 336.0);
4793        let mut aim_angle: f32 = 0.0;
4794        let mut dashed: bool = false;
4795        if let Some(player) = self.get_mut_world().get_entity_mut(player_id) {
4796            player_pos = player.get_transform().get_position();
4797            let accel: f32 = 1650.0;
4798            let mut vel: Velocity2D = player.get_velocity();
4799            vel.set_vx(vel.get_vx() + move_vec.get_x() * accel * dt);
4800            vel.set_vy(vel.get_vy() + move_vec.get_y() * accel * dt);
4801            let mut rot: f32 = player.get_transform().get_rotation_rad();
4802            if move_vec.get_x().abs() > 0.05 || move_vec.get_y().abs() > 0.05 {
4803                rot = move_vec.get_y().atan2(move_vec.get_x());
4804            } else {
4805                rot += dt * 0.8;
4806            }
4807            if dash_pressed && dash_cd <= 0.0 {
4808                vel.set_vx(vel.get_vx() + rot.cos() * 440.0);
4809                vel.set_vy(vel.get_vy() + rot.sin() * 440.0);
4810                dashed = true;
4811            }
4812            player.set_velocity(vel);
4813            player.get_mut_transform().set_rotation_rad(rot);
4814            aim_angle = rot;
4815        }
4816        if dashed {
4817            self.set_dash_cooldown(0.45);
4818            self.get_mut_camera().add_trauma(0.25);
4819            let mut burst: ParticleEmitterConfig = ParticleEmitterConfig::default();
4820            burst
4821                .set_base_angle(aim_angle + PI)
4822                .set_spread_rad(0.9)
4823                .set_start_color(Color::hex(0x38BDF8))
4824                .set_end_color(Color::rgba(56, 189, 248, 0));
4825            self.get_mut_particles().emit_burst(player_pos, 18, burst);
4826            self.push_shockwave(player_pos, 16.0);
4827            self.get_mut_audio().play(SoundCue::Dash, 0.8, 0.0, 1.0);
4828        }
4829        if self.get_ticks().is_multiple_of(2) {
4830            let stern: Point = Point::new(
4831                player_pos.get_x() - aim_angle.cos() * 14.0,
4832                player_pos.get_y() - aim_angle.sin() * 14.0,
4833            );
4834            let mut thruster: ParticleEmitterConfig = ParticleEmitterConfig::default();
4835            thruster
4836                .set_base_angle(aim_angle + PI)
4837                .set_spread_rad(0.38)
4838                .set_min_speed(42.0)
4839                .set_max_speed(105.0)
4840                .set_min_life(0.16)
4841                .set_max_life(0.34)
4842                .set_start_size(3.2)
4843                .set_start_color(Color::hex(0x38BDF8))
4844                .set_end_color(Color::rgba(99, 102, 241, 0));
4845            self.get_mut_particles().emit_burst(stern, 2, thruster);
4846        }
4847        if (fire_pressed || self.get_ticks().is_multiple_of(22)) && fire_cd <= 0.0 {
4848            self.fire_projectile(player_pos, aim_angle);
4849            self.set_fire_cooldown(0.14);
4850        }
4851        let collisions: Vec<CollisionEvent> = {
4852            let Self { world, physics, .. } = self;
4853            physics.step(world, dt)
4854        };
4855        {
4856            let Self {
4857                world,
4858                to_despawn_scratch,
4859                camera,
4860                audio,
4861                ..
4862            } = self;
4863            to_despawn_scratch.clear();
4864            for ui_event in collisions.into_iter() {
4865                let tag_a: Option<EntityTag> = world
4866                    .get_entity(ui_event.get_entity_a())
4867                    .map(EntityRecord::get_tag);
4868                let tag_b: Option<EntityTag> = world
4869                    .get_entity(ui_event.get_entity_b())
4870                    .map(EntityRecord::get_tag);
4871                match (tag_a, tag_b) {
4872                    (Some(EntityTag::Projectile), Some(EntityTag::Enemy)) => {
4873                        if let Some(event_ref) = world.get_entity(ui_event.get_entity_b()) {
4874                            to_despawn_scratch.push((
4875                                ui_event.get_entity_b(),
4876                                event_ref.get_transform().get_position(),
4877                                true,
4878                            ));
4879                        }
4880                        to_despawn_scratch.push((ui_event.get_entity_a(), Point::default(), false));
4881                    }
4882                    (Some(EntityTag::Enemy), Some(EntityTag::Projectile)) => {
4883                        if let Some(error_val) = world.get_entity(ui_event.get_entity_a()) {
4884                            to_despawn_scratch.push((
4885                                ui_event.get_entity_a(),
4886                                error_val.get_transform().get_position(),
4887                                true,
4888                            ));
4889                        }
4890                        to_despawn_scratch.push((ui_event.get_entity_b(), Point::default(), false));
4891                    }
4892                    (Some(EntityTag::Projectile), Some(EntityTag::Obstacle)) => {
4893                        to_despawn_scratch.push((ui_event.get_entity_a(), Point::default(), false));
4894                    }
4895                    (Some(EntityTag::Obstacle), Some(EntityTag::Projectile)) => {
4896                        to_despawn_scratch.push((ui_event.get_entity_b(), Point::default(), false));
4897                    }
4898                    (Some(EntityTag::Player), Some(EntityTag::Enemy))
4899                    | (Some(EntityTag::Enemy), Some(EntityTag::Player)) => {
4900                        camera.add_trauma(0.35);
4901                        audio.play(SoundCue::Bounce, 0.7, 0.0, 0.85);
4902                    }
4903                    _ => {}
4904                }
4905            }
4906        }
4907        {
4908            let Self {
4909                world,
4910                to_despawn_scratch,
4911                score,
4912                camera,
4913                particles,
4914                audio,
4915                shockwaves,
4916                ..
4917            } = self;
4918            for &(eid, pos, is_enemy) in to_despawn_scratch.iter() {
4919                if world.despawn(eid) && is_enemy {
4920                    *score = score.saturating_add(100);
4921                    camera.add_trauma(0.32);
4922                    let mut exp: ParticleEmitterConfig = ParticleEmitterConfig::default();
4923                    exp.set_min_speed(70.0)
4924                        .set_max_speed(260.0)
4925                        .set_start_size(5.5)
4926                        .set_start_color(Color::hex(0xFB7185))
4927                        .set_end_color(Color::rgba(250, 204, 21, 0));
4928                    particles.emit_burst(pos, 26, exp);
4929                    for ring in shockwaves.iter_mut() {
4930                        if ring.3 <= 0.001 {
4931                            *ring = (pos.get_x(), pos.get_y(), 12.0, 1.0);
4932                            break;
4933                        }
4934                    }
4935                    audio.play(SoundCue::Explosion, 0.9, 0.0, 0.95);
4936                }
4937            }
4938            to_despawn_scratch.clear();
4939            for ring in shockwaves.iter_mut() {
4940                if ring.3 > 0.0 {
4941                    ring.2 += 210.0 * dt;
4942                    ring.3 = (ring.3 - 2.35 * dt).max(0.0);
4943                }
4944            }
4945        }
4946        if self.get_world().count_by_tag(EntityTag::Enemy) < 3 {
4947            let next_wave: u32 = self.get_wave().saturating_add(1);
4948            self.set_wave(next_wave);
4949            self.spawn_enemy_wave(6);
4950        }
4951        let _: usize = self.get_mut_world().tick_lifetimes(dt);
4952        let _: usize = self.get_mut_particles().update(dt);
4953        let _: Vec<AudioCommand> = self.get_mut_audio().drain();
4954        if let Some(player) = self.get_world().get_entity(player_id) {
4955            let point_coords: Point = player.get_transform().get_position();
4956            let box_size: Size = self.get_viewport_size();
4957            self.get_mut_camera()
4958                .follow(point_coords, 7.5, dt, box_size);
4959        }
4960        self.set_ticks(self.get_ticks().saturating_add(1));
4961        self.set_last_sampled_tick(u64::MAX);
4962        let next_snap: World2DSnapshot =
4963            World2DSnapshot::capture(self.get_world(), self.get_camera(), false, Vec::new());
4964        self.get_mut_snapshots().commit(next_snap);
4965    }
4966
4967    /// Updates smoothed frame-rate telemetry once per visual frame.
4968    ///
4969    /// # Arguments
4970    ///
4971    /// - `&Self` - Mutable arena scene.
4972    /// - `f32` - Real frame delta time in seconds.
4973    /// - `&InputState` - Current polled input snapshot.
4974    fn update(&mut self, dt: f32, _input: &InputState) {
4975        if dt > 0.0001 {
4976            let inst_fps: f32 = (1.0 / dt).clamp(1.0, 9999.0);
4977            let prev: f32 = self.get_smoothed_fps();
4978            let next: f32 = if prev <= 0.5 {
4979                inst_fps
4980            } else {
4981                prev * 0.85 + inst_fps * 0.15
4982            };
4983            self.set_smoothed_fps(next);
4984        }
4985    }
4986
4987    /// Renders the camera-projected tilemap, ECS entities, raycast targeting laser, particles, and engine HUD with single-pass snapshot interpolation.
4988    ///
4989    /// # Arguments
4990    ///
4991    /// - `&Self` - Mutable arena scene.
4992    /// - `f32` - Interpolation alpha in `[0.0, 1.0]`.
4993    /// - `&mut GameRenderContext<'_>` - Immediate-mode game draw surface.
4994    fn render(&mut self, alpha: f32, ctx: &mut GameRenderContext<'_>) {
4995        self.ensure_initialized();
4996        let size: Size = ctx.viewport_size();
4997        if size.get_width() > 32.0 && size.get_height() > 32.0 {
4998            let fit_zoom: f32 = (size.get_width() / 860.0)
4999                .min(size.get_height() / 620.0)
5000                .clamp(0.48, 1.28);
5001            let vp_changed: bool = size != self.get_viewport_size();
5002            let zoom_changed: bool = (self.get_camera().get_zoom() - fit_zoom).abs() > 0.001;
5003            if vp_changed || zoom_changed {
5004                self.set_viewport_size(size);
5005                self.get_mut_camera().set_zoom(fit_zoom);
5006                self.get_mut_snapshots()
5007                    .get_mut_prev_state()
5008                    .get_mut_camera()
5009                    .set_zoom(fit_zoom);
5010                self.get_mut_snapshots()
5011                    .get_mut_curr_state()
5012                    .get_mut_camera()
5013                    .set_zoom(fit_zoom);
5014                self.set_last_sampled_tick(u64::MAX);
5015            }
5016        }
5017        ctx.clear(Color::hex(0x030712));
5018        let alpha_milli: i32 = (alpha.clamp(0.0, 1.0) * 1000.0).round() as i32;
5019        let cur_ticks: u64 = self.get_ticks();
5020        let needs_resample: bool = self.get_last_sampled_tick() != cur_ticks
5021            || self.get_last_sampled_alpha_milli() != alpha_milli
5022            || {
5023                let Self { cached_interp, .. } = self;
5024                cached_interp.is_none()
5025            };
5026        if needs_resample {
5027            let sampled: World2DSnapshot = self.get_snapshots().sample(alpha);
5028            let Self {
5029                cached_interp,
5030                last_sampled_tick,
5031                last_sampled_alpha_milli,
5032                ..
5033            } = self;
5034            *cached_interp = Some(sampled);
5035            *last_sampled_tick = cur_ticks;
5036            *last_sampled_alpha_milli = alpha_milli;
5037        }
5038        let player_id: EntityId = self.get_player_id();
5039        let (cam, interp_player_tr): (Camera2D, Option<EntityTransform>) = {
5040            let Self {
5041                cached_interp,
5042                world,
5043                camera,
5044                ..
5045            } = self;
5046            match cached_interp.as_ref() {
5047                Some(snap) => {
5048                    let transform_val: Option<EntityTransform> = snap
5049                        .get_entities()
5050                        .iter()
5051                        .find(|pose: &&EntityPose2D| pose.get_alive() && pose.get_id() == player_id)
5052                        .map(EntityPose2D::get_transform)
5053                        .or_else(|| world.get_entity(player_id).map(EntityRecord::get_transform));
5054                    (snap.get_camera(), transform_val)
5055                }
5056                None => (
5057                    *camera,
5058                    world.get_entity(player_id).map(EntityRecord::get_transform),
5059                ),
5060            }
5061        };
5062        let phase_secs: f32 = ((cur_ticks as f32) + alpha) * (1.0 / 60.0);
5063        self.render_tactical_arena_floor(ctx, &cam, size, phase_secs);
5064        if let Some(player_tr) = interp_player_tr {
5065            let origin: Point = player_tr.get_position();
5066            let rot: f32 = player_tr.get_rotation_rad();
5067            let dir: Point = Point::new(rot.cos(), rot.sin());
5068            let (end_world, locked_target): (Point, bool) = match PhysicsWorld2D::raycast(
5069                self.get_world(),
5070                origin,
5071                dir,
5072                340.0,
5073                COLLISION_LAYER_ENEMY | COLLISION_LAYER_WORLD,
5074            ) {
5075                Some(hit) => (hit.get_point(), true),
5076                None => (
5077                    Point::new(
5078                        origin.get_x() + dir.get_x() * 340.0,
5079                        origin.get_y() + dir.get_y() * 340.0,
5080                    ),
5081                    false,
5082                ),
5083            };
5084            let s0: Point = cam.world_to_screen(origin, size);
5085            let s1: Point = cam.world_to_screen(end_world, size);
5086            let beam_outer: Color = if locked_target {
5087                Color::rgba(244, 63, 94, 42)
5088            } else {
5089                Color::rgba(56, 189, 248, 32)
5090            };
5091            let beam_core: Color = if locked_target {
5092                Color::rgba(251, 113, 133, 195)
5093            } else {
5094                Color::rgba(125, 211, 252, 165)
5095            };
5096            ctx.draw_line(s0, s1, 5.4, beam_outer);
5097            ctx.draw_line(s0, s1, 1.6, beam_core);
5098            let ret_r: f32 = if locked_target { 9.5 } else { 5.5 };
5099            ctx.fill_circle(s1, ret_r * 1.4, beam_outer);
5100            ctx.fill_circle(s1, 3.0, beam_core);
5101        }
5102        let shockwave_copy: [(f32, f32, f32, f32); 8] = *self.get_shockwaves();
5103        let zoom: f32 = cam.get_zoom();
5104        for &(wx, wy, rad_w, life) in shockwave_copy.iter() {
5105            if life <= 0.01 {
5106                continue;
5107            }
5108            let sc: Point = cam.world_to_screen(Point::new(wx, wy), size);
5109            let sr: f32 = rad_w * zoom;
5110            let ring_alpha: u8 = (life * 92.0).clamp(0.0, 120.0) as u8;
5111            ctx.fill_circle(sc, sr, Color::rgba(56, 189, 248, ring_alpha / 3));
5112            let segs: usize = 16;
5113            let step: f32 = (2.0 * PI) / (segs as f32);
5114            for seg in 0..segs {
5115                let a0: f32 = (seg as f32) * step;
5116                let a1: f32 = ((seg + 1) as f32) * step;
5117                let p0: Point = Point::new(sc.get_x() + a0.cos() * sr, sc.get_y() + a0.sin() * sr);
5118                let p1: Point = Point::new(sc.get_x() + a1.cos() * sr, sc.get_y() + a1.sin() * sr);
5119                ctx.draw_line(p0, p1, 2.0, Color::rgba(125, 211, 252, ring_alpha));
5120            }
5121        }
5122        let drawn_entities: usize = match self.try_get_cached_interp() {
5123            Some(snap) => self.render_layered_entities(ctx, snap, size, phase_secs),
5124            None => 0,
5125        };
5126        let drawn_particles: usize = ctx.render_particles(self.get_particles(), &cam);
5127        if self.get_show_colliders() {
5128            ctx.draw_debug_colliders(self.get_world(), &cam);
5129        }
5130        let hud_text: String = format!(
5131            "{:.0} FPS · W{} · {} pts · {} Ent · {} Part · DASH",
5132            self.get_smoothed_fps().max(60.0),
5133            self.get_wave(),
5134            self.get_score(),
5135            drawn_entities,
5136            drawn_particles
5137        );
5138        let dash_charge: f32 = (1.0 - self.get_dash_cooldown() / 0.45).clamp(0.0, 1.0);
5139        let pill_w: f32 =
5140            ((hud_text.len() as f32) * 6.8 + 64.0).clamp(245.0, size.get_width() - 20.0);
5141        let pill_rect: Rect = Rect::new(10.0, 10.0, pill_w, 26.0);
5142        ctx.fill_rounded_rect(pill_rect, Color::rgba(6, 11, 24, 216), 8.0);
5143        ctx.stroke_rect(pill_rect, 1.0, Color::rgba(56, 189, 248, 95));
5144        let bar_w: f32 = 42.0;
5145        let bar_x: f32 = 10.0 + pill_w - bar_w - 10.0;
5146        ctx.fill_rounded_rect(
5147            Rect::new(bar_x, 19.0, bar_w, 7.0),
5148            Color::rgba(30, 41, 59, 220),
5149            3.5,
5150        );
5151        ctx.fill_rounded_rect(
5152            Rect::new(bar_x, 19.0, (bar_w * dash_charge).max(3.0), 7.0),
5153            Color::hex(0x38BDF8),
5154            3.5,
5155        );
5156        ctx.draw_text(Point::new(18.0, 15.5), hud_text, 11.0, Color::hex(0xE2E8F0));
5157    }
5158}
5159
5160/// Construction, async city loading, and runtime-config helpers for `DemoOpenWorld3DScene`.
5161impl DemoOpenWorld3DScene {
5162    /// Creates an empty zero-allocation 3D city placeholder sharing lazy signal and background-worker cells.
5163    ///
5164    /// # Arguments
5165    ///
5166    /// - `Rc<Cell<Option<Engine3dSignals>>>` - Shared lazy `/game3d` control signal cell.
5167    /// - `Scope` - Root ownership scope retaining lazily materialized `/game3d` signals across route evictions.
5168    /// - `Rc<Cell<bool>>` - Shared toggle enabling background OS-thread city construction.
5169    ///
5170    /// # Returns
5171    ///
5172    /// - `Self` - Uninitialized lazy 3D scene placeholder.
5173    #[must_use]
5174    pub(crate) fn create_lazy_city_deferred(
5175        signals_cell: Rc<Cell<Option<Engine3dSignals>>>,
5176        state_scope: Scope,
5177        bg_workers_enabled: Rc<Cell<bool>>,
5178    ) -> Self {
5179        Self {
5180            world: World3D::default(),
5181            renderer: Renderer3D::default(),
5182            actions: ActionMap::default(),
5183            signals_cell,
5184            state_scope,
5185            bg_workers_enabled,
5186            bg_city_task: None,
5187            last_import_seq: 0,
5188            smoothed_fps: 0.0,
5189            initialized: false,
5190            snapshots: DoubleBufferedSnapshot::new(World3DSnapshot::default()),
5191            frame_pool: RenderBufferPool::with_capacity(3),
5192            gpu_target: GpuCompositeTarget::default(),
5193            frame_fence: 0,
5194            last_camera_mode: 0,
5195            last_atmosphere_idx: 0,
5196            ticks: 0,
5197            cached_world_frame: None,
5198            cached_world_rev: u64::MAX,
5199            cached_alpha_milli: i32::MIN,
5200            cached_dims: (0, 0),
5201            cached_quality: RenderQualityConfig::default(),
5202            last_render_ms: 0.0,
5203        }
5204    }
5205
5206    /// Resolves the shared lazy `/game3d` control signals on first active tick or render.
5207    ///
5208    /// # Arguments
5209    ///
5210    /// - `&Self` - 3D scene reference.
5211    ///
5212    /// # Returns
5213    ///
5214    /// - `Engine3dSignals` - Active `/game3d` control signals.
5215    fn active_signals(&self) -> Engine3dSignals {
5216        Engine3dSignals::get_or_init(self.get_signals_cell().as_ref(), self.get_state_scope())
5217    }
5218
5219    /// Commits a constructed `World3D` open-world city into this scene and marks the world render target dirty.
5220    ///
5221    /// # Arguments
5222    ///
5223    /// - `&Self` - Mutable 3D scene.
5224    /// - `World3D` - Built Vice Boulevard open-world city.
5225    fn install_world(&mut self, world: World3D) {
5226        let initial_snap: World3DSnapshot =
5227            World3DSnapshot::capture(&world, 0, true, Vec::new(), Vec::new());
5228        let init_mode: u8 = world.get_camera_mode();
5229        self.set_world(world);
5230        self.set_snapshots(DoubleBufferedSnapshot::new(initial_snap));
5231        self.set_last_camera_mode(init_mode);
5232        self.get_mut_gpu_target().mark_world_dirty();
5233        self.set_cached_world_frame(None);
5234        self.set_cached_world_rev(u64::MAX);
5235        self.set_initialized(true);
5236        let _: bool = self
5237            .active_signals()
5238            .get_engine3d_import_status()
5239            .set_if_changed(DEFAULT_ENGINE3D_STATUS.to_string());
5240    }
5241
5242    /// Lazily initializes the Vice Boulevard 3D open-world city, using a background worker thread on interactive native apps.
5243    ///
5244    /// # Arguments
5245    ///
5246    /// - `&Self` - Mutable 3D scene.
5247    ///
5248    /// # Returns
5249    ///
5250    /// - `bool` - `true` when the 3D city is ready for simulation and rendering.
5251    fn ensure_initialized(&mut self) -> bool {
5252        if self.get_initialized() {
5253            return true;
5254        }
5255        let ready_world: Option<World3D> = {
5256            let Self { bg_city_task, .. } = self;
5257            if let Some(task) = bg_city_task.as_ref() {
5258                if let Some(world) = task.try_take() {
5259                    *bg_city_task = None;
5260                    Some(world)
5261                } else {
5262                    return false;
5263                }
5264            } else {
5265                None
5266            }
5267        };
5268        if let Some(world) = ready_world {
5269            self.install_world(world);
5270            return true;
5271        }
5272        if self.get_bg_workers_enabled().get() {
5273            let task: BackgroundTask<World3D> =
5274                BackgroundTask::spawn(World3D::create_open_world_city);
5275            let _: bool = self
5276                .active_signals()
5277                .get_engine3d_import_status()
5278                .set_if_changed(STATUS_ENGINE3D_LOADING.to_string());
5279            self.set_bg_city_task(Some(task));
5280            return false;
5281        }
5282        let world: World3D = World3D::create_open_world_city();
5283        self.install_world(world);
5284        true
5285    }
5286
5287    /// Creates the live Vice Boulevard 3D open-world scene bound to explicit reactive runtime settings signals.
5288    ///
5289    /// # Arguments
5290    ///
5291    /// - `Signal<RenderQualityConfig>` - Live quality/RT/resolution configuration signal.
5292    /// - `Signal<f32>` - Live time-of-day sun hour signal.
5293    /// - `Signal<u64>` - Monotonic model import request signal.
5294    /// - `Signal<String>` - Live status feedback signal.
5295    /// - `Signal<u8>` - Active 3D camera mode signal (`0=Chase, 1=Hood, 2=Orbit, 3=Aerial`).
5296    ///
5297    /// # Returns
5298    ///
5299    /// - `Self` - Initialized 3D open-world scene.
5300    #[must_use]
5301    pub fn create_city(
5302        quality_signal: Signal<RenderQualityConfig>,
5303        time_signal: Signal<f32>,
5304        import_signal: Signal<u64>,
5305        status_signal: Signal<String>,
5306        camera_mode_signal: Signal<u8>,
5307    ) -> Self {
5308        let group: Engine3dSignals = Engine3dSignals {
5309            engine3d_quality: quality_signal,
5310            engine3d_preset_idx: Signal::new(4),
5311            engine3d_rt_idx: Signal::new(3),
5312            engine3d_res_scale: Signal::new(100.0),
5313            engine3d_time_of_day: time_signal,
5314            engine3d_import_queue: import_signal,
5315            engine3d_import_status: status_signal,
5316            engine3d_camera_mode: camera_mode_signal,
5317            engine3d_tsr_idx: Signal::new(0),
5318            engine3d_atmosphere_idx: Signal::new(0),
5319        };
5320        let (state_scope, _): (Scope, ()) = Scope::run(|_: Scope| {});
5321        let mut scene: Self = Self::create_lazy_city_deferred(
5322            Rc::new(Cell::new(Some(group))),
5323            state_scope,
5324            Rc::new(Cell::new(false)),
5325        );
5326        let _: bool = scene.ensure_initialized();
5327        scene
5328    }
5329}
5330
5331/// Deterministic 3D open-world simulation and HUD-decoupled PBR + BVH ray-traced rendering for `DemoOpenWorld3DScene`.
5332impl GameScene for DemoOpenWorld3DScene {
5333    /// Steps vehicle physics, camera follow, spinning imported models, time-of-day sun, and queued model imports.
5334    ///
5335    /// # Arguments
5336    ///
5337    /// - `&Self` - Mutable 3D scene.
5338    /// - `f32` - Fixed simulation timestep in seconds.
5339    /// - `&InputState` - Real-time polled keyboard/pointer state.
5340    fn fixed_update(&mut self, dt: f32, input: &InputState) {
5341        if !self.ensure_initialized() {
5342            return;
5343        }
5344        let prev_world_rev: u64 = self.get_world().get_world_revision();
5345        let signals: Engine3dSignals = self.active_signals();
5346        let req_seq: u64 = signals.get_engine3d_import_queue().get_untracked();
5347        if req_seq != self.get_last_import_seq() {
5348            self.set_last_import_seq(req_seq);
5349            let is_obj: bool = req_seq % 2 == 1;
5350            let z_pos: f32 = -4.0 - ((req_seq % 5) as f32) * 8.0;
5351            let x_pos: f32 = if is_obj { -5.5 } else { 5.5 };
5352            let import_res: Result<ImportedModel3D, String> = if is_obj {
5353                self.get_mut_world().import_model(
5354                    ModelFormat::Obj,
5355                    SAMPLE_OBJ_MONUMENT,
5356                    Transform3D::new(Vec3::new(x_pos, 0.0, z_pos), 0.0, Vec3::splat(1.0)),
5357                    PbrMaterial::pbr(Color::hex(0xF59E0B), 0.9, 0.14, 0.72),
5358                    0.85,
5359                )
5360            } else {
5361                self.get_mut_world().import_model(
5362                    ModelFormat::GltfJson,
5363                    SAMPLE_GLTF_TOWER,
5364                    Transform3D::new(Vec3::new(x_pos, 0.0, z_pos), 0.0, Vec3::splat(1.0)),
5365                    PbrMaterial::pbr(Color::hex(0x38BDF8), 0.85, 0.12, 0.80),
5366                    -0.70,
5367                )
5368            };
5369            if let Ok(info) = import_res {
5370                let msg: String = format!(
5371                    "Imported {} ({:?}): {} verts, {} tris (LOD0+LOD1 + BVH rebuilt)",
5372                    info.get_name(),
5373                    info.get_format(),
5374                    info.get_total_vertices(),
5375                    info.get_total_triangles()
5376                );
5377                let _: bool = signals.get_engine3d_import_status().set_if_changed(msg);
5378            }
5379        }
5380        let atmo_idx: usize = signals.get_engine3d_atmosphere_idx().get_untracked();
5381        if atmo_idx != self.get_last_atmosphere_idx() {
5382            self.set_last_atmosphere_idx(atmo_idx);
5383            let preset_hour: f32 = self
5384                .get_mut_world()
5385                .apply_atmosphere_preset(atmo_idx.min(3) as u8);
5386            let _: bool = signals
5387                .get_engine3d_time_of_day()
5388                .set_if_changed(preset_hour);
5389        } else {
5390            let hour: f32 = signals.get_engine3d_time_of_day().get_untracked();
5391            if (hour - self.get_world().get_sun().get_time_of_day()).abs() > 0.05 {
5392                self.get_mut_world()
5393                    .set_sun(DirectionalLight3D::from_time_of_day(hour));
5394            }
5395        }
5396        let cam_mode: u8 = signals.get_engine3d_camera_mode().get_untracked();
5397        let cam_cut: bool = cam_mode != self.get_last_camera_mode();
5398        if cam_mode != self.get_world().get_camera_mode() {
5399            self.get_mut_world().set_camera_mode(cam_mode);
5400        }
5401        self.set_last_camera_mode(cam_mode);
5402        let Self { world, actions, .. } = self;
5403        world.step_simulation(dt, input, actions);
5404        let next_tick: u64 = self.get_ticks().saturating_add(1);
5405        self.set_ticks(next_tick);
5406        let world_changed: bool =
5407            cam_cut || self.get_world().get_world_revision() != prev_world_rev;
5408        if cam_cut {
5409            let Self {
5410                world, snapshots, ..
5411            } = self;
5412            snapshots.capture_discontinuous_into(|dst: &mut World3DSnapshot| {
5413                dst.capture_dynamic_into(world, next_tick, true, &[], &[]);
5414            });
5415        } else {
5416            let Self {
5417                world, snapshots, ..
5418            } = self;
5419            snapshots.capture_into(|dst: &mut World3DSnapshot| {
5420                dst.capture_dynamic_into(world, next_tick, false, &[], &[]);
5421            });
5422        }
5423        if world_changed {
5424            self.get_mut_gpu_target().mark_world_dirty();
5425        }
5426    }
5427
5428    /// Updates smoothed FPS telemetry for the 3D HUD overlay without dirtying the 3D world render target.
5429    ///
5430    /// # Arguments
5431    ///
5432    /// - `&Self` - Mutable 3D scene.
5433    /// - `f32` - Real frame delta time in seconds.
5434    /// - `&InputState` - Current polled input snapshot.
5435    fn update(&mut self, dt: f32, _input: &InputState) {
5436        if dt > 0.0001 {
5437            let inst_fps: f32 = (1.0 / dt).clamp(1.0, 9999.0);
5438            let prev: f32 = self.get_smoothed_fps();
5439            let next: f32 = if prev <= 0.5 {
5440                inst_fps
5441            } else {
5442                prev * 0.85 + inst_fps * 0.15
5443            };
5444            self.set_smoothed_fps(next);
5445            self.get_mut_gpu_target().mark_hud_dirty();
5446        }
5447    }
5448
5449    /// Renders the 3D open-world city with HUD-decoupled caching and overlays live telemetry HUD.
5450    ///
5451    /// # Arguments
5452    ///
5453    /// - `&Self` - Mutable 3D scene.
5454    /// - `f32` - Interpolation alpha.
5455    /// - `&mut GameRenderContext<'_>` - Immediate-mode viewport draw context.
5456    fn render(&mut self, alpha: f32, ctx: &mut GameRenderContext<'_>) {
5457        let size: Size = ctx.viewport_size();
5458        if !self.ensure_initialized() {
5459            ctx.clear(Color::hex(0x090D16));
5460            ctx.fill_rounded_rect(
5461                Rect::new(
5462                    10.0,
5463                    10.0,
5464                    (size.get_width() - 20.0).clamp(200.0, 560.0),
5465                    28.0,
5466                ),
5467                Color::rgba(15, 23, 42, 220),
5468                6.0,
5469            );
5470            ctx.draw_text(
5471                Point::new(18.0, 16.0),
5472                HUD_3D_LOADING_TITLE.to_string(),
5473                11.5,
5474                Color::hex(0x38BDF8),
5475            );
5476            return;
5477        }
5478        let signals: Engine3dSignals = self.active_signals();
5479        let mut quality: RenderQualityConfig = signals.get_engine3d_quality().get_untracked();
5480        let prev_render_ms: f32 = self.get_last_render_ms();
5481        if quality.get_dynamic_resolution() && prev_render_ms > 0.05 {
5482            let _: FramePacingTelemetry3D = self
5483                .get_mut_renderer()
5484                .apply_frame_pacing_feedback(prev_render_ms, &mut quality);
5485        }
5486        let dpr: f32 = ctx.scale_factor().clamp(1.0, 2.5);
5487        let preset_boost: f32 = match quality.get_preset() {
5488            QualityPreset::Low => 1.05,
5489            QualityPreset::Medium => 1.25,
5490            QualityPreset::High => 1.38,
5491            QualityPreset::Ultra => 1.45,
5492            QualityPreset::Cinematic => 1.52,
5493        };
5494        let dpi_boost: f32 = preset_boost.max(dpr.min(2.0));
5495        let raw_w: f32 = (size.get_width().max(64.0) * dpi_boost).max(160.0);
5496        let raw_h: f32 = (size.get_height().max(64.0) * dpi_boost).max(160.0);
5497        let max_dim: f32 = 960.0;
5498        let max_pixels: f32 = 960.0 * 540.0;
5499        let dim_scale: f32 = (max_dim / raw_w.max(raw_h)).min(1.0);
5500        let area_scale: f32 = (max_pixels / (raw_w * raw_h).max(1.0)).sqrt().min(1.0);
5501        let fit_scale: f32 = dim_scale.min(area_scale);
5502        let vw: u32 = ((raw_w * fit_scale).round() as u32).clamp(160, 960);
5503        let vh: u32 = ((raw_h * fit_scale).round() as u32).clamp(160, 960);
5504        let next_fence: u64 = self.get_frame_fence().saturating_add(1);
5505        self.set_frame_fence(next_fence);
5506        let dst_rect: Rect = Rect::new(0.0, 0.0, size.get_width(), size.get_height());
5507        let alpha_milli: i32 = (alpha.clamp(0.0, 1.0) * 1000.0).round() as i32;
5508        let world_rev: u64 = self.get_gpu_target().get_world_revision();
5509        let can_reuse_world: bool = !self.get_gpu_target().needs_world_render()
5510            && self.get_cached_world_rev() == world_rev
5511            && self.get_cached_dims() == (vw, vh)
5512            && self.get_cached_quality() == quality
5513            && self.get_cached_alpha_milli() == alpha_milli;
5514        let mut blitted_pooled: bool = false;
5515        let gpu_handle: GpuTextureHandle = self.get_gpu_target().get_handle();
5516        if gpu_handle.is_valid() && ctx.composite_gpu_texture(dst_rect, gpu_handle) {
5517            let _: Option<GpuCompositeDescriptor> = self
5518                .get_mut_gpu_target()
5519                .record_composite_present(next_fence);
5520            blitted_pooled = true;
5521        } else if can_reuse_world {
5522            let reused_ref: Option<PooledFrameRef> = {
5523                let Self {
5524                    cached_world_frame, ..
5525                } = self;
5526                cached_world_frame.clone()
5527            };
5528            if let Some(cached_ref) = reused_ref {
5529                ctx.blit_pooled_frame_ref(dst_rect, &cached_ref);
5530                let hud_rev: u64 = self.get_gpu_target().get_hud_revision();
5531                let next_reuse: u64 = self
5532                    .get_gpu_target()
5533                    .get_hud_only_reuses()
5534                    .saturating_add(1);
5535                let target: &mut GpuCompositeTarget = self.get_mut_gpu_target();
5536                target.set_presented_hud_revision(hud_rev);
5537                target.set_hud_only_reuses(next_reuse);
5538                blitted_pooled = true;
5539            }
5540        }
5541        if !blitted_pooled {
5542            self.set_cached_world_frame(None);
5543            #[cfg(not(target_arch = "wasm32"))]
5544            let render_started: Instant = Instant::now();
5545            let use_tsr_upscale: bool = quality.get_anti_aliasing() == AntiAliasingMode::Tsr
5546                && quality.get_resolution_scale() < 0.99;
5547            let pooled_lease: Option<PooledFrameLease> = {
5548                let Self {
5549                    world,
5550                    renderer,
5551                    snapshots,
5552                    frame_pool,
5553                    ..
5554                } = self;
5555                if use_tsr_upscale {
5556                    renderer.render_world_tsr_into_pool(
5557                        world,
5558                        (vw, vh),
5559                        &quality,
5560                        (frame_pool, next_fence),
5561                    )
5562                } else {
5563                    renderer.render_world_interpolated_into_pool(
5564                        world,
5565                        snapshots,
5566                        alpha,
5567                        (vw, vh),
5568                        &quality,
5569                        (frame_pool, next_fence),
5570                    )
5571                }
5572            };
5573            if let Some(lease) = pooled_lease {
5574                ctx.blit_pooled_frame(dst_rect, &lease);
5575                let cached_ref: PooledFrameRef = lease.to_frame_ref();
5576                lease.submit_in_flight();
5577                let _: usize = self.get_frame_pool().retire_fence(next_fence);
5578                self.set_cached_world_frame(Some(cached_ref));
5579                blitted_pooled = true;
5580            }
5581            if !blitted_pooled {
5582                let frame_img: ImageBuffer = {
5583                    let Self {
5584                        world, renderer, ..
5585                    } = self;
5586                    renderer.render_world(world, vw, vh, &quality)
5587                };
5588                ctx.draw_image(dst_rect, frame_img);
5589            }
5590            #[cfg(not(target_arch = "wasm32"))]
5591            let measured_ms: f32 = (render_started.elapsed().as_nanos() as f32) / 1_000_000.0;
5592            #[cfg(target_arch = "wasm32")]
5593            let measured_ms: f32 = if self.get_smoothed_fps() > 1.0 {
5594                1000.0 / self.get_smoothed_fps()
5595            } else {
5596                16.67
5597            };
5598            self.set_last_render_ms(measured_ms);
5599            self.set_cached_world_rev(world_rev);
5600            self.set_cached_dims((vw, vh));
5601            self.set_cached_quality(quality);
5602            self.set_cached_alpha_milli(alpha_milli);
5603            let hud_rev: u64 = self.get_gpu_target().get_hud_revision();
5604            let target: &mut GpuCompositeTarget = self.get_mut_gpu_target();
5605            target.set_presented_world_revision(world_rev);
5606            target.set_presented_hud_revision(hud_rev);
5607        }
5608        let stats: RenderStats3D = self.get_renderer().get_last_stats();
5609        let fps: f32 = self.get_smoothed_fps();
5610        let exp_val: f32 = self.get_renderer().get_adapted_exposure();
5611        let aa_tag: &str = match quality.get_anti_aliasing() {
5612            AntiAliasingMode::Tsr => HUD_AA_TSR,
5613            AntiAliasingMode::Taa => HUD_AA_TAA,
5614            AntiAliasingMode::Fxaa => HUD_AA_FXAA,
5615            AntiAliasingMode::Off => HUD_AA_OFF,
5616        };
5617        let compact_hud: bool = size.get_width() < 520.0;
5618        let render_ms: f32 = self.get_last_render_ms();
5619        let rays_k: f32 = (stats.get_rays_traced() as f32) * 0.001;
5620        let hud_text: String = if compact_hud {
5621            format!(
5622                "{fps:.0} FPS · {}x{} · {render_ms:.1}ms · {rays_k:.1}k rays",
5623                stats.get_render_width(),
5624                stats.get_render_height(),
5625            )
5626        } else {
5627            format!(
5628                "{fps:.0} FPS · {:?} {aa_tag} · {}x{} · {render_ms:.1}ms · {rays_k:.1}k rays · Reproj {} · Exp {exp_val:.2}",
5629                quality.get_preset(),
5630                stats.get_render_width(),
5631                stats.get_render_height(),
5632                stats.get_probe_reproj_hits(),
5633            )
5634        };
5635        let hud_w: f32 =
5636            ((hud_text.len() as f32) * 5.2 + 20.0).clamp(180.0, size.get_width() - 20.0);
5637        let hud_rect: Rect = Rect::new(10.0, 10.0, hud_w, 26.0);
5638        ctx.fill_rounded_rect(hud_rect, Color::rgba(9, 13, 24, 212), 8.0);
5639        ctx.stroke_rect(hud_rect, 1.0, Color::rgba(148, 163, 184, 72));
5640        ctx.draw_text(Point::new(18.0, 15.5), hud_text, 10.5, Color::hex(0xE2E8F0));
5641    }
5642}