Skip to main content

euv_performance/suite/
fn.rs

1use super::*;
2
3/// Benchmarks fine-grained `Signal` updates propagating through a diamond `Memo` graph.
4///
5/// # Arguments
6///
7/// - `usize` - Number of signal updates to measure.
8///
9/// # Returns
10///
11/// - `BenchMetric` - Measured latency and throughput telemetry.
12#[must_use]
13pub fn bench_reactive_signals_and_memos(iterations: usize) -> BenchMetric {
14    reset_reactive_runtime();
15    let count: usize = iterations.max(1);
16    let source: Signal<i64> = Signal::new(0);
17    let left: Memo<i64> = Memo::new(move || source.get() + 1);
18    let right: Memo<i64> = Memo::new(move || source.get() * 2);
19    let sum: Memo<i64> = Memo::new(move || left.get() + right.get());
20    let start: Instant = Instant::now();
21    let mut checksum: i64 = 0;
22    for i in 1..=(count as i64) {
23        let _: bool = source.set(i);
24        checksum = checksum.wrapping_add(sum.get());
25    }
26    build_metric(
27        BENCH_REACTIVE_NAME,
28        count,
29        start.elapsed(),
30        format!("checksum={checksum}"),
31    )
32}
33
34/// Benchmarks O(1) `Selector<usize>` active-index switching across 1,000 tracked rows.
35///
36/// # Arguments
37///
38/// - `usize` - Number of active-row switches to measure.
39///
40/// # Returns
41///
42/// - `BenchMetric` - Measured latency and throughput telemetry.
43#[must_use]
44pub fn bench_selector_o1(iterations: usize) -> BenchMetric {
45    reset_reactive_runtime();
46    let count: usize = iterations.max(1);
47    let selected: Signal<usize> = Signal::new(0);
48    let selector: Selector<usize> = Selector::new(move || selected.get());
49    let start: Instant = Instant::now();
50    let mut hits: usize = 0;
51    for i in 0..count {
52        let key: usize = i % 1_000;
53        let _: bool = selected.set(key);
54        if selector.is_selected(key) {
55            hits += 1;
56        }
57    }
58    build_metric(
59        BENCH_SELECTOR_NAME,
60        count,
61        start.elapsed(),
62        format!("hits={hits}"),
63    )
64}
65
66/// Benchmarks retained layout engine clean-subtree caching across a 120-node UI tree.
67///
68/// # Arguments
69///
70/// - `usize` - Number of layout passes to measure.
71///
72/// # Returns
73///
74/// - `BenchMetric` - Measured latency and cache-hit telemetry.
75#[must_use]
76pub fn bench_layout_cache(iterations: usize) -> BenchMetric {
77    reset_reactive_runtime();
78    let count: usize = iterations.max(1);
79    let scene: SceneHandle = SceneHandle::new_tree();
80    let ctx: Context = Context::new(scene.clone(), PlatformKind::Headless);
81    let container: NodeId = with_context(ctx, || {
82        view! {
83            column {
84                width: Length::Px(800.0)
85                height: Length::Px(600.0)
86                gap: SPACE_XS
87                for idx in 0..120usize {
88                    row {
89                        width: Length::Percent(100.0)
90                        height: Length::Px(24.0)
91                        text {
92                            { format!("{BENCH_ROW_LABEL} {idx}") }
93                        }
94                    }
95                }
96            }
97        }
98    });
99    scene.with_write(
100        |tree: &mut SceneTree| {
101            let root: NodeId = tree.get_root();
102            tree.replace_children(root, vec![container]);
103        },
104        (),
105    );
106    let mut engine: LayoutEngine = LayoutEngine::default();
107    let viewport: Size = Size::new(800.0, 600.0);
108    let _: LayoutStats = scene.with_write(
109        |tree: &mut SceneTree| engine.compute(tree, viewport),
110        LayoutStats::default(),
111    );
112    let start: Instant = Instant::now();
113    let mut cache_hits: usize = 0;
114    for _ in 0..count {
115        let stats: LayoutStats = scene.with_write(
116            |tree: &mut SceneTree| engine.compute(tree, viewport),
117            LayoutStats::default(),
118        );
119        cache_hits += stats.get_subtrees_skipped();
120    }
121    build_metric(
122        BENCH_LAYOUT_CACHE_NAME,
123        count,
124        start.elapsed(),
125        format!("cache_hits={cache_hits}"),
126    )
127}
128
129/// Benchmarks full 800x600 software SDF tile rasterization frames.
130///
131/// # Arguments
132///
133/// - `usize` - Number of rendered frames to measure.
134///
135/// # Returns
136///
137/// - `BenchMetric` - Measured frame latency, FPS throughput, and pixel hash.
138#[must_use]
139pub fn bench_software_rasterizer(iterations: usize) -> BenchMetric {
140    bench_render_pipeline(BENCH_SW_RASTER_NAME, RenderConfig::software(), iterations)
141}
142
143/// Benchmarks hardware GPU instanced draw-batch compilation frames.
144///
145/// # Arguments
146///
147/// - `usize` - Number of GPU frame submissions to measure.
148///
149/// # Returns
150///
151/// - `BenchMetric` - Measured frame latency, FPS throughput, and batch count.
152#[must_use]
153pub fn bench_hardware_gpu_batching(iterations: usize) -> BenchMetric {
154    bench_render_pipeline(BENCH_HW_BATCH_NAME, RenderConfig::hardware(), iterations)
155}
156
157/// Benchmarks Unicode + CJK glyph rasterization and GPU RGBA8 atlas shelf-packing.
158///
159/// # Arguments
160///
161/// - `usize` - Number of glyph-pack iterations to measure.
162///
163/// # Returns
164///
165/// - `BenchMetric` - Measured latency and packed glyph count.
166#[must_use]
167pub fn bench_unicode_glyph_atlas(iterations: usize) -> BenchMetric {
168    let count: usize = iterations.max(1);
169    let sample_chars: [char; 8] = ['A', 'g', '9', '跨', '端', '原', '生', '框'];
170    let provider: NativeSystemFont = NativeSystemFont::deterministic();
171    let start: Instant = Instant::now();
172    let mut packed_regions: usize = 0;
173    for _ in 0..count {
174        let mut atlas: GlyphAtlas = GlyphAtlas::default();
175        for ch in sample_chars.iter() {
176            let key: GlyphKey = GlyphKey::new(*ch, 160, false);
177            let _: &RasterizedGlyph = atlas.get_or_rasterize_with(key, &provider);
178        }
179        let packed: PackedGlyphAtlas = atlas.pack_rgba_atlas();
180        packed_regions = packed.get_regions().len();
181    }
182    build_metric(
183        BENCH_GLYPH_ATLAS_NAME,
184        count,
185        start.elapsed(),
186        format!("packed_glyphs={packed_regions}"),
187    )
188}
189
190/// Benchmarks full forced-redraw 800x600 software SDF tile rasterization frames.
191///
192/// # Arguments
193///
194/// - `usize` - Number of full raster frames to measure.
195///
196/// # Returns
197///
198/// - `BenchMetric` - Measured full-frame raster latency and FPS throughput.
199#[must_use]
200pub fn bench_software_full_redraw(iterations: usize) -> BenchMetric {
201    reset_reactive_runtime();
202    let count: usize = iterations.max(1);
203    let tokens: ThemeTokens = ThemeTokens::resolve(DesignScheme::Shadcn, ThemeMode::Light);
204    let mut win: WindowConfig = WindowConfig::default();
205    win.set_size(800, 600).set_render(RenderConfig::software());
206    let mut cfg: AppConfig = AppConfig::default();
207    cfg.set_window(win);
208    let Ok(mut app) = App::headless(cfg) else {
209        return build_metric(BENCH_SW_FULL_NAME, count, Duration::ZERO, String::new());
210    };
211    let _: NodeId = app.mount(|| {
212        view! {
213            column {
214                width: Length::Percent(100.0)
215                padding: Edges::all(SPACE_LG)
216                gap: SPACE_MD
217                EuvHeader {
218                    title: BENCH_TITLE.to_string()
219                    subtitle: BENCH_SUBTITLE.to_string()
220                    tokens: tokens
221                }
222                EuvCard {
223                    title: BENCH_TITLE.to_string()
224                    tokens: tokens
225                    subtitle: BENCH_SUBTITLE
226                    EuvBadge {
227                        label: BENCH_BADGE.to_string()
228                        tone: EuvTone::Primary
229                        tokens: tokens
230                    }
231                    EuvProgress {
232                        value: 0.72
233                        tokens: tokens
234                    }
235                }
236            }
237        }
238    });
239    let wid: WindowId = app.get_window_state().get_id();
240    let start: Instant = Instant::now();
241    let mut last_hash: u64 = 0;
242    let mut last_batches: usize = 0;
243    for _ in 0..count {
244        app.dispatch_window_event(WindowEvent::RedrawRequested(wid));
245        if let Ok(stats) = app.step_frame() {
246            last_hash = stats.get_frame_hash();
247            last_batches = stats.get_draw_batches();
248        }
249    }
250    build_metric(
251        BENCH_SW_FULL_NAME,
252        count,
253        start.elapsed(),
254        format!("batches={last_batches} hash={last_hash:#018x}"),
255    )
256}
257
258/// Benchmarks 256 dynamic 2D rigid bodies stepping through spatial-hash broad-phase and narrow-phase collision resolution.
259///
260/// # Arguments
261///
262/// - `usize` - Number of fixed 60Hz physics ticks to measure.
263///
264/// # Returns
265///
266/// - `BenchMetric` - Measured physics tick latency and collision throughput.
267#[must_use]
268pub fn bench_game_ecs_physics(iterations: usize) -> BenchMetric {
269    let count: usize = iterations.max(1);
270    let mut world: GameWorld = GameWorld::with_capacity(256);
271    for idx in 0..256usize {
272        let col: f32 = (idx % 16) as f32;
273        let row: f32 = (idx / 16) as f32;
274        let eid: EntityId = world.spawn(
275            EntityTag::Enemy,
276            Point::new(40.0 + col * 52.0, 40.0 + row * 40.0),
277        );
278        if let Some(ent) = world.get_entity_mut(eid) {
279            ent.set_velocity(Velocity2D::new(
280                if idx % 2 == 0 { 110.0 } else { -95.0 },
281                if idx % 3 == 0 { 85.0 } else { -75.0 },
282                0.0,
283            ));
284            ent.set_body(Some(RigidBody2D::dynamic(1.0, 0.9, 0.02)));
285            ent.set_collider(Some(Collider2D::circle(
286                10.0,
287                COLLISION_LAYER_ENEMY,
288                COLLISION_LAYER_ALL,
289                false,
290            )));
291        }
292    }
293    let mut phys_cfg: PhysicsConfig = PhysicsConfig::default();
294    phys_cfg.set_arena_bounds(Some(Rect::new(0.0, 0.0, 960.0, 720.0)));
295    let mut physics: PhysicsWorld2D = PhysicsWorld2D::with_config(phys_cfg);
296    let start: Instant = Instant::now();
297    let mut total_collisions: usize = 0;
298    for _ in 0..count {
299        let evs: Vec<CollisionEvent> = physics.step(&mut world, 1.0 / 60.0);
300        total_collisions += evs.len();
301    }
302    build_metric(
303        BENCH_GAME_PHYSICS_NAME,
304        count,
305        start.elapsed(),
306        format!("entities=256 collisions={total_collisions}"),
307    )
308}
309
310/// Benchmarks updating 1,024 active zero-allocation pooled particles per frame.
311///
312/// # Arguments
313///
314/// - `usize` - Number of particle update steps to measure.
315///
316/// # Returns
317///
318/// - `BenchMetric` - Measured particle update latency and throughput.
319#[must_use]
320pub fn bench_game_particles(iterations: usize) -> BenchMetric {
321    let count: usize = iterations.max(1);
322    let mut system: ParticleSystem = ParticleSystem::with_capacity(1024);
323    let mut cfg: ParticleEmitterConfig = ParticleEmitterConfig::default();
324    cfg.set_min_life(10.0).set_max_life(20.0);
325    system.emit_burst(Point::new(400.0, 300.0), 1024, cfg);
326    let start: Instant = Instant::now();
327    let mut live: usize = 0;
328    for _ in 0..count {
329        live = system.update(1.0 / 60.0);
330    }
331    build_metric(
332        BENCH_GAME_PARTICLES_NAME,
333        count,
334        start.elapsed(),
335        format!("active_particles={live}"),
336    )
337}
338
339/// Benchmarks the AAA 3D open-world PBR + BVH ray-traced shadows and reflections pipeline.
340///
341/// # Arguments
342///
343/// - `usize` - Number of 3D ray-traced frames to measure.
344///
345/// # Returns
346///
347/// - `BenchMetric` - Measured 3D frame latency, triangle throughput, and BVH ray count.
348#[must_use]
349pub fn bench_game3d_pbr_bvh_raytrace(iterations: usize) -> BenchMetric {
350    let count: usize = iterations.max(1);
351    let mut world: World3D = World3D::create_open_world_city();
352    let mut renderer: Renderer3D = Renderer3D::default();
353    let cfg: RenderQualityConfig = RenderQualityConfig::from_preset(QualityPreset::High);
354    let start: Instant = Instant::now();
355    let mut last_rays: usize = 0;
356    let mut last_tris: usize = 0;
357    for _ in 0..count {
358        let _: ImageBuffer = renderer.render_world(&mut world, 480, 270, &cfg);
359        let st: RenderStats3D = renderer.get_last_stats();
360        last_rays = st.get_rays_traced();
361        last_tris = st.get_triangles_drawn();
362    }
363    build_metric(
364        BENCH_GAME_3D_RT_NAME,
365        count,
366        start.elapsed(),
367        format!("tris={last_tris} rays={last_rays}"),
368    )
369}
370
371/// Benchmarks maxed-out `Cinematic` + `FullPathTracedGi` + `125%` scale 3D ray tracing at HD resolution.
372///
373/// # Arguments
374///
375/// - `usize` - Number of max-settings 3D frames to measure.
376///
377/// # Returns
378///
379/// - `BenchMetric` - Measured frame latency, FPS throughput, resolution, and ray count.
380#[must_use]
381pub fn bench_game3d_cinematic_max_rt(iterations: usize) -> BenchMetric {
382    let count: usize = iterations.max(1);
383    let mut world: World3D = World3D::create_open_world_city();
384    let mut renderer: Renderer3D = Renderer3D::default();
385    let mut cfg: RenderQualityConfig = RenderQualityConfig::from_preset(QualityPreset::Cinematic);
386    cfg.set_ray_tracing(RayTracingMode::FullPathTracedGi)
387        .set_resolution_scale(1.25);
388    let start: Instant = Instant::now();
389    let mut last_rays: usize = 0;
390    let mut last_w: u32 = 0;
391    let mut last_h: u32 = 0;
392    for _ in 0..count {
393        let _: ImageBuffer = renderer.render_world(&mut world, 960, 480, &cfg);
394        let st: RenderStats3D = renderer.get_last_stats();
395        last_rays = st.get_rays_traced();
396        last_w = st.get_render_width();
397        last_h = st.get_render_height();
398    }
399    build_metric(
400        BENCH_GAME_3D_MAX_RT_NAME,
401        count,
402        start.elapsed(),
403        format!("res={last_w}x{last_h} rays={last_rays}"),
404    )
405}
406
407/// Stress-benchmarks continuous scrolling of a 100,000-row `EuvVirtualList` through full layout and software rasterization.
408///
409/// # Arguments
410///
411/// - `usize` - Number of scrolled frames to measure.
412///
413/// # Returns
414///
415/// - `BenchMetric` - Measured frame latency, throughput, and final virtual scroll offset.
416#[must_use]
417pub fn bench_stress_long_list_100k(iterations: usize) -> BenchMetric {
418    reset_reactive_runtime();
419    let count: usize = iterations.max(1);
420    let tokens: ThemeTokens = ThemeTokens::resolve(DesignScheme::Shadcn, ThemeMode::Light);
421    let p: ThemePalette = tokens.get_palette();
422    let g: ThemeGeometry = tokens.get_geometry();
423    let mut win: WindowConfig = WindowConfig::default();
424    win.set_size(400, 720).set_render(RenderConfig::software());
425    let mut cfg: AppConfig = AppConfig::default();
426    cfg.set_window(win);
427    let Ok(mut app) = App::headless(cfg) else {
428        return build_metric(
429            BENCH_STRESS_LONG_LIST_NAME,
430            count,
431            Duration::ZERO,
432            String::new(),
433        );
434    };
435    let scroll_y: Signal<f32> = Signal::new(0.0);
436    let _: NodeId = app.mount(|| {
437        let vlist: EuvVirtualList =
438            EuvVirtualList::new(100_000, 36.0, scroll_y, tokens).viewport_height(680.0);
439        vlist.mount_with(move |idx: usize| {
440            view! {
441                row {
442                    width: Length::Percent(100.0)
443                    height: Length::Px(36.0)
444                    padding: Edges::symmetric(SPACE_XS, SPACE_MD)
445                    align: AlignItems::Center
446                    border: (g.get_border_width(), p.get_border())
447                    text {
448                        font_size: 13.0
449                        color: p.get_foreground()
450                        { format!("{BENCH_ROW_LABEL} #{idx}") }
451                    }
452                }
453            }
454        })
455    });
456    let _: Result<FrameStats, PlatformError> = app.step_frame();
457    let start: Instant = Instant::now();
458    let mut last_shaded: usize = 0;
459    for step in 1..=count {
460        let next_y: f32 = ((step as f32) * 144.0) % 3_500_000.0;
461        let _: bool = scroll_y.set_if_changed(next_y);
462        if let Ok(stats) = app.step_frame() {
463            last_shaded = stats.get_pixels_shaded();
464        }
465    }
466    build_metric(
467        BENCH_STRESS_LONG_LIST_NAME,
468        count,
469        start.elapsed(),
470        format!(
471            "rows=100000 scroll_y={:.0}px shaded={last_shaded}",
472            scroll_y.get_untracked()
473        ),
474    )
475}
476
477/// Stress-benchmarks a deeply nested 2,000-node Flex/Grid layout tree under repeated full and dirty-subtree layout passes.
478///
479/// # Arguments
480///
481/// - `usize` - Number of layout passes to measure.
482///
483/// # Returns
484///
485/// - `BenchMetric` - Measured per-pass layout latency and node count.
486#[must_use]
487pub fn bench_stress_complex_layout_2000(iterations: usize) -> BenchMetric {
488    reset_reactive_runtime();
489    let count: usize = iterations.max(1);
490    let scene: SceneHandle = SceneHandle::new_tree();
491    let ctx: Context = Context::new(scene.clone(), PlatformKind::Headless);
492    let (leaf_nodes, page): (Vec<NodeId>, NodeId) = with_context(ctx, || {
493        let mut leaves: Vec<NodeId> = Vec::with_capacity(50);
494        let mut sections: Vec<NodeId> = Vec::with_capacity(50);
495        for section_idx in 0..50usize {
496            let mut first_title: NodeId = NodeId::default();
497            let grid_node: NodeId = view! {
498                grid {
499                    columns: 4
500                    width: Length::Percent(100.0)
501                    gap: SPACE_SM
502                    for card_idx in 0..8usize {
503                        column {
504                            width: Length::Percent(100.0)
505                            padding: Edges::all(SPACE_SM)
506                            gap: SPACE_XS
507                            row {
508                                width: Length::Percent(100.0)
509                                justify: JustifyContent::SpaceBetween
510                                if card_idx == 0 {
511                                    text {
512                                        node_ref: first_title
513                                        font_size: 13.0
514                                        { format!("{BENCH_CELL_LABEL} {section_idx}-{card_idx}") }
515                                    }
516                                } else {
517                                    text {
518                                        font_size: 13.0
519                                        { format!("{BENCH_CELL_LABEL} {section_idx}-{card_idx}") }
520                                    }
521                                }
522                                text {
523                                    font_size: 11.0
524                                    { format!("{section_idx}") }
525                                }
526                            }
527                        }
528                    }
529                }
530            };
531            leaves.push(first_title);
532            sections.push(grid_node);
533        }
534        let p_node: NodeId = view! {
535            column {
536                width: Length::Px(1280.0)
537                padding: Edges::all(SPACE_MD)
538                gap: SPACE_SM
539                ..sections
540            }
541        };
542        (leaves, p_node)
543    });
544    scene.with_write(
545        |tree: &mut SceneTree| {
546            let root: NodeId = tree.get_root();
547            tree.replace_children(root, vec![page]);
548        },
549        (),
550    );
551    let mut engine: LayoutEngine = LayoutEngine::default();
552    let viewport: Size = Size::new(1280.0, 800.0);
553    let init_stats: LayoutStats = scene.with_write(
554        |tree: &mut SceneTree| engine.compute(tree, viewport),
555        LayoutStats::default(),
556    );
557    let start: Instant = Instant::now();
558    let mut total_computed: usize = 0;
559    let mut total_skipped: usize = 0;
560    for step in 0..count {
561        let target: NodeId = leaf_nodes[step % leaf_nodes.len()];
562        scene.with_write(
563            |tree: &mut SceneTree| {
564                tree.set_text(target, format!("{BENCH_CELL_LABEL} #{step}"));
565                let stats: LayoutStats = engine.compute(tree, viewport);
566                total_computed += stats.get_nodes_computed();
567                total_skipped += stats.get_subtrees_skipped();
568            },
569            (),
570        );
571    }
572    build_metric(
573        BENCH_STRESS_COMPLEX_LAYOUT_NAME,
574        count,
575        start.elapsed(),
576        format!(
577            "initial_nodes={} avg_computed={} avg_skipped={}",
578            init_stats.get_nodes_computed(),
579            total_computed / count,
580            total_skipped / count
581        ),
582    )
583}
584
585/// Stress-benchmarks bulk batched updates across 1,000 live reactive UI components with subscribed signals and memos.
586///
587/// # Arguments
588///
589/// - `usize` - Number of full 1,000-component batch update ticks to measure.
590///
591/// # Returns
592///
593/// - `BenchMetric` - Measured batch update + reactive flush + scene patch latency.
594#[must_use]
595pub fn bench_stress_bulk_reactive_1000(iterations: usize) -> BenchMetric {
596    reset_reactive_runtime();
597    let count: usize = iterations.max(1);
598    let tokens: ThemeTokens = ThemeTokens::resolve(DesignScheme::Shadcn, ThemeMode::Light);
599    let p: ThemePalette = tokens.get_palette();
600    let mut win: WindowConfig = WindowConfig::default();
601    win.set_size(800, 600).set_render(RenderConfig::hardware());
602    let mut cfg: AppConfig = AppConfig::default();
603    cfg.set_window(win);
604    let Ok(mut app) = App::headless(cfg) else {
605        return build_metric(
606            BENCH_STRESS_BULK_REACTIVE_NAME,
607            count,
608            Duration::ZERO,
609            String::new(),
610        );
611    };
612    let mut signals: Vec<Signal<u32>> = Vec::with_capacity(1_000);
613    for idx in 0..1_000u32 {
614        signals.push(Signal::new(idx));
615    }
616    let signals_mount: Vec<Signal<u32>> = signals.clone();
617    let _: NodeId = app.mount(move || {
618        let derived_memos: Vec<Memo<u32>> = signals_mount
619            .into_iter()
620            .map(|sig: Signal<u32>| Memo::new(move || sig.get().wrapping_mul(3).wrapping_add(1)))
621            .collect();
622        view! {
623            scroll {
624                width: Length::Percent(100.0)
625                height: Length::Percent(100.0)
626                gap: 2.0
627                for derived in derived_memos.into_iter() {
628                    text {
629                        font_size: 12.0
630                        color: p.get_foreground()
631                        { move || format!("{BENCH_CELL_LABEL} {}", derived.get()) }
632                    }
633                }
634            }
635        }
636    });
637    let _: Result<FrameStats, PlatformError> = app.step_frame();
638    let start: Instant = Instant::now();
639    let mut last_rev: u64 = 0;
640    for tick in 1..=(count as u32) {
641        batch(|| {
642            for (idx, sig) in signals.iter().enumerate() {
643                let _: bool = sig.set_if_changed(tick.wrapping_add(idx as u32));
644            }
645        });
646        flush_effects();
647        if app.step_frame().is_ok() {
648            last_rev = app.get_last_rendered_revision();
649        }
650    }
651    build_metric(
652        BENCH_STRESS_BULK_REACTIVE_NAME,
653        count,
654        start.elapsed(),
655        format!("components=1000 final_rev={last_rev}"),
656    )
657}
658
659/// Stress-benchmarks end-to-end dynamic `.wasm` binary verification, sandbox execution, hot-swap, and rollback cycles.
660///
661/// # Arguments
662///
663/// - `usize` - Number of v1 -> v2 -> rollback hot-swap cycles to measure.
664///
665/// # Returns
666///
667/// - `BenchMetric` - Measured latency per full dynamic WASM hot-swap cycle.
668#[must_use]
669pub fn bench_stress_wasm_dynamic_hotswap(iterations: usize) -> BenchMetric {
670    reset_reactive_runtime();
671    let count: usize = iterations.max(1);
672    let mut win: WindowConfig = WindowConfig::default();
673    win.set_size(640, 480).set_render(RenderConfig::hardware());
674    let mut cfg: AppConfig = AppConfig::default();
675    cfg.set_window(win);
676    let Ok(mut app) = App::headless(cfg) else {
677        return build_metric(
678            BENCH_STRESS_WASM_LOAD_NAME,
679            count,
680            Duration::ZERO,
681            String::new(),
682        );
683    };
684    let hub: DynamicUpdateHub = app.get_dynamic_hub().clone();
685    let registry: RegistryWasmFetcher = RegistryWasmFetcher::default();
686    let wasm_v1: Vec<u8> = build_partial_widget_wasm(BENCH_WASM_TITLE_V1, 1, 0x2563EB);
687    let wasm_v2: Vec<u8> = build_partial_widget_wasm(BENCH_WASM_TITLE_V2, 2, 0x7C3AED);
688    let csum_v1: u64 = compute_wasm_checksum(&wasm_v1);
689    let csum_v2: u64 = compute_wasm_checksum(&wasm_v2);
690    registry.register(
691        BENCH_WASM_URL_V1.to_string(),
692        wasm_v1,
693        BENCH_WASM_ETAG_V1.to_string(),
694        WasmFaultKind::None,
695    );
696    registry.register(
697        BENCH_WASM_URL_V2.to_string(),
698        wasm_v2,
699        BENCH_WASM_ETAG_V2.to_string(),
700        WasmFaultKind::None,
701    );
702    let manager: WasmDynamicManager =
703        WasmDynamicManager::new(hub.clone(), Rc::new(registry), WasmSandboxConfig::default());
704    let hub_slot: DynamicUpdateHub = hub;
705    let _: NodeId = app.mount(move || {
706        view! {
707            slot {
708                id: BENCH_WASM_SLOT
709                hub: hub_slot
710                text {
711                    font_size: 14.0
712                    { BENCH_TITLE }
713                }
714            }
715        }
716    });
717    let _: Result<FrameStats, PlatformError> = app.step_frame();
718    let start: Instant = Instant::now();
719    let mut completed: usize = 0;
720    for cycle in 0..count {
721        let base_ver: u64 = ((cycle as u64) * 2) + 1;
722        let req_v1: WasmDownloadRequest = WasmDownloadRequest::partial(
723            BENCH_WASM_URL_V1.to_string(),
724            BENCH_WASM_SLOT.to_string(),
725            base_ver,
726        )
727        .with_checksum(csum_v1)
728        .with_allow_downgrade(true);
729        let req_v2: WasmDownloadRequest = WasmDownloadRequest::partial(
730            BENCH_WASM_URL_V2.to_string(),
731            BENCH_WASM_SLOT.to_string(),
732            base_ver + 1,
733        )
734        .with_checksum(csum_v2)
735        .with_allow_downgrade(true);
736        if manager.load_and_mount(req_v1, BENCH_WASM_SIGN_KEY).is_ok()
737            && manager.load_and_mount(req_v2, BENCH_WASM_SIGN_KEY).is_ok()
738            && manager
739                .rollback_partial(BENCH_WASM_SLOT, BENCH_WASM_ROLLBACK_REASON)
740                .is_ok()
741        {
742            let _: Result<FrameStats, PlatformError> = app.step_frame();
743            completed += 1;
744        }
745    }
746    build_metric(
747        BENCH_STRESS_WASM_LOAD_NAME,
748        count,
749        start.elapsed(),
750        format!("cycles={completed} cache={}", manager.cache_len()),
751    )
752}
753
754/// Stress-benchmarks flagship mobile `1440x3168 @ 4.0x` multi-card shadowed UI scrolling in the multi-core software rasterizer.
755///
756/// # Arguments
757///
758/// - `usize` - Number of full scrolled 4x-DPI frames to measure.
759///
760/// # Returns
761///
762/// - `BenchMetric` - Measured frame latency and FPS throughput at `1440x3168`.
763#[must_use]
764pub fn bench_stress_hidpi_4x_1440x3168(iterations: usize) -> BenchMetric {
765    reset_reactive_runtime();
766    let count: usize = iterations.max(1);
767    let tokens: ThemeTokens = ThemeTokens::resolve(DesignScheme::Shadcn, ThemeMode::Light);
768    let mut win: WindowConfig = WindowConfig::default();
769    win.set_size(360, 792).set_render(RenderConfig::software());
770    let mut cfg: AppConfig = AppConfig::default();
771    cfg.set_window(win);
772    let Ok(mut app) = App::headless(cfg) else {
773        return build_metric(
774            BENCH_STRESS_HIDPI_4X_NAME,
775            count,
776            Duration::ZERO,
777            String::new(),
778        );
779    };
780    let mut scroll_id: NodeId = NodeId::default();
781    let _: NodeId = app.mount(|| {
782        view! {
783            scroll {
784                node_ref: scroll_id
785                width: Length::Percent(100.0)
786                height: Length::Percent(100.0)
787                padding: Edges::all(SPACE_MD)
788                gap: SPACE_MD
789                background: tokens.get_palette().get_background()
790                for idx in 0..16usize {
791                    EuvCard {
792                        title: format!("{BENCH_TITLE} #{idx}")
793                        tokens: tokens
794                        subtitle: BENCH_CARD_CAPTION
795                        EuvBadge {
796                            label: BENCH_BADGE.to_string()
797                            tone: EuvTone::Primary
798                            tokens: tokens
799                        }
800                        EuvProgress {
801                            value: ((idx % 9) as f32 + 1.0) * 0.1
802                            tokens: tokens
803                        }
804                    }
805                }
806            }
807        }
808    });
809    app.set_exact_physical_viewport(1440, 3168, 4.0);
810    let _: Result<FrameStats, PlatformError> = app.step_frame();
811    let start: Instant = Instant::now();
812    let mut last_shaded: usize = 0;
813    for step in 1..=count {
814        let offset_y: f32 = ((step as f32) * 18.5) % 800.0;
815        app.get_scene().with_write(
816            |tree: &mut SceneTree| {
817                tree.set_scroll_offset(scroll_id, Point::new(0.0, offset_y));
818            },
819            (),
820        );
821        if let Ok(stats) = app.step_frame() {
822            last_shaded = stats.get_pixels_shaded();
823        }
824    }
825    build_metric(
826        BENCH_STRESS_HIDPI_4X_NAME,
827        count,
828        start.elapsed(),
829        format!("res=1440x3168@4x shaded={last_shaded}"),
830    )
831}
832
833/// Stress-benchmarks 240Hz touch-pan scroll physics, thumb-lift anti-reversal filtering, and 1,000-node scene hit-testing.
834///
835/// # Arguments
836///
837/// - `usize` - Number of 240Hz input/hit-test ticks to measure.
838///
839/// # Returns
840///
841/// - `BenchMetric` - Measured input + hit-test latency and throughput.
842#[must_use]
843pub fn bench_stress_scroll_physics_and_hittest(iterations: usize) -> BenchMetric {
844    reset_reactive_runtime();
845    let count: usize = iterations.max(1);
846    let mut win: WindowConfig = WindowConfig::default();
847    win.set_size(360, 792).set_render(RenderConfig::hardware());
848    let mut cfg: AppConfig = AppConfig::default();
849    cfg.set_window(win);
850    let Ok(mut app) = App::headless(cfg) else {
851        return build_metric(
852            BENCH_STRESS_INPUT_HITTEST_NAME,
853            count,
854            Duration::ZERO,
855            String::new(),
856        );
857    };
858    let _: NodeId = app.mount(|| {
859        view! {
860            scroll {
861                width: Length::Percent(100.0)
862                height: Length::Percent(100.0)
863                gap: 4.0
864                for idx in 0..1_000usize {
865                    row {
866                        width: Length::Percent(100.0)
867                        height: Length::Px(32.0)
868                        cursor: CursorIcon::Pointer
869                        text {
870                            { format!("{BENCH_ROW_LABEL} {idx}") }
871                        }
872                    }
873                }
874            }
875        }
876    });
877    let wid: WindowId = app.get_window_state().get_id();
878    let _: Result<FrameStats, PlatformError> = app.step_game_frame(1.0 / 120.0);
879    let start: Instant = Instant::now();
880    let mut hits: usize = 0;
881    app.dispatch_window_event(WindowEvent::PointerDown(
882        wid,
883        PointerEvent::touch(1, 180.0, 620.0),
884    ));
885    for step in 0..count {
886        let y: f32 = 620.0 - ((step % 48) as f32) * 8.0;
887        app.dispatch_window_event(WindowEvent::PointerMove(
888            wid,
889            PointerEvent::touch(1, 180.0, y),
890        ));
891        let found: bool = app.get_scene().with_read(
892            |tree: &SceneTree| hit_test(tree, Point::new(180.0, 320.0)).is_some(),
893            false,
894        );
895        if found {
896            hits += 1;
897        }
898        if step % 2 == 0 {
899            let _: Result<FrameStats, PlatformError> = app.step_game_frame(1.0 / 240.0);
900        }
901    }
902    app.dispatch_window_event(WindowEvent::PointerUp(
903        wid,
904        PointerEvent::touch(1, 180.0, 240.0),
905    ));
906    build_metric(
907        BENCH_STRESS_INPUT_HITTEST_NAME,
908        count,
909        start.elapsed(),
910        format!("nodes=1000 hits={hits}"),
911    )
912}
913
914/// Benchmarks forced 800x600 software redraw of 12 `Overflow::Hidden` rounded cards with borders, shadows, badges, progress bars, and wrapped text.
915///
916/// # Arguments
917///
918/// - `usize` - Number of full software redraw frames to measure.
919///
920/// # Returns
921///
922/// - `BenchMetric` - Measured frame latency, throughput, and pixel hash.
923#[must_use]
924pub fn bench_software_rounded_clip_cards(iterations: usize) -> BenchMetric {
925    reset_reactive_runtime();
926    let count: usize = iterations.max(1);
927    let tokens: ThemeTokens = ThemeTokens::resolve(DesignScheme::Shadcn, ThemeMode::Light);
928    let p: ThemePalette = tokens.get_palette();
929    let g: ThemeGeometry = tokens.get_geometry();
930    let mut win: WindowConfig = WindowConfig::default();
931    win.set_size(800, 600).set_render(RenderConfig::software());
932    let mut cfg: AppConfig = AppConfig::default();
933    cfg.set_window(win);
934    let Ok(mut app) = App::headless(cfg) else {
935        return build_metric(
936            BENCH_SW_ROUNDED_CLIP_NAME,
937            count,
938            Duration::ZERO,
939            String::new(),
940        );
941    };
942    let _: NodeId = app.mount(|| {
943        view! {
944            grid {
945                columns: 3
946                width: Length::Percent(100.0)
947                height: Length::Percent(100.0)
948                padding: Edges::all(SPACE_SM)
949                gap: SPACE_SM
950                background: p.get_background()
951                for idx in 0..12usize {
952                    column {
953                        width: Length::Percent(100.0)
954                        padding: Edges::all(SPACE_SM)
955                        gap: SPACE_XS
956                        background: p.get_card()
957                        border: (g.get_border_width(), p.get_border())
958                        radius: 16.0
959                        shadow: g.get_shadow_md()
960                        overflow: Overflow::Hidden
961                        row {
962                            width: Length::Percent(100.0)
963                            justify: JustifyContent::SpaceBetween
964                            align: AlignItems::Center
965                            text {
966                                flex_shrink: 1.0
967                                min_width: Length::Px(0.0)
968                                font_size: 13.0
969                                font_weight: FontWeight::SemiBold
970                                color: p.get_card_foreground()
971                                { format!("{BENCH_TITLE} #{idx}") }
972                            }
973                            EuvBadge {
974                                label: BENCH_BADGE.to_string()
975                                tone: if idx % 2 == 0 { EuvTone::Primary } else { EuvTone::Success }
976                                tokens: tokens
977                            }
978                        }
979                        text {
980                            width: Length::Percent(100.0)
981                            font_size: 11.0
982                            color: p.get_muted_foreground()
983                            { BENCH_CARD_WRAP_COPY }
984                        }
985                        EuvProgress {
986                            value: ((idx % 8) as f32 + 1.0) * 0.11
987                            tokens: tokens
988                        }
989                    }
990                }
991            }
992        }
993    });
994    let wid: WindowId = app.get_window_state().get_id();
995    let _: Result<FrameStats, PlatformError> = app.step_frame();
996    let start: Instant = Instant::now();
997    let mut last_hash: u64 = 0;
998    let mut last_shaded: usize = 0;
999    for _ in 0..count {
1000        app.dispatch_window_event(WindowEvent::RedrawRequested(wid));
1001        if let Ok(stats) = app.step_frame() {
1002            last_hash = stats.get_frame_hash();
1003            last_shaded = stats.get_pixels_shaded();
1004        }
1005    }
1006    build_metric(
1007        BENCH_SW_ROUNDED_CLIP_NAME,
1008        count,
1009        start.elapsed(),
1010        format!("cards=12 shaded={last_shaded} hash={last_hash:#018x}"),
1011    )
1012}
1013
1014/// Benchmarks forced 800x600 software redraw of linear gradients, 1:1 & scaled rounded images, sprite regions, circles, thick AA lines, and filled triangles.
1015///
1016/// # Arguments
1017///
1018/// - `usize` - Number of full software redraw frames to measure.
1019///
1020/// # Returns
1021///
1022/// - `BenchMetric` - Measured frame latency, throughput, and pixel hash.
1023#[must_use]
1024pub fn bench_software_primitives_image_vec(iterations: usize) -> BenchMetric {
1025    reset_reactive_runtime();
1026    let count: usize = iterations.max(1);
1027    let mut win: WindowConfig = WindowConfig::default();
1028    win.set_size(800, 600).set_render(RenderConfig::software());
1029    let mut cfg: AppConfig = AppConfig::default();
1030    cfg.set_window(win);
1031    let Ok(mut app) = App::headless(cfg) else {
1032        return build_metric(
1033            BENCH_SW_PRIMITIVES_NAME,
1034            count,
1035            Duration::ZERO,
1036            String::new(),
1037        );
1038    };
1039    let img_opaque: ImageBuffer = build_test_image_buffer(128, 128, 255);
1040    let img_rounded: ImageBuffer = build_test_image_buffer(96, 96, 224);
1041    let sprite_sheet: ImageBuffer = build_test_image_buffer(128, 128, 255);
1042    let img_canvas_opaque: ImageBuffer = img_opaque.clone();
1043    let img_canvas_scaled: ImageBuffer = img_rounded.clone();
1044    let canvas_sprites: ImageBuffer = sprite_sheet;
1045    let _: NodeId = app.mount(move || {
1046        let painter = move |bounds: Rect, dl: &mut DisplayList| {
1047            let bx: f32 = bounds.get_x();
1048            let by: f32 = bounds.get_y();
1049            dl.push(DrawCommand::LinearGradientRect {
1050                rect: Rect::new(bx + 8.0, by + 8.0, 240.0, 110.0),
1051                gradient: LinearGradient::new(
1052                    0.0,
1053                    Color::rgb(37, 99, 235),
1054                    Color::rgb(124, 58, 237),
1055                ),
1056                radius: CornerRadius::all(14.0),
1057            });
1058            dl.push(DrawCommand::LinearGradientRect {
1059                rect: Rect::new(bx + 260.0, by + 8.0, 240.0, 110.0),
1060                gradient: LinearGradient::new(
1061                    45.0,
1062                    Color::rgb(16, 185, 129),
1063                    Color::rgb(14, 165, 233),
1064                ),
1065                radius: CornerRadius::all(14.0),
1066            });
1067            dl.push(DrawCommand::Image {
1068                rect: Rect::new(bx + 516.0, by + 8.0, 128.0, 128.0),
1069                buffer: img_canvas_opaque.clone(),
1070                radius: CornerRadius::all(0.0),
1071            });
1072            dl.push(DrawCommand::Image {
1073                rect: Rect::new(bx + 654.0, by + 8.0, 130.0, 116.0),
1074                buffer: img_canvas_scaled.clone(),
1075                radius: CornerRadius::all(18.0),
1076            });
1077            for idx in 0..8usize {
1078                let fx: f32 = bx + 12.0 + (idx as f32) * 94.0;
1079                let tint: Color = if idx % 2 == 0 {
1080                    Color::rgb(255, 255, 255)
1081                } else {
1082                    Color::rgba(220, 235, 255, 220)
1083                };
1084                dl.push(DrawCommand::SpriteRegion {
1085                    rect: Rect::new(fx, by + 150.0, 76.0, 64.0),
1086                    buffer: canvas_sprites.clone(),
1087                    src_rect: Rect::new(
1088                        ((idx % 4) as f32) * 32.0,
1089                        ((idx / 4) as f32) * 64.0,
1090                        32.0,
1091                        64.0,
1092                    ),
1093                    tint,
1094                });
1095            }
1096            for idx in 0..12usize {
1097                let cx: f32 = bx + 42.0 + (idx as f32) * 62.0;
1098                let cy: f32 = by + 258.0 + ((idx % 2) as f32) * 26.0;
1099                dl.push(DrawCommand::Circle {
1100                    center: Point::new(cx, cy),
1101                    radius: 14.0 + ((idx % 4) as f32) * 4.0,
1102                    color: Color::rgba(59 + ((idx as u8) * 14), 130, 246 - ((idx as u8) * 12), 235),
1103                });
1104            }
1105            for idx in 0..16usize {
1106                let lx: f32 = bx + 16.0 + (idx as f32) * 46.0;
1107                dl.push(DrawCommand::Line {
1108                    from: Point::new(lx, by + 312.0),
1109                    to: Point::new(lx + 72.0, by + 372.0),
1110                    color: Color::rgba(244, 63, 94, 230),
1111                    width: 2.5 + ((idx % 3) as f32) * 1.5,
1112                });
1113            }
1114            for idx in 0..12usize {
1115                let tx: f32 = bx + 18.0 + (idx as f32) * 62.0;
1116                let ty: f32 = by + 392.0;
1117                let (p0, p1, p2): (Point, Point, Point) = if idx % 2 == 0 {
1118                    (
1119                        Point::new(tx, ty + 48.0),
1120                        Point::new(tx + 28.0, ty),
1121                        Point::new(tx + 54.0, ty + 48.0),
1122                    )
1123                } else {
1124                    (
1125                        Point::new(tx, ty),
1126                        Point::new(tx + 54.0, ty),
1127                        Point::new(tx + 27.0, ty + 48.0),
1128                    )
1129                };
1130                dl.push(DrawCommand::Triangle {
1131                    p0,
1132                    p1,
1133                    p2,
1134                    color: Color::rgba(234, 179, 8, 225),
1135                });
1136            }
1137        };
1138        view! {
1139            column {
1140                width: Length::Percent(100.0)
1141                height: Length::Percent(100.0)
1142                padding: Edges::all(SPACE_SM)
1143                gap: SPACE_SM
1144                background: Color::rgb(15, 23, 42)
1145                row {
1146                    width: Length::Percent(100.0)
1147                    height: Length::Px(104.0)
1148                    gap: SPACE_SM
1149                    view {
1150                        flex_grow: 1.0
1151                        height: Length::Percent(100.0)
1152                        gradient: LinearGradient::new(
1153                            0.0,
1154                            Color::rgb(30, 64, 175),
1155                            Color::rgb(15, 23, 42),
1156                        )
1157                        radius: 12.0
1158                    }
1159                    view {
1160                        flex_grow: 1.0
1161                        height: Length::Percent(100.0)
1162                        gradient: LinearGradient::new(
1163                            135.0,
1164                            Color::rgb(168, 85, 247),
1165                            Color::rgb(236, 72, 153),
1166                        )
1167                        radius: 12.0
1168                    }
1169                    image {
1170                        source: img_opaque
1171                        width: Length::Px(96.0)
1172                        height: Length::Px(96.0)
1173                    }
1174                    image {
1175                        source: img_rounded
1176                        width: Length::Px(132.0)
1177                        height: Length::Px(96.0)
1178                        radius: 14.0
1179                    }
1180                }
1181                canvas {
1182                    width: Length::Percent(100.0)
1183                    flex_grow: 1.0
1184                    painter: painter
1185                }
1186            }
1187        }
1188    });
1189    let wid: WindowId = app.get_window_state().get_id();
1190    let _: Result<FrameStats, PlatformError> = app.step_frame();
1191    let start: Instant = Instant::now();
1192    let mut last_hash: u64 = 0;
1193    let mut last_shaded: usize = 0;
1194    for _ in 0..count {
1195        app.dispatch_window_event(WindowEvent::RedrawRequested(wid));
1196        if let Ok(stats) = app.step_frame() {
1197            last_hash = stats.get_frame_hash();
1198            last_shaded = stats.get_pixels_shaded();
1199        }
1200    }
1201    build_metric(
1202        BENCH_SW_PRIMITIVES_NAME,
1203        count,
1204        start.elapsed(),
1205        format!("shaded={last_shaded} hash={last_hash:#018x}"),
1206    )
1207}
1208
1209/// Benchmarks 720x1280@2x software `EuvDrawer` portal slide-in and slide-out animation over 8 shadowed cards.
1210///
1211/// # Arguments
1212///
1213/// - `usize` - Number of 120Hz animated overlay frames to measure.
1214///
1215/// # Returns
1216///
1217/// - `BenchMetric` - Measured portal animation frame latency and throughput.
1218#[must_use]
1219pub fn bench_software_portal_overlay_anim(iterations: usize) -> BenchMetric {
1220    reset_reactive_runtime();
1221    let count: usize = iterations.max(1);
1222    let tokens: ThemeTokens = ThemeTokens::resolve(DesignScheme::Shadcn, ThemeMode::Light);
1223    let p: ThemePalette = tokens.get_palette();
1224    let mut win: WindowConfig = WindowConfig::default();
1225    win.set_size(360, 640).set_render(RenderConfig::software());
1226    let mut cfg: AppConfig = AppConfig::default();
1227    cfg.set_window(win);
1228    let Ok(mut app) = App::headless(cfg) else {
1229        return build_metric(
1230            BENCH_SW_PORTAL_ANIM_NAME,
1231            count,
1232            Duration::ZERO,
1233            String::new(),
1234        );
1235    };
1236    let drawer_open: Signal<bool> = Signal::new(false);
1237    let _: NodeId = app.mount(move || {
1238        let drawer_body: NodeId = view! {
1239            column {
1240                width: Length::Percent(100.0)
1241                gap: SPACE_SM
1242                text {
1243                    width: Length::Percent(100.0)
1244                    font_size: 13.0
1245                    color: p.get_muted_foreground()
1246                    { BENCH_DRAWER_BODY }
1247                }
1248                EuvBadge {
1249                    label: BENCH_BADGE.to_string()
1250                    tone: EuvTone::Primary
1251                    tokens: tokens
1252                }
1253                EuvProgress {
1254                    value: 0.68
1255                    tokens: tokens
1256                }
1257            }
1258        };
1259        view! {
1260            column {
1261                width: Length::Percent(100.0)
1262                height: Length::Percent(100.0)
1263                padding: Edges::all(SPACE_SM)
1264                gap: SPACE_SM
1265                background: p.get_background()
1266                grid {
1267                    columns: 2
1268                    width: Length::Percent(100.0)
1269                    gap: SPACE_SM
1270                    for idx in 0..8usize {
1271                        EuvCard {
1272                            title: format!("{BENCH_TITLE} #{idx}")
1273                            tokens: tokens
1274                            subtitle: BENCH_CARD_CAPTION
1275                            EuvBadge {
1276                                label: BENCH_BADGE.to_string()
1277                                tone: EuvTone::Primary
1278                                tokens: tokens
1279                            }
1280                            EuvProgress {
1281                                value: ((idx % 7) as f32 + 1.0) * 0.12
1282                                tokens: tokens
1283                            }
1284                        }
1285                    }
1286                }
1287                EuvDrawer {
1288                    open: drawer_open
1289                    title: BENCH_DRAWER_TITLE.to_string()
1290                    body: drawer_body
1291                    tokens: tokens
1292                }
1293            }
1294        }
1295    });
1296    app.set_exact_physical_viewport(720, 1280, 2.0);
1297    let _: Result<FrameStats, PlatformError> = app.step_frame();
1298    let toggle_step: usize = (count / 2).max(1);
1299    let start: Instant = Instant::now();
1300    let mut last_hash: u64 = 0;
1301    let mut last_shaded: usize = 0;
1302    let _: bool = drawer_open.set_if_changed(true);
1303    for step in 0..count {
1304        if step == toggle_step && count > 1 {
1305            let _: bool = drawer_open.set_if_changed(false);
1306        }
1307        if let Ok(stats) = app.step_game_frame(1.0 / 120.0) {
1308            last_hash = stats.get_frame_hash();
1309            last_shaded = stats.get_pixels_shaded();
1310        }
1311    }
1312    build_metric(
1313        BENCH_SW_PORTAL_ANIM_NAME,
1314        count,
1315        start.elapsed(),
1316        format!("res=720x1280@2x shaded={last_shaded} hash={last_hash:#018x}"),
1317    )
1318}
1319
1320/// Benchmarks active per-frame dirty mutation through `PaintPass::build` and `HardwareRenderer::render` on every iteration.
1321///
1322/// # Arguments
1323///
1324/// - `usize` - Number of actively mutated hardware frames to measure.
1325///
1326/// # Returns
1327///
1328/// - `BenchMetric` - Measured active hardware batching latency and total draw batches.
1329#[must_use]
1330pub fn bench_hardware_active_batching(iterations: usize) -> BenchMetric {
1331    reset_reactive_runtime();
1332    let count: usize = iterations.max(1);
1333    let tokens: ThemeTokens = ThemeTokens::resolve(DesignScheme::Shadcn, ThemeMode::Light);
1334    let p: ThemePalette = tokens.get_palette();
1335    let mut win: WindowConfig = WindowConfig::default();
1336    win.set_size(800, 600).set_render(RenderConfig::hardware());
1337    let mut cfg: AppConfig = AppConfig::default();
1338    cfg.set_window(win);
1339    let Ok(mut app) = App::headless(cfg) else {
1340        return build_metric(
1341            BENCH_HW_ACTIVE_BATCH_NAME,
1342            count,
1343            Duration::ZERO,
1344            String::new(),
1345        );
1346    };
1347    let mut accent_node: NodeId = NodeId::default();
1348    let _: NodeId = app.mount(|| {
1349        view! {
1350            column {
1351                width: Length::Percent(100.0)
1352                height: Length::Percent(100.0)
1353                padding: Edges::all(SPACE_MD)
1354                gap: SPACE_SM
1355                background: p.get_background()
1356                EuvHeader {
1357                    title: BENCH_TITLE.to_string()
1358                    subtitle: BENCH_SUBTITLE.to_string()
1359                    tokens: tokens
1360                }
1361                view {
1362                    node_ref: accent_node
1363                    width: Length::Percent(100.0)
1364                    height: Length::Px(12.0)
1365                    radius: 6.0
1366                    background: p.get_primary()
1367                }
1368                grid {
1369                    columns: 2
1370                    width: Length::Percent(100.0)
1371                    gap: SPACE_SM
1372                    for idx in 0..8usize {
1373                        EuvCard {
1374                            title: format!("{BENCH_TITLE} #{idx}")
1375                            tokens: tokens
1376                            subtitle: BENCH_SUBTITLE
1377                            EuvBadge {
1378                                label: BENCH_BADGE.to_string()
1379                                tone: EuvTone::Primary
1380                                tokens: tokens
1381                            }
1382                            EuvProgress {
1383                                value: ((idx % 7) as f32 + 1.0) * 0.12
1384                                tokens: tokens
1385                            }
1386                        }
1387                    }
1388                }
1389            }
1390        }
1391    });
1392    let _: Result<FrameStats, PlatformError> = app.step_frame();
1393    let start: Instant = Instant::now();
1394    let mut last_batches: usize = 0;
1395    let mut total_batches: usize = 0;
1396    for step in 0..count {
1397        let next_opacity: f32 = if step % 2 == 0 { 0.85 } else { 1.0 };
1398        app.get_scene().with_write(
1399            |tree: &mut SceneTree| {
1400                if let Some(node) = tree.get_node(accent_node) {
1401                    let mut st: Style = *node.style_ref();
1402                    st.get_mut_paint().set_opacity(next_opacity);
1403                    tree.set_style(accent_node, st);
1404                }
1405            },
1406            (),
1407        );
1408        if let Ok(stats) = app.step_frame() {
1409            last_batches = stats.get_draw_batches();
1410            total_batches += last_batches;
1411        }
1412    }
1413    build_metric(
1414        BENCH_HW_ACTIVE_BATCH_NAME,
1415        count,
1416        start.elapsed(),
1417        format!("batches={last_batches} total_batches={total_batches}"),
1418    )
1419}
1420
1421/// Benchmarks `DeterministicTextMeasurer::measure` and `measure_size` on mixed ASCII/CJK paragraphs alongside hot `GlyphAtlas` hits.
1422///
1423/// # Arguments
1424///
1425/// - `usize` - Number of text measurement and glyph lookup iterations to measure.
1426///
1427/// # Returns
1428///
1429/// - `BenchMetric` - Measured latency, throughput, and checksum.
1430#[must_use]
1431pub fn bench_font_text_wrap_measure_cache(iterations: usize) -> BenchMetric {
1432    let count: usize = iterations.max(1);
1433    let measurer: DeterministicTextMeasurer = DeterministicTextMeasurer;
1434    let style: TextStyle = TextStyle::default();
1435    let mut atlas: GlyphAtlas = GlyphAtlas::default();
1436    let hot_chars: [char; 12] = [
1437        'E', 'u', 'v', 'R', 's', 't', '0', '9', '跨', '端', '原', '生',
1438    ];
1439    let keys: Vec<GlyphKey> = hot_chars
1440        .iter()
1441        .map(|ch: &char| GlyphKey::new(*ch, 140, false))
1442        .collect();
1443    for key in keys.iter().copied() {
1444        let _: &RasterizedGlyph = atlas.get_or_rasterize(key);
1445    }
1446    let start: Instant = Instant::now();
1447    let mut checksum: f32 = 0.0;
1448    for _ in 0..count {
1449        let wrapped: TextLayoutResult = measurer.measure(BENCH_PARA_MIXED_A, style, Some(280.0));
1450        let sz_wrapped: Size = measurer.measure_size(BENCH_PARA_MIXED_B, style, Some(280.0));
1451        let sz_single: Size = measurer.measure_size(BENCH_PARA_SINGLE, style, None);
1452        checksum +=
1453            wrapped.get_size().get_height() + sz_wrapped.get_width() + sz_single.get_width();
1454        for key in keys.iter().copied() {
1455            let glyph: &RasterizedGlyph = atlas.get_or_rasterize(key);
1456            checksum += glyph.get_advance() as f32;
1457        }
1458    }
1459    build_metric(
1460        BENCH_FONT_WRAP_CACHE_NAME,
1461        count,
1462        start.elapsed(),
1463        format!("atlas_glyphs={} checksum={checksum:.0}", atlas.len()),
1464    )
1465}
1466
1467/// Benchmarks fractional `+3.7px` wheel scrolling and active pointer hover moves at 240Hz across a 1,000-row scroll viewport.
1468///
1469/// # Arguments
1470///
1471/// - `usize` - Number of 240Hz fractional scroll ticks to measure.
1472///
1473/// # Returns
1474///
1475/// - `BenchMetric` - Measured smooth-scroll latency and throughput.
1476#[must_use]
1477pub fn bench_app_smooth_scroll_fractional(iterations: usize) -> BenchMetric {
1478    reset_reactive_runtime();
1479    let count: usize = iterations.max(1);
1480    let mut win: WindowConfig = WindowConfig::default();
1481    win.set_size(360, 792).set_render(RenderConfig::hardware());
1482    let mut cfg: AppConfig = AppConfig::default();
1483    cfg.set_window(win);
1484    let Ok(mut app) = App::headless(cfg) else {
1485        return build_metric(
1486            BENCH_APP_SMOOTH_SCROLL_NAME,
1487            count,
1488            Duration::ZERO,
1489            String::new(),
1490        );
1491    };
1492    let _: NodeId = app.mount(|| {
1493        view! {
1494            scroll {
1495                width: Length::Percent(100.0)
1496                height: Length::Percent(100.0)
1497                gap: 4.0
1498                for idx in 0..1_000usize {
1499                    row {
1500                        width: Length::Percent(100.0)
1501                        height: Length::Px(32.0)
1502                        cursor: CursorIcon::Pointer
1503                        text {
1504                            { format!("{BENCH_ROW_LABEL} #{idx}") }
1505                        }
1506                    }
1507                }
1508            }
1509        }
1510    });
1511    let wid: WindowId = app.get_window_state().get_id();
1512    let _: Result<FrameStats, PlatformError> = app.step_game_frame(1.0 / 120.0);
1513    let start: Instant = Instant::now();
1514    let mut total_layout_nodes: usize = 0;
1515    let mut total_batches: usize = 0;
1516    for step in 0..count {
1517        let hover_y: f32 = 120.0 + ((step % 40) as f32) * 8.0;
1518        app.dispatch_window_event(WindowEvent::PointerMove(
1519            wid,
1520            PointerEvent::mouse(180.0, hover_y),
1521        ));
1522        app.dispatch_window_event(WindowEvent::Scroll(wid, Point::new(0.0, 3.7)));
1523        if let Ok(stats) = app.step_game_frame(1.0 / 240.0) {
1524            total_layout_nodes += stats.get_layout_nodes();
1525            total_batches += stats.get_draw_batches();
1526        }
1527    }
1528    build_metric(
1529        BENCH_APP_SMOOTH_SCROLL_NAME,
1530        count,
1531        start.elapsed(),
1532        format!("rows=1000 layout_nodes={total_layout_nodes} batches={total_batches}"),
1533    )
1534}
1535
1536/// Benchmarks parsing, mounting, and disposing a full GFM `EuvMarkdown` document containing a 6x4 table, task list, alert, and 60-line Rust `EuvCodeBlock`.
1537///
1538/// # Arguments
1539///
1540/// - `usize` - Number of mount + dispose cycles to measure.
1541///
1542/// # Returns
1543///
1544/// - `BenchMetric` - Measured Markdown mount latency and scene node count.
1545#[must_use]
1546pub fn bench_ui_markdown_codeblock_mount(iterations: usize) -> BenchMetric {
1547    reset_reactive_runtime();
1548    let count: usize = iterations.max(1);
1549    let tokens: ThemeTokens = ThemeTokens::resolve(DesignScheme::Shadcn, ThemeMode::Dark);
1550    let scene: SceneHandle = SceneHandle::new_tree();
1551    let ctx: Context = Context::new(scene.clone(), PlatformKind::Headless);
1552    let start: Instant = Instant::now();
1553    let mut peak_nodes: usize = 0;
1554    for _ in 0..count {
1555        let (scope, root_node): (Scope, NodeId) = with_context(ctx.clone(), || {
1556            Scope::run(|_: Scope| {
1557                view! {
1558                    EuvMarkdown {
1559                        source: BENCH_MARKDOWN_DOC.to_string()
1560                        tokens: tokens
1561                    }
1562                }
1563            })
1564        });
1565        let live: usize = scene.with_read(|tree: &SceneTree| tree.live_node_count(), 0);
1566        peak_nodes = peak_nodes.max(live);
1567        scope.dispose();
1568        scene.with_write(|tree: &mut SceneTree| tree.dispose_subtree(root_node), ());
1569    }
1570    build_metric(
1571        BENCH_UI_MARKDOWN_MOUNT_NAME,
1572        count,
1573        start.elapsed(),
1574        format!(
1575            "peak_nodes={peak_nodes} doc_bytes={}",
1576            BENCH_MARKDOWN_DOC.len()
1577        ),
1578    )
1579}
1580
1581/// Benchmarks mounting and disposing a ~500-node declarative `view!` tree combining `style!` with `EuvCard`, `EuvButton`, `EuvBadge`, `EuvProgress`, `EuvTag`, and `EuvStatCard`.
1582///
1583/// # Arguments
1584///
1585/// - `usize` - Number of mount + dispose cycles to measure.
1586///
1587/// # Returns
1588///
1589/// - `BenchMetric` - Measured declarative mount latency and live node count per mount.
1590#[must_use]
1591pub fn bench_ui_view_macro_mount_500_nodes(iterations: usize) -> BenchMetric {
1592    reset_reactive_runtime();
1593    let count: usize = iterations.max(1);
1594    let tokens: ThemeTokens = ThemeTokens::resolve(DesignScheme::Shadcn, ThemeMode::Light);
1595    let p: ThemePalette = tokens.get_palette();
1596    let g: ThemeGeometry = tokens.get_geometry();
1597    let scene: SceneHandle = SceneHandle::new_tree();
1598    let ctx: Context = Context::new(scene.clone(), PlatformKind::Headless);
1599    let start: Instant = Instant::now();
1600    let mut nodes_per_mount: usize = 0;
1601    for _ in 0..count {
1602        let (scope, root_node): (Scope, NodeId) = with_context(ctx.clone(), || {
1603            Scope::run(|_: Scope| {
1604                let shell_style: Style = style! {
1605                    FlexDirection::Column
1606                    Overflow::Hidden
1607                    width: Length::Px(1200.0)
1608                    padding: Edges::all(SPACE_MD)
1609                    gap: SPACE_SM
1610                    background: p.get_background()
1611                };
1612                let strip_style: Style = style! {
1613                    FlexDirection::Row
1614                    AlignItems::Center
1615                    gap: SPACE_XS
1616                    width: Length::Percent(100.0)
1617                    border: (g.get_border_width(), p.get_border())
1618                    radius: g.get_radius_sm()
1619                    padding: Edges::all(SPACE_XS)
1620                };
1621                view! {
1622                    view {
1623                        style: shell_style
1624                        for idx in 0..27usize {
1625                            EuvCard {
1626                                title: format!("{BENCH_TITLE} #{idx}")
1627                                tokens: tokens
1628                                subtitle: BENCH_SUBTITLE
1629                                view {
1630                                    style: strip_style
1631                                    EuvButton {
1632                                        label: BENCH_BTN_LABEL.to_string()
1633                                        variant: EuvButtonVariant::Secondary
1634                                        size: EuvButtonSize::Small
1635                                        tokens: tokens
1636                                    }
1637                                    EuvBadge {
1638                                        label: BENCH_BADGE.to_string()
1639                                        tone: EuvTone::Primary
1640                                        tokens: tokens
1641                                    }
1642                                    EuvTag {
1643                                        label: BENCH_TAG_LABEL.to_string()
1644                                        tone: EuvTone::Neutral
1645                                        tokens: tokens
1646                                    }
1647                                }
1648                                EuvProgress {
1649                                    value: ((idx % 9) as f32 + 1.0) * 0.1
1650                                    tokens: tokens
1651                                }
1652                                EuvStatCard {
1653                                    label: BENCH_STAT_LABEL.to_string()
1654                                    value: format!("{}k", idx + 10)
1655                                    caption: BENCH_STAT_CAPTION.to_string()
1656                                    tokens: tokens
1657                                }
1658                            }
1659                        }
1660                    }
1661                }
1662            })
1663        });
1664        nodes_per_mount = scene.with_read(|tree: &SceneTree| tree.live_node_count(), 0);
1665        scope.dispose();
1666        scene.with_write(|tree: &mut SceneTree| tree.dispose_subtree(root_node), ());
1667    }
1668    build_metric(
1669        BENCH_UI_VIEW_MOUNT_500_NAME,
1670        count,
1671        start.elapsed(),
1672        format!("nodes_per_mount={nodes_per_mount}"),
1673    )
1674}
1675
1676/// Benchmarks cycling across 8 `PageRetention::Freeze` routes in `EuvRouter` + `EuvRouterOutlet` paired with `EuvSidebarNav` and `EuvTabs`.
1677///
1678/// # Arguments
1679///
1680/// - `usize` - Number of route switches and frame steps to measure.
1681///
1682/// # Returns
1683///
1684/// - `BenchMetric` - Measured route switch latency and frozen route count.
1685#[must_use]
1686pub fn bench_ui_router_freeze_switch(iterations: usize) -> BenchMetric {
1687    reset_reactive_runtime();
1688    let count: usize = iterations.max(1);
1689    let tokens: ThemeTokens = ThemeTokens::resolve(DesignScheme::Shadcn, ThemeMode::Light);
1690    let mut win: WindowConfig = WindowConfig::default();
1691    win.set_size(800, 600).set_render(RenderConfig::hardware());
1692    let mut cfg: AppConfig = AppConfig::default();
1693    cfg.set_window(win);
1694    let Ok(mut app) = App::headless(cfg) else {
1695        return build_metric(
1696            BENCH_UI_ROUTER_FREEZE_NAME,
1697            count,
1698            Duration::ZERO,
1699            String::new(),
1700        );
1701    };
1702    let mut router: EuvRouter =
1703        EuvRouter::new(BENCH_ROUTE_PATHS[0]).with_default_retention(PageRetention::Freeze);
1704    for idx in 0..BENCH_ROUTE_PATHS.len() {
1705        let route_label: &'static str = BENCH_ROUTE_LABELS[idx];
1706        router = router.route(
1707            BENCH_ROUTE_PATHS[idx],
1708            route_label,
1709            move |_matched: &EuvRouteMatch| {
1710                let counter: Signal<u32> = Signal::new(idx as u32);
1711                let label_text: Box<dyn Fn() -> String> =
1712                    Box::new(move || format!("{route_label} active={}", counter.get()));
1713                view! {
1714                    EuvCard {
1715                        title: route_label.to_string()
1716                        tokens: tokens
1717                        subtitle: BENCH_SUBTITLE
1718                        text {
1719                            width: Length::Percent(100.0)
1720                            font_size: 13.0
1721                            { label_text }
1722                        }
1723                        EuvProgress {
1724                            value: ((idx as f32) + 1.0) * 0.11
1725                            tokens: tokens
1726                        }
1727                    }
1728                }
1729            },
1730        );
1731    }
1732    let active_tab: Signal<usize> = Signal::new(0);
1733    let router_mount: EuvRouter = router.clone();
1734    let _: NodeId = app.mount(move || {
1735        let nav_items: Vec<EuvNavItem> = BENCH_ROUTE_PATHS
1736            .iter()
1737            .zip(BENCH_ROUTE_LABELS.iter())
1738            .map(|(path, label): (&&str, &&str)| {
1739                EuvNavItem::new((*path).to_string(), (*label).to_string())
1740            })
1741            .collect();
1742        let tab_labels: Vec<String> = BENCH_ROUTE_LABELS
1743            .iter()
1744            .map(|label: &&str| (*label).to_string())
1745            .collect();
1746        let outlet: EuvRouterOutlet = router_mount.outlet(|_m: &EuvRouteMatch| {
1747            view! {
1748                text {
1749                    { BENCH_FALLBACK_LABEL }
1750                }
1751            }
1752        });
1753        let outlet_node: NodeId = outlet.mount();
1754        view! {
1755            row {
1756                width: Length::Percent(100.0)
1757                height: Length::Percent(100.0)
1758                padding: Edges::all(SPACE_SM)
1759                gap: SPACE_MD
1760                column {
1761                    width: Length::Px(180.0)
1762                    EuvSidebarNav {
1763                        items: nav_items
1764                        active_route: router_mount.get_current_path()
1765                        tokens: tokens
1766                    }
1767                }
1768                column {
1769                    flex_grow: 1.0
1770                    gap: SPACE_SM
1771                    EuvTabs {
1772                        labels: tab_labels
1773                        active: active_tab
1774                        tokens: tokens
1775                    }
1776                    { outlet_node }
1777                }
1778            }
1779        }
1780    });
1781    let _: Result<FrameStats, PlatformError> = app.step_frame();
1782    let start: Instant = Instant::now();
1783    for step in 0..count {
1784        let idx: usize = (step + 1) % BENCH_ROUTE_PATHS.len();
1785        router.push(BENCH_ROUTE_PATHS[idx]);
1786        let _: bool = active_tab.set_if_changed(idx);
1787        let _: Result<FrameStats, PlatformError> = app.step_frame();
1788    }
1789    build_metric(
1790        BENCH_UI_ROUTER_FREEZE_NAME,
1791        count,
1792        start.elapsed(),
1793        format!(
1794            "routes=8 frozen={} switches={count}",
1795            router.get_frozen_count().get_untracked()
1796        ),
1797    )
1798}
1799
1800/// Benchmarks filter query updates, sort-order toggles, and single-row selection changes on a 120-row by 5-column `EuvDataTable`.
1801///
1802/// # Arguments
1803///
1804/// - `usize` - Number of alternating table mutation + frame steps to measure.
1805///
1806/// # Returns
1807///
1808/// - `BenchMetric` - Measured data table update latency and throughput.
1809#[must_use]
1810pub fn bench_ui_datatable_filter_select(iterations: usize) -> BenchMetric {
1811    reset_reactive_runtime();
1812    let count: usize = iterations.max(1);
1813    let tokens: ThemeTokens = ThemeTokens::resolve(DesignScheme::Shadcn, ThemeMode::Light);
1814    let mut win: WindowConfig = WindowConfig::default();
1815    win.set_size(800, 600).set_render(RenderConfig::hardware());
1816    let mut cfg: AppConfig = AppConfig::default();
1817    cfg.set_window(win);
1818    let Ok(mut app) = App::headless(cfg) else {
1819        return build_metric(
1820            BENCH_UI_DATATABLE_NAME,
1821            count,
1822            Duration::ZERO,
1823            String::new(),
1824        );
1825    };
1826    let headers: Vec<String> = BENCH_TABLE_HEADERS
1827        .iter()
1828        .map(|h: &&str| (*h).to_string())
1829        .collect();
1830    let mut rows: Vec<Vec<String>> = Vec::with_capacity(120);
1831    for idx in 0..120usize {
1832        let team: &'static str = BENCH_TABLE_TEAMS[idx % BENCH_TABLE_TEAMS.len()];
1833        let status: &'static str = BENCH_TABLE_STATUSES[idx % BENCH_TABLE_STATUSES.len()];
1834        rows.push(vec![
1835            format!("{idx:03}"),
1836            format!("{team}-{idx:03}"),
1837            team.to_string(),
1838            format!("{}.{}ms", 1 + (idx % 9), idx % 10),
1839            status.to_string(),
1840        ]);
1841    }
1842    let filter_sig: Signal<String> = Signal::new(String::new());
1843    let sort_sig: Signal<bool> = Signal::new(true);
1844    let selected_sig: Signal<Option<usize>> = Signal::new(None);
1845    let _: NodeId = app.mount(move || {
1846        view! {
1847            scroll {
1848                width: Length::Percent(100.0)
1849                height: Length::Percent(100.0)
1850                padding: Edges::all(SPACE_SM)
1851                EuvDataTable {
1852                    headers: headers
1853                    rows: rows
1854                    filter: filter_sig
1855                    sort_ascending: sort_sig
1856                    selected_row: selected_sig
1857                    tokens: tokens
1858                }
1859            }
1860        }
1861    });
1862    let _: Result<FrameStats, PlatformError> = app.step_frame();
1863    let start: Instant = Instant::now();
1864    for step in 0..count {
1865        match step % 3 {
1866            0 => {
1867                let query: &'static str =
1868                    BENCH_TABLE_FILTERS[(step / 3) % BENCH_TABLE_FILTERS.len()];
1869                let _: bool = filter_sig.set_if_changed(query.to_string());
1870            }
1871            1 => {
1872                let next_sort: bool = !sort_sig.get_untracked();
1873                let _: bool = sort_sig.set_if_changed(next_sort);
1874            }
1875            _ => {
1876                let _: bool = selected_sig.set_if_changed(Some(step % 40));
1877            }
1878        }
1879        let _: Result<FrameStats, PlatformError> = app.step_frame();
1880    }
1881    build_metric(
1882        BENCH_UI_DATATABLE_NAME,
1883        count,
1884        start.elapsed(),
1885        format!("rows=120 cols=5 updates={count}"),
1886    )
1887}
1888
1889/// Runs the complete reproducible benchmark and stress-test suite across reactivity, layout, virtual lists, WASM OTA, high-DPI rendering, input, UI, and game physics.
1890///
1891/// # Returns
1892///
1893/// - `BenchReport` - Aggregated benchmark results.
1894#[must_use]
1895pub fn run_full_benchmark_suite() -> BenchReport {
1896    run_filtered_benchmark_suite(None)
1897}
1898
1899/// Runs the benchmark suite optionally restricted to metrics whose canonical name contains `filter`.
1900///
1901/// # Arguments
1902///
1903/// - `Option<&str>` - Optional case-sensitive substring filter; `None` executes all 27 benchmarks.
1904///
1905/// # Returns
1906///
1907/// - `BenchReport` - Aggregated results for all matching benchmarks.
1908#[must_use]
1909pub fn run_filtered_benchmark_suite(filter: Option<&str>) -> BenchReport {
1910    let entries: [BenchEntry; 27] = [
1911        (BENCH_REACTIVE_NAME, || {
1912            bench_reactive_signals_and_memos(10_000)
1913        }),
1914        (BENCH_SELECTOR_NAME, || bench_selector_o1(10_000)),
1915        (BENCH_LAYOUT_CACHE_NAME, || bench_layout_cache(1_000)),
1916        (BENCH_GLYPH_ATLAS_NAME, || bench_unicode_glyph_atlas(100)),
1917        (BENCH_SW_FULL_NAME, || bench_software_full_redraw(20)),
1918        (BENCH_SW_RASTER_NAME, || bench_software_rasterizer(20)),
1919        (BENCH_HW_BATCH_NAME, || bench_hardware_gpu_batching(200)),
1920        (BENCH_GAME_PHYSICS_NAME, || bench_game_ecs_physics(200)),
1921        (BENCH_GAME_PARTICLES_NAME, || bench_game_particles(1_000)),
1922        (BENCH_GAME_3D_RT_NAME, || bench_game3d_pbr_bvh_raytrace(10)),
1923        (BENCH_GAME_3D_MAX_RT_NAME, || {
1924            bench_game3d_cinematic_max_rt(10)
1925        }),
1926        (BENCH_STRESS_LONG_LIST_NAME, || {
1927            bench_stress_long_list_100k(30)
1928        }),
1929        (BENCH_STRESS_COMPLEX_LAYOUT_NAME, || {
1930            bench_stress_complex_layout_2000(40)
1931        }),
1932        (BENCH_STRESS_BULK_REACTIVE_NAME, || {
1933            bench_stress_bulk_reactive_1000(20)
1934        }),
1935        (BENCH_STRESS_WASM_LOAD_NAME, || {
1936            bench_stress_wasm_dynamic_hotswap(30)
1937        }),
1938        (BENCH_STRESS_HIDPI_4X_NAME, || {
1939            bench_stress_hidpi_4x_1440x3168(15)
1940        }),
1941        (BENCH_STRESS_INPUT_HITTEST_NAME, || {
1942            bench_stress_scroll_physics_and_hittest(240)
1943        }),
1944        (BENCH_SW_ROUNDED_CLIP_NAME, || {
1945            bench_software_rounded_clip_cards(20)
1946        }),
1947        (BENCH_SW_PRIMITIVES_NAME, || {
1948            bench_software_primitives_image_vec(25)
1949        }),
1950        (BENCH_SW_PORTAL_ANIM_NAME, || {
1951            bench_software_portal_overlay_anim(30)
1952        }),
1953        (BENCH_HW_ACTIVE_BATCH_NAME, || {
1954            bench_hardware_active_batching(200)
1955        }),
1956        (BENCH_FONT_WRAP_CACHE_NAME, || {
1957            bench_font_text_wrap_measure_cache(2_000)
1958        }),
1959        (BENCH_APP_SMOOTH_SCROLL_NAME, || {
1960            bench_app_smooth_scroll_fractional(240)
1961        }),
1962        (BENCH_UI_MARKDOWN_MOUNT_NAME, || {
1963            bench_ui_markdown_codeblock_mount(40)
1964        }),
1965        (BENCH_UI_VIEW_MOUNT_500_NAME, || {
1966            bench_ui_view_macro_mount_500_nodes(50)
1967        }),
1968        (BENCH_UI_ROUTER_FREEZE_NAME, || {
1969            bench_ui_router_freeze_switch(100)
1970        }),
1971        (BENCH_UI_DATATABLE_NAME, || {
1972            bench_ui_datatable_filter_select(100)
1973        }),
1974    ];
1975    let mut metrics: Vec<BenchMetric> = Vec::with_capacity(entries.len());
1976    for (name, runner) in entries.iter() {
1977        let selected: bool = filter
1978            .map(|substr: &str| name.contains(substr))
1979            .unwrap_or(true);
1980        if selected {
1981            metrics.push(runner());
1982        }
1983    }
1984    BenchReport::new(metrics)
1985}
1986
1987/// Builds a deterministic RGBA8 test image buffer for image and sprite-sheet raster benchmarks.
1988///
1989/// # Arguments
1990///
1991/// - `u32` - Width in pixels.
1992/// - `u32` - Height in pixels.
1993/// - `u8` - Constant alpha channel value.
1994///
1995/// # Returns
1996///
1997/// - `ImageBuffer` - Populated deterministic RGBA8 pixel buffer.
1998fn build_test_image_buffer(width: u32, height: u32, alpha: u8) -> ImageBuffer {
1999    let pixel_count: usize = (width as usize).saturating_mul(height as usize);
2000    let mut pixels: Vec<u8> = Vec::with_capacity(pixel_count.saturating_mul(4));
2001    for y in 0..height {
2002        for x in 0..width {
2003            pixels.push(((x.wrapping_mul(3) + y) & 0xFF) as u8);
2004            pixels.push(((y.wrapping_mul(3) + x) & 0xFF) as u8);
2005            pixels.push(((x ^ y).wrapping_mul(5) & 0xFF) as u8);
2006            pixels.push(alpha);
2007        }
2008    }
2009    ImageBuffer::new(width, height, pixels)
2010}
2011
2012/// Formats a `BenchReport` into an aligned terminal summary table.
2013///
2014/// # Arguments
2015///
2016/// - `&BenchReport` - Completed benchmark report.
2017///
2018/// # Returns
2019///
2020/// - `String` - Human-readable report table.
2021#[must_use]
2022pub fn format_bench_report(report: &BenchReport) -> String {
2023    let mut out: String = String::from(REPORT_HEADER);
2024    for m in report.get_metrics().iter() {
2025        out.push_str(&format!(
2026            "{:32} iters={:6} avg={:10.1} ns/op  throughput={:10.0} ops/s  {}\n",
2027            m.get_name(),
2028            m.get_iterations(),
2029            m.get_ns_per_op(),
2030            m.get_ops_per_sec(),
2031            m.get_detail()
2032        ));
2033    }
2034    out
2035}
2036
2037/// Serializes a `BenchReport` to formatted JSON.
2038///
2039/// # Arguments
2040///
2041/// - `&BenchReport` - Completed benchmark report.
2042///
2043/// # Returns
2044///
2045/// - `String` - Pretty-printed JSON string.
2046#[must_use]
2047pub fn report_to_json(report: &BenchReport) -> String {
2048    to_string_pretty(report).unwrap_or_default()
2049}
2050
2051/// Shared rendering benchmark harness supporting both Software and Hardware modes.
2052///
2053/// # Arguments
2054///
2055/// - `&str` - Benchmark name.
2056/// - `RenderConfig` - Renderer pipeline configuration.
2057/// - `usize` - Number of frames to step.
2058///
2059/// # Returns
2060///
2061/// - `BenchMetric` - Measured frame telemetry.
2062fn bench_render_pipeline(name: &str, render: RenderConfig, iterations: usize) -> BenchMetric {
2063    reset_reactive_runtime();
2064    let count: usize = iterations.max(1);
2065    let tokens: ThemeTokens = ThemeTokens::resolve(DesignScheme::Shadcn, ThemeMode::Light);
2066    let mut win: WindowConfig = WindowConfig::default();
2067    win.set_size(800, 600).set_render(render);
2068    let mut cfg: AppConfig = AppConfig::default();
2069    cfg.set_window(win);
2070    let Ok(mut app) = App::headless(cfg) else {
2071        return build_metric(name, count, Duration::ZERO, String::new());
2072    };
2073    let _: NodeId = app.mount(|| {
2074        view! {
2075            column {
2076                width: Length::Percent(100.0)
2077                padding: Edges::all(SPACE_LG)
2078                gap: SPACE_MD
2079                EuvHeader {
2080                    title: BENCH_TITLE.to_string()
2081                    subtitle: BENCH_SUBTITLE.to_string()
2082                    tokens: tokens
2083                }
2084                EuvCard {
2085                    title: BENCH_TITLE.to_string()
2086                    tokens: tokens
2087                    subtitle: BENCH_SUBTITLE
2088                    EuvBadge {
2089                        label: BENCH_BADGE.to_string()
2090                        tone: EuvTone::Primary
2091                        tokens: tokens
2092                    }
2093                    EuvProgress {
2094                        value: 0.72
2095                        tokens: tokens
2096                    }
2097                }
2098            }
2099        }
2100    });
2101    let start: Instant = Instant::now();
2102    let mut last_hash: u64 = 0;
2103    let mut last_batches: usize = 0;
2104    for _ in 0..count {
2105        if let Ok(stats) = app.step_frame() {
2106            last_hash = stats.get_frame_hash();
2107            last_batches = stats.get_draw_batches();
2108        }
2109    }
2110    build_metric(
2111        name,
2112        count,
2113        start.elapsed(),
2114        format!("batches={last_batches} hash={last_hash:#018x}"),
2115    )
2116}
2117
2118/// Constructs a `BenchMetric` from elapsed wall time and iteration count.
2119///
2120/// # Arguments
2121///
2122/// - `&str` - Metric name.
2123/// - `usize` - Completed iterations.
2124/// - `Duration` - Total elapsed time.
2125/// - `String` - Extra metadata string.
2126///
2127/// # Returns
2128///
2129/// - `BenchMetric` - Computed timing metric.
2130fn build_metric(name: &str, iterations: usize, elapsed: Duration, detail: String) -> BenchMetric {
2131    let total_nanos: f64 = elapsed.as_nanos().max(1) as f64;
2132    let ns_per_op: f64 = total_nanos / (iterations.max(1) as f64);
2133    let ops_per_sec: f64 = 1_000_000_000.0 / ns_per_op.max(1.0);
2134    BenchMetric::new(
2135        name.to_string(),
2136        iterations,
2137        elapsed.as_micros() as u64,
2138        ns_per_op,
2139        ops_per_sec,
2140        detail,
2141    )
2142}