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(BENCH_TITLE.to_string(), BENCH_SUBTITLE.to_string(), tokens)
218                EuvCard(BENCH_TITLE.to_string(), tokens) {
219                    subtitle: BENCH_SUBTITLE
220                    EuvBadge(BENCH_BADGE.to_string(), EuvTone::Primary, tokens)
221                    EuvProgress(0.72, tokens)
222                }
223            }
224        }
225    });
226    let wid: WindowId = app.get_window_state().get_id();
227    let start: Instant = Instant::now();
228    let mut last_hash: u64 = 0;
229    let mut last_batches: usize = 0;
230    for _ in 0..count {
231        app.dispatch_window_event(WindowEvent::RedrawRequested(wid));
232        if let Ok(stats) = app.step_frame() {
233            last_hash = stats.get_frame_hash();
234            last_batches = stats.get_draw_batches();
235        }
236    }
237    build_metric(
238        BENCH_SW_FULL_NAME,
239        count,
240        start.elapsed(),
241        format!("batches={last_batches} hash={last_hash:#018x}"),
242    )
243}
244
245/// Benchmarks 256 dynamic 2D rigid bodies stepping through spatial-hash broad-phase and narrow-phase collision resolution.
246///
247/// # Arguments
248///
249/// - `usize` - Number of fixed 60Hz physics ticks to measure.
250///
251/// # Returns
252///
253/// - `BenchMetric` - Measured physics tick latency and collision throughput.
254#[must_use]
255pub fn bench_game_ecs_physics(iterations: usize) -> BenchMetric {
256    let count: usize = iterations.max(1);
257    let mut world: GameWorld = GameWorld::with_capacity(256);
258    for idx in 0..256usize {
259        let col: f32 = (idx % 16) as f32;
260        let row: f32 = (idx / 16) as f32;
261        let eid: EntityId = world.spawn(
262            EntityTag::Enemy,
263            Point::new(40.0 + col * 52.0, 40.0 + row * 40.0),
264        );
265        if let Some(ent) = world.get_entity_mut(eid) {
266            ent.set_velocity(Velocity2D::new(
267                if idx % 2 == 0 { 110.0 } else { -95.0 },
268                if idx % 3 == 0 { 85.0 } else { -75.0 },
269                0.0,
270            ));
271            ent.set_body(Some(RigidBody2D::dynamic(1.0, 0.9, 0.02)));
272            ent.set_collider(Some(Collider2D::circle(
273                10.0,
274                COLLISION_LAYER_ENEMY,
275                COLLISION_LAYER_ALL,
276                false,
277            )));
278        }
279    }
280    let mut phys_cfg: PhysicsConfig = PhysicsConfig::default();
281    phys_cfg.set_arena_bounds(Some(Rect::new(0.0, 0.0, 960.0, 720.0)));
282    let mut physics: PhysicsWorld2D = PhysicsWorld2D::with_config(phys_cfg);
283    let start: Instant = Instant::now();
284    let mut total_collisions: usize = 0;
285    for _ in 0..count {
286        let evs: Vec<CollisionEvent> = physics.step(&mut world, 1.0 / 60.0);
287        total_collisions += evs.len();
288    }
289    build_metric(
290        BENCH_GAME_PHYSICS_NAME,
291        count,
292        start.elapsed(),
293        format!("entities=256 collisions={total_collisions}"),
294    )
295}
296
297/// Benchmarks updating 1,024 active zero-allocation pooled particles per frame.
298///
299/// # Arguments
300///
301/// - `usize` - Number of particle update steps to measure.
302///
303/// # Returns
304///
305/// - `BenchMetric` - Measured particle update latency and throughput.
306#[must_use]
307pub fn bench_game_particles(iterations: usize) -> BenchMetric {
308    let count: usize = iterations.max(1);
309    let mut system: ParticleSystem = ParticleSystem::with_capacity(1024);
310    let mut cfg: ParticleEmitterConfig = ParticleEmitterConfig::default();
311    cfg.set_min_life(10.0).set_max_life(20.0);
312    system.emit_burst(Point::new(400.0, 300.0), 1024, cfg);
313    let start: Instant = Instant::now();
314    let mut live: usize = 0;
315    for _ in 0..count {
316        live = system.update(1.0 / 60.0);
317    }
318    build_metric(
319        BENCH_GAME_PARTICLES_NAME,
320        count,
321        start.elapsed(),
322        format!("active_particles={live}"),
323    )
324}
325
326/// Benchmarks the AAA 3D open-world PBR + BVH ray-traced shadows and reflections pipeline.
327///
328/// # Arguments
329///
330/// - `usize` - Number of 3D ray-traced frames to measure.
331///
332/// # Returns
333///
334/// - `BenchMetric` - Measured 3D frame latency, triangle throughput, and BVH ray count.
335#[must_use]
336pub fn bench_game3d_pbr_bvh_raytrace(iterations: usize) -> BenchMetric {
337    let count: usize = iterations.max(1);
338    let mut world: World3D = World3D::create_open_world_city();
339    let mut renderer: Renderer3D = Renderer3D::default();
340    let cfg: RenderQualityConfig = RenderQualityConfig::from_preset(QualityPreset::High);
341    let start: Instant = Instant::now();
342    let mut last_rays: usize = 0;
343    let mut last_tris: usize = 0;
344    for _ in 0..count {
345        let _: ImageBuffer = renderer.render_world(&mut world, 480, 270, &cfg);
346        let st: RenderStats3D = renderer.get_last_stats();
347        last_rays = st.get_rays_traced();
348        last_tris = st.get_triangles_drawn();
349    }
350    build_metric(
351        BENCH_GAME_3D_RT_NAME,
352        count,
353        start.elapsed(),
354        format!("tris={last_tris} rays={last_rays}"),
355    )
356}
357
358/// Benchmarks maxed-out `Cinematic` + `FullPathTracedGi` + `125%` scale 3D ray tracing at HD resolution.
359///
360/// # Arguments
361///
362/// - `usize` - Number of max-settings 3D frames to measure.
363///
364/// # Returns
365///
366/// - `BenchMetric` - Measured frame latency, FPS throughput, resolution, and ray count.
367#[must_use]
368pub fn bench_game3d_cinematic_max_rt(iterations: usize) -> BenchMetric {
369    let count: usize = iterations.max(1);
370    let mut world: World3D = World3D::create_open_world_city();
371    let mut renderer: Renderer3D = Renderer3D::default();
372    let mut cfg: RenderQualityConfig = RenderQualityConfig::from_preset(QualityPreset::Cinematic);
373    cfg.set_ray_tracing(RayTracingMode::FullPathTracedGi)
374        .set_resolution_scale(1.25);
375    let start: Instant = Instant::now();
376    let mut last_rays: usize = 0;
377    let mut last_w: u32 = 0;
378    let mut last_h: u32 = 0;
379    for _ in 0..count {
380        let _: ImageBuffer = renderer.render_world(&mut world, 960, 480, &cfg);
381        let st: RenderStats3D = renderer.get_last_stats();
382        last_rays = st.get_rays_traced();
383        last_w = st.get_render_width();
384        last_h = st.get_render_height();
385    }
386    build_metric(
387        BENCH_GAME_3D_MAX_RT_NAME,
388        count,
389        start.elapsed(),
390        format!("res={last_w}x{last_h} rays={last_rays}"),
391    )
392}
393
394/// Stress-benchmarks continuous scrolling of a 100,000-row `EuvVirtualList` through full layout and software rasterization.
395///
396/// # Arguments
397///
398/// - `usize` - Number of scrolled frames to measure.
399///
400/// # Returns
401///
402/// - `BenchMetric` - Measured frame latency, throughput, and final virtual scroll offset.
403#[must_use]
404pub fn bench_stress_long_list_100k(iterations: usize) -> BenchMetric {
405    reset_reactive_runtime();
406    let count: usize = iterations.max(1);
407    let tokens: ThemeTokens = ThemeTokens::resolve(DesignScheme::Shadcn, ThemeMode::Light);
408    let p: ThemePalette = tokens.get_palette();
409    let g: ThemeGeometry = tokens.get_geometry();
410    let mut win: WindowConfig = WindowConfig::default();
411    win.set_size(400, 720).set_render(RenderConfig::software());
412    let mut cfg: AppConfig = AppConfig::default();
413    cfg.set_window(win);
414    let Ok(mut app) = App::headless(cfg) else {
415        return build_metric(
416            BENCH_STRESS_LONG_LIST_NAME,
417            count,
418            Duration::ZERO,
419            String::new(),
420        );
421    };
422    let scroll_y: Signal<f32> = Signal::new(0.0);
423    let _: NodeId = app.mount(|| {
424        let vlist: EuvVirtualList =
425            EuvVirtualList::new(100_000, 36.0, scroll_y, tokens).viewport_height(680.0);
426        vlist.mount_with(move |idx: usize| {
427            view! {
428                row {
429                    width: Length::Percent(100.0)
430                    height: Length::Px(36.0)
431                    padding: Edges::symmetric(SPACE_XS, SPACE_MD)
432                    align: AlignItems::Center
433                    border: (g.get_border_width(), p.get_border())
434                    text {
435                        font_size: 13.0
436                        color: p.get_foreground()
437                        { format!("{BENCH_ROW_LABEL} #{idx}") }
438                    }
439                }
440            }
441        })
442    });
443    let _: Result<FrameStats, PlatformError> = app.step_frame();
444    let start: Instant = Instant::now();
445    let mut last_shaded: usize = 0;
446    for step in 1..=count {
447        let next_y: f32 = ((step as f32) * 144.0) % 3_500_000.0;
448        let _: bool = scroll_y.set_if_changed(next_y);
449        if let Ok(stats) = app.step_frame() {
450            last_shaded = stats.get_pixels_shaded();
451        }
452    }
453    build_metric(
454        BENCH_STRESS_LONG_LIST_NAME,
455        count,
456        start.elapsed(),
457        format!(
458            "rows=100000 scroll_y={:.0}px shaded={last_shaded}",
459            scroll_y.get_untracked()
460        ),
461    )
462}
463
464/// Stress-benchmarks a deeply nested 2,000-node Flex/Grid layout tree under repeated full and dirty-subtree layout passes.
465///
466/// # Arguments
467///
468/// - `usize` - Number of layout passes to measure.
469///
470/// # Returns
471///
472/// - `BenchMetric` - Measured per-pass layout latency and node count.
473#[must_use]
474pub fn bench_stress_complex_layout_2000(iterations: usize) -> BenchMetric {
475    reset_reactive_runtime();
476    let count: usize = iterations.max(1);
477    let scene: SceneHandle = SceneHandle::new_tree();
478    let ctx: Context = Context::new(scene.clone(), PlatformKind::Headless);
479    let (leaf_nodes, page): (Vec<NodeId>, NodeId) = with_context(ctx, || {
480        let mut leaves: Vec<NodeId> = Vec::with_capacity(50);
481        let mut sections: Vec<NodeId> = Vec::with_capacity(50);
482        for section_idx in 0..50usize {
483            let mut first_title: NodeId = NodeId::default();
484            let grid_node: NodeId = view! {
485                grid {
486                    columns: 4
487                    width: Length::Percent(100.0)
488                    gap: SPACE_SM
489                    for card_idx in 0..8usize {
490                        column {
491                            width: Length::Percent(100.0)
492                            padding: Edges::all(SPACE_SM)
493                            gap: SPACE_XS
494                            row {
495                                width: Length::Percent(100.0)
496                                justify: JustifyContent::SpaceBetween
497                                if card_idx == 0 {
498                                    text {
499                                        node_ref: first_title
500                                        font_size: 13.0
501                                        { format!("{BENCH_CELL_LABEL} {section_idx}-{card_idx}") }
502                                    }
503                                } else {
504                                    text {
505                                        font_size: 13.0
506                                        { format!("{BENCH_CELL_LABEL} {section_idx}-{card_idx}") }
507                                    }
508                                }
509                                text {
510                                    font_size: 11.0
511                                    { format!("{section_idx}") }
512                                }
513                            }
514                        }
515                    }
516                }
517            };
518            leaves.push(first_title);
519            sections.push(grid_node);
520        }
521        let p_node: NodeId = view! {
522            column {
523                width: Length::Px(1280.0)
524                padding: Edges::all(SPACE_MD)
525                gap: SPACE_SM
526                ..sections
527            }
528        };
529        (leaves, p_node)
530    });
531    scene.with_write(
532        |tree: &mut SceneTree| {
533            let root: NodeId = tree.get_root();
534            tree.replace_children(root, vec![page]);
535        },
536        (),
537    );
538    let mut engine: LayoutEngine = LayoutEngine::default();
539    let viewport: Size = Size::new(1280.0, 800.0);
540    let init_stats: LayoutStats = scene.with_write(
541        |tree: &mut SceneTree| engine.compute(tree, viewport),
542        LayoutStats::default(),
543    );
544    let start: Instant = Instant::now();
545    let mut total_computed: usize = 0;
546    let mut total_skipped: usize = 0;
547    for step in 0..count {
548        let target: NodeId = leaf_nodes[step % leaf_nodes.len()];
549        scene.with_write(
550            |tree: &mut SceneTree| {
551                tree.set_text(target, format!("{BENCH_CELL_LABEL} #{step}"));
552                let stats: LayoutStats = engine.compute(tree, viewport);
553                total_computed += stats.get_nodes_computed();
554                total_skipped += stats.get_subtrees_skipped();
555            },
556            (),
557        );
558    }
559    build_metric(
560        BENCH_STRESS_COMPLEX_LAYOUT_NAME,
561        count,
562        start.elapsed(),
563        format!(
564            "initial_nodes={} avg_computed={} avg_skipped={}",
565            init_stats.get_nodes_computed(),
566            total_computed / count,
567            total_skipped / count
568        ),
569    )
570}
571
572/// Stress-benchmarks bulk batched updates across 1,000 live reactive UI components with subscribed signals and memos.
573///
574/// # Arguments
575///
576/// - `usize` - Number of full 1,000-component batch update ticks to measure.
577///
578/// # Returns
579///
580/// - `BenchMetric` - Measured batch update + reactive flush + scene patch latency.
581#[must_use]
582pub fn bench_stress_bulk_reactive_1000(iterations: usize) -> BenchMetric {
583    reset_reactive_runtime();
584    let count: usize = iterations.max(1);
585    let tokens: ThemeTokens = ThemeTokens::resolve(DesignScheme::Shadcn, ThemeMode::Light);
586    let p: ThemePalette = tokens.get_palette();
587    let mut win: WindowConfig = WindowConfig::default();
588    win.set_size(800, 600).set_render(RenderConfig::hardware());
589    let mut cfg: AppConfig = AppConfig::default();
590    cfg.set_window(win);
591    let Ok(mut app) = App::headless(cfg) else {
592        return build_metric(
593            BENCH_STRESS_BULK_REACTIVE_NAME,
594            count,
595            Duration::ZERO,
596            String::new(),
597        );
598    };
599    let mut signals: Vec<Signal<u32>> = Vec::with_capacity(1_000);
600    for idx in 0..1_000u32 {
601        signals.push(Signal::new(idx));
602    }
603    let signals_mount: Vec<Signal<u32>> = signals.clone();
604    let _: NodeId = app.mount(move || {
605        let derived_memos: Vec<Memo<u32>> = signals_mount
606            .into_iter()
607            .map(|sig: Signal<u32>| Memo::new(move || sig.get().wrapping_mul(3).wrapping_add(1)))
608            .collect();
609        view! {
610            scroll {
611                width: Length::Percent(100.0)
612                height: Length::Percent(100.0)
613                gap: 2.0
614                for derived in derived_memos.into_iter() {
615                    text {
616                        font_size: 12.0
617                        color: p.get_foreground()
618                        { move || format!("{BENCH_CELL_LABEL} {}", derived.get()) }
619                    }
620                }
621            }
622        }
623    });
624    let _: Result<FrameStats, PlatformError> = app.step_frame();
625    let start: Instant = Instant::now();
626    let mut last_rev: u64 = 0;
627    for tick in 1..=(count as u32) {
628        batch(|| {
629            for (idx, sig) in signals.iter().enumerate() {
630                let _: bool = sig.set_if_changed(tick.wrapping_add(idx as u32));
631            }
632        });
633        flush_effects();
634        if app.step_frame().is_ok() {
635            last_rev = app.get_last_rendered_revision();
636        }
637    }
638    build_metric(
639        BENCH_STRESS_BULK_REACTIVE_NAME,
640        count,
641        start.elapsed(),
642        format!("components=1000 final_rev={last_rev}"),
643    )
644}
645
646/// Stress-benchmarks end-to-end dynamic `.wasm` binary verification, sandbox execution, hot-swap, and rollback cycles.
647///
648/// # Arguments
649///
650/// - `usize` - Number of v1 -> v2 -> rollback hot-swap cycles to measure.
651///
652/// # Returns
653///
654/// - `BenchMetric` - Measured latency per full dynamic WASM hot-swap cycle.
655#[must_use]
656pub fn bench_stress_wasm_dynamic_hotswap(iterations: usize) -> BenchMetric {
657    reset_reactive_runtime();
658    let count: usize = iterations.max(1);
659    let mut win: WindowConfig = WindowConfig::default();
660    win.set_size(640, 480).set_render(RenderConfig::hardware());
661    let mut cfg: AppConfig = AppConfig::default();
662    cfg.set_window(win);
663    let Ok(mut app) = App::headless(cfg) else {
664        return build_metric(
665            BENCH_STRESS_WASM_LOAD_NAME,
666            count,
667            Duration::ZERO,
668            String::new(),
669        );
670    };
671    let hub: DynamicUpdateHub = app.get_dynamic_hub().clone();
672    let registry: RegistryWasmFetcher = RegistryWasmFetcher::default();
673    let wasm_v1: Vec<u8> = build_partial_widget_wasm(BENCH_WASM_TITLE_V1, 1, 0x2563EB);
674    let wasm_v2: Vec<u8> = build_partial_widget_wasm(BENCH_WASM_TITLE_V2, 2, 0x7C3AED);
675    let csum_v1: u64 = compute_wasm_checksum(&wasm_v1);
676    let csum_v2: u64 = compute_wasm_checksum(&wasm_v2);
677    registry.register(
678        BENCH_WASM_URL_V1.to_string(),
679        wasm_v1,
680        BENCH_WASM_ETAG_V1.to_string(),
681        WasmFaultKind::None,
682    );
683    registry.register(
684        BENCH_WASM_URL_V2.to_string(),
685        wasm_v2,
686        BENCH_WASM_ETAG_V2.to_string(),
687        WasmFaultKind::None,
688    );
689    let manager: WasmDynamicManager =
690        WasmDynamicManager::new(hub.clone(), Rc::new(registry), WasmSandboxConfig::default());
691    let hub_slot: DynamicUpdateHub = hub;
692    let _: NodeId = app.mount(move || {
693        view! {
694            slot {
695                id: BENCH_WASM_SLOT
696                hub: hub_slot
697                text {
698                    font_size: 14.0
699                    { BENCH_TITLE }
700                }
701            }
702        }
703    });
704    let _: Result<FrameStats, PlatformError> = app.step_frame();
705    let start: Instant = Instant::now();
706    let mut completed: usize = 0;
707    for cycle in 0..count {
708        let base_ver: u64 = ((cycle as u64) * 2) + 1;
709        let req_v1: WasmDownloadRequest = WasmDownloadRequest::partial(
710            BENCH_WASM_URL_V1.to_string(),
711            BENCH_WASM_SLOT.to_string(),
712            base_ver,
713        )
714        .with_checksum(csum_v1)
715        .with_allow_downgrade(true);
716        let req_v2: WasmDownloadRequest = WasmDownloadRequest::partial(
717            BENCH_WASM_URL_V2.to_string(),
718            BENCH_WASM_SLOT.to_string(),
719            base_ver + 1,
720        )
721        .with_checksum(csum_v2)
722        .with_allow_downgrade(true);
723        if manager.load_and_mount(req_v1, BENCH_WASM_SIGN_KEY).is_ok()
724            && manager.load_and_mount(req_v2, BENCH_WASM_SIGN_KEY).is_ok()
725            && manager
726                .rollback_partial(BENCH_WASM_SLOT, BENCH_WASM_ROLLBACK_REASON)
727                .is_ok()
728        {
729            let _: Result<FrameStats, PlatformError> = app.step_frame();
730            completed += 1;
731        }
732    }
733    build_metric(
734        BENCH_STRESS_WASM_LOAD_NAME,
735        count,
736        start.elapsed(),
737        format!("cycles={completed} cache={}", manager.cache_len()),
738    )
739}
740
741/// Stress-benchmarks flagship mobile `1440x3168 @ 4.0x` multi-card shadowed UI scrolling in the multi-core software rasterizer.
742///
743/// # Arguments
744///
745/// - `usize` - Number of full scrolled 4x-DPI frames to measure.
746///
747/// # Returns
748///
749/// - `BenchMetric` - Measured frame latency and FPS throughput at `1440x3168`.
750#[must_use]
751pub fn bench_stress_hidpi_4x_1440x3168(iterations: usize) -> BenchMetric {
752    reset_reactive_runtime();
753    let count: usize = iterations.max(1);
754    let tokens: ThemeTokens = ThemeTokens::resolve(DesignScheme::Shadcn, ThemeMode::Light);
755    let mut win: WindowConfig = WindowConfig::default();
756    win.set_size(360, 792).set_render(RenderConfig::software());
757    let mut cfg: AppConfig = AppConfig::default();
758    cfg.set_window(win);
759    let Ok(mut app) = App::headless(cfg) else {
760        return build_metric(
761            BENCH_STRESS_HIDPI_4X_NAME,
762            count,
763            Duration::ZERO,
764            String::new(),
765        );
766    };
767    let mut scroll_id: NodeId = NodeId::default();
768    let _: NodeId = app.mount(|| {
769        view! {
770            scroll {
771                node_ref: scroll_id
772                width: Length::Percent(100.0)
773                height: Length::Percent(100.0)
774                padding: Edges::all(SPACE_MD)
775                gap: SPACE_MD
776                background: tokens.get_palette().get_background()
777                for idx in 0..16usize {
778                    EuvCard(format!("{BENCH_TITLE} #{idx}"), tokens) {
779                        subtitle: BENCH_CARD_CAPTION
780                        EuvBadge(BENCH_BADGE.to_string(), EuvTone::Primary, tokens)
781                        EuvProgress(((idx % 9) as f32 + 1.0) * 0.1, tokens)
782                    }
783                }
784            }
785        }
786    });
787    app.set_exact_physical_viewport(1440, 3168, 4.0);
788    let _: Result<FrameStats, PlatformError> = app.step_frame();
789    let start: Instant = Instant::now();
790    let mut last_shaded: usize = 0;
791    for step in 1..=count {
792        let offset_y: f32 = ((step as f32) * 18.5) % 800.0;
793        app.get_scene().with_write(
794            |tree: &mut SceneTree| {
795                tree.set_scroll_offset(scroll_id, Point::new(0.0, offset_y));
796            },
797            (),
798        );
799        if let Ok(stats) = app.step_frame() {
800            last_shaded = stats.get_pixels_shaded();
801        }
802    }
803    build_metric(
804        BENCH_STRESS_HIDPI_4X_NAME,
805        count,
806        start.elapsed(),
807        format!("res=1440x3168@4x shaded={last_shaded}"),
808    )
809}
810
811/// Stress-benchmarks 240Hz touch-pan scroll physics, thumb-lift anti-reversal filtering, and 1,000-node scene hit-testing.
812///
813/// # Arguments
814///
815/// - `usize` - Number of 240Hz input/hit-test ticks to measure.
816///
817/// # Returns
818///
819/// - `BenchMetric` - Measured input + hit-test latency and throughput.
820#[must_use]
821pub fn bench_stress_scroll_physics_and_hittest(iterations: usize) -> BenchMetric {
822    reset_reactive_runtime();
823    let count: usize = iterations.max(1);
824    let mut win: WindowConfig = WindowConfig::default();
825    win.set_size(360, 792).set_render(RenderConfig::hardware());
826    let mut cfg: AppConfig = AppConfig::default();
827    cfg.set_window(win);
828    let Ok(mut app) = App::headless(cfg) else {
829        return build_metric(
830            BENCH_STRESS_INPUT_HITTEST_NAME,
831            count,
832            Duration::ZERO,
833            String::new(),
834        );
835    };
836    let _: NodeId = app.mount(|| {
837        view! {
838            scroll {
839                width: Length::Percent(100.0)
840                height: Length::Percent(100.0)
841                gap: 4.0
842                for idx in 0..1_000usize {
843                    row {
844                        width: Length::Percent(100.0)
845                        height: Length::Px(32.0)
846                        cursor: CursorIcon::Pointer
847                        text {
848                            { format!("{BENCH_ROW_LABEL} {idx}") }
849                        }
850                    }
851                }
852            }
853        }
854    });
855    let wid: WindowId = app.get_window_state().get_id();
856    let _: Result<FrameStats, PlatformError> = app.step_game_frame(1.0 / 120.0);
857    let start: Instant = Instant::now();
858    let mut hits: usize = 0;
859    app.dispatch_window_event(WindowEvent::PointerDown(
860        wid,
861        PointerEvent::touch(1, 180.0, 620.0),
862    ));
863    for step in 0..count {
864        let y: f32 = 620.0 - ((step % 48) as f32) * 8.0;
865        app.dispatch_window_event(WindowEvent::PointerMove(
866            wid,
867            PointerEvent::touch(1, 180.0, y),
868        ));
869        let found: bool = app.get_scene().with_read(
870            |tree: &SceneTree| hit_test(tree, Point::new(180.0, 320.0)).is_some(),
871            false,
872        );
873        if found {
874            hits += 1;
875        }
876        if step % 2 == 0 {
877            let _: Result<FrameStats, PlatformError> = app.step_game_frame(1.0 / 240.0);
878        }
879    }
880    app.dispatch_window_event(WindowEvent::PointerUp(
881        wid,
882        PointerEvent::touch(1, 180.0, 240.0),
883    ));
884    build_metric(
885        BENCH_STRESS_INPUT_HITTEST_NAME,
886        count,
887        start.elapsed(),
888        format!("nodes=1000 hits={hits}"),
889    )
890}
891
892/// Runs the complete reproducible benchmark and stress-test suite across reactivity, layout, virtual lists, WASM OTA, high-DPI rendering, input, and game physics.
893///
894/// # Returns
895///
896/// - `BenchReport` - Aggregated benchmark results.
897#[must_use]
898pub fn run_full_benchmark_suite() -> BenchReport {
899    let metrics: Vec<BenchMetric> = vec![
900        bench_reactive_signals_and_memos(10_000),
901        bench_selector_o1(10_000),
902        bench_layout_cache(1_000),
903        bench_unicode_glyph_atlas(100),
904        bench_software_full_redraw(20),
905        bench_software_rasterizer(20),
906        bench_hardware_gpu_batching(200),
907        bench_game_ecs_physics(200),
908        bench_game_particles(1_000),
909        bench_game3d_pbr_bvh_raytrace(10),
910        bench_game3d_cinematic_max_rt(10),
911        bench_stress_long_list_100k(30),
912        bench_stress_complex_layout_2000(40),
913        bench_stress_bulk_reactive_1000(20),
914        bench_stress_wasm_dynamic_hotswap(30),
915        bench_stress_hidpi_4x_1440x3168(15),
916        bench_stress_scroll_physics_and_hittest(240),
917    ];
918    BenchReport::new(metrics)
919}
920
921/// Formats a `BenchReport` into an aligned terminal summary table.
922///
923/// # Arguments
924///
925/// - `&BenchReport` - Completed benchmark report.
926///
927/// # Returns
928///
929/// - `String` - Human-readable report table.
930#[must_use]
931pub fn format_bench_report(report: &BenchReport) -> String {
932    let mut out: String = String::from(REPORT_HEADER);
933    for m in report.get_metrics().iter() {
934        out.push_str(&format!(
935            "{:32} iters={:6} avg={:10.1} ns/op  throughput={:10.0} ops/s  {}\n",
936            m.get_name(),
937            m.get_iterations(),
938            m.get_ns_per_op(),
939            m.get_ops_per_sec(),
940            m.get_detail()
941        ));
942    }
943    out
944}
945
946/// Serializes a `BenchReport` to formatted JSON.
947///
948/// # Arguments
949///
950/// - `&BenchReport` - Completed benchmark report.
951///
952/// # Returns
953///
954/// - `String` - Pretty-printed JSON string.
955#[must_use]
956pub fn report_to_json(report: &BenchReport) -> String {
957    to_string_pretty(report).unwrap_or_default()
958}
959
960/// Shared rendering benchmark harness supporting both Software and Hardware modes.
961///
962/// # Arguments
963///
964/// - `&str` - Benchmark name.
965/// - `RenderConfig` - Renderer pipeline configuration.
966/// - `usize` - Number of frames to step.
967///
968/// # Returns
969///
970/// - `BenchMetric` - Measured frame telemetry.
971fn bench_render_pipeline(name: &str, render: RenderConfig, iterations: usize) -> BenchMetric {
972    reset_reactive_runtime();
973    let count: usize = iterations.max(1);
974    let tokens: ThemeTokens = ThemeTokens::resolve(DesignScheme::Shadcn, ThemeMode::Light);
975    let mut win: WindowConfig = WindowConfig::default();
976    win.set_size(800, 600).set_render(render);
977    let mut cfg: AppConfig = AppConfig::default();
978    cfg.set_window(win);
979    let Ok(mut app) = App::headless(cfg) else {
980        return build_metric(name, count, Duration::ZERO, String::new());
981    };
982    let _: NodeId = app.mount(|| {
983        view! {
984            column {
985                width: Length::Percent(100.0)
986                padding: Edges::all(SPACE_LG)
987                gap: SPACE_MD
988                EuvHeader(BENCH_TITLE.to_string(), BENCH_SUBTITLE.to_string(), tokens)
989                EuvCard(BENCH_TITLE.to_string(), tokens) {
990                    subtitle: BENCH_SUBTITLE
991                    EuvBadge(BENCH_BADGE.to_string(), EuvTone::Primary, tokens)
992                    EuvProgress(0.72, tokens)
993                }
994            }
995        }
996    });
997    let start: Instant = Instant::now();
998    let mut last_hash: u64 = 0;
999    let mut last_batches: usize = 0;
1000    for _ in 0..count {
1001        if let Ok(stats) = app.step_frame() {
1002            last_hash = stats.get_frame_hash();
1003            last_batches = stats.get_draw_batches();
1004        }
1005    }
1006    build_metric(
1007        name,
1008        count,
1009        start.elapsed(),
1010        format!("batches={last_batches} hash={last_hash:#018x}"),
1011    )
1012}
1013
1014/// Constructs a `BenchMetric` from elapsed wall time and iteration count.
1015///
1016/// # Arguments
1017///
1018/// - `&str` - Metric name.
1019/// - `usize` - Completed iterations.
1020/// - `Duration` - Total elapsed time.
1021/// - `String` - Extra metadata string.
1022///
1023/// # Returns
1024///
1025/// - `BenchMetric` - Computed timing metric.
1026fn build_metric(name: &str, iterations: usize, elapsed: Duration, detail: String) -> BenchMetric {
1027    let total_nanos: f64 = elapsed.as_nanos().max(1) as f64;
1028    let ns_per_op: f64 = total_nanos / (iterations.max(1) as f64);
1029    let ops_per_sec: f64 = 1_000_000_000.0 / ns_per_op.max(1.0);
1030    BenchMetric::new(
1031        name.to_string(),
1032        iterations,
1033        elapsed.as_micros() as u64,
1034        ns_per_op,
1035        ops_per_sec,
1036        detail,
1037    )
1038}