1use super::*;
2
3#[cfg(not(target_arch = "wasm32"))]
13fn measure_ms<F>(work: F) -> f64
14where
15 F: FnOnce(),
16{
17 let start: Instant = Instant::now();
18 work();
19 start.elapsed().as_secs_f64() * 1000.0
20}
21
22#[cfg(target_arch = "wasm32")]
32fn measure_ms<F>(work: F) -> f64
33where
34 F: FnOnce(),
35{
36 let perf: Option<Performance> = window().and_then(|w: Window| w.performance());
37 let t0: f64 = perf.as_ref().map(Performance::now).unwrap_or(0.0);
38 work();
39 let t1: f64 = perf.as_ref().map(Performance::now).unwrap_or(t0);
40 (t1 - t0).max(0.0)
41}
42
43fn summarize_samples(samples: &[f64]) -> (f64, f64, f64) {
53 if samples.is_empty() {
54 return (0.0, 0.0, 0.0);
55 }
56 let mut sorted: Vec<f64> = samples.to_vec();
57 sorted.sort_by(f64::total_cmp);
58 let sum: f64 = sorted.iter().copied().sum();
59 let len: usize = sorted.len();
60 let avg: f64 = sum / (len as f64);
61 let p95_idx: usize = ((len * 95) / 100).min(len - 1);
62 let p95: f64 = sorted[p95_idx];
63 let max: f64 = sorted[len - 1];
64 (avg, p95, max)
65}
66
67fn format_rate(avg_ms: f64, is_fps: bool) -> String {
78 let rate: f64 = if avg_ms > 0.0001 {
79 1000.0 / avg_ms
80 } else {
81 999_999.0
82 };
83 if is_fps {
84 format!("{rate:.0} FPS")
85 } else {
86 format!("{rate:.0} ops/s")
87 }
88}
89
90fn make_idle_case(
105 id: &str,
106 title: &str,
107 category: &str,
108 description: &str,
109 button_label: &str,
110 budget_ms: f64,
111) -> StressCaseResult {
112 StressCaseResult {
113 id: id.to_string(),
114 title: title.to_string(),
115 category: category.to_string(),
116 description: description.to_string(),
117 button_label: button_label.to_string(),
118 status: STRESS_STATUS_IDLE.to_string(),
119 budget_ms,
120 iterations: 0,
121 avg_ms: 0.0,
122 p95_ms: 0.0,
123 max_ms: 0.0,
124 throughput: STRESS_UNIT_NA.to_string(),
125 details: STRESS_UNIT_NA.to_string(),
126 runs: 0,
127 }
128}
129
130#[must_use]
136pub fn default_stress_results() -> Vec<StressCaseResult> {
137 vec![
138 make_idle_case(
139 STRESS_ID_VLIST_100K,
140 STRESS_TITLE_VLIST,
141 STRESS_CAT_LIST,
142 STRESS_DESC_VLIST,
143 STRESS_BTN_VLIST,
144 8.33,
145 ),
146 make_idle_case(
147 STRESS_ID_LAYOUT_2000,
148 STRESS_TITLE_LAYOUT,
149 STRESS_CAT_LAYOUT,
150 STRESS_DESC_LAYOUT,
151 STRESS_BTN_LAYOUT,
152 2.0,
153 ),
154 make_idle_case(
155 STRESS_ID_REACTIVE_1000,
156 STRESS_TITLE_REACTIVE,
157 STRESS_CAT_REACTIVE,
158 STRESS_DESC_REACTIVE,
159 STRESS_BTN_REACTIVE,
160 6.0,
161 ),
162 make_idle_case(
163 STRESS_ID_WASM_HOTSWAP,
164 STRESS_TITLE_WASM,
165 STRESS_CAT_WASM,
166 STRESS_DESC_WASM,
167 STRESS_BTN_WASM,
168 5.0,
169 ),
170 make_idle_case(
171 STRESS_ID_DRAWER_ANIM,
172 STRESS_TITLE_ANIM,
173 STRESS_CAT_ANIM,
174 STRESS_DESC_ANIM,
175 STRESS_BTN_ANIM,
176 8.33,
177 ),
178 make_idle_case(
179 STRESS_ID_TOUCH_HITTEST,
180 STRESS_TITLE_TOUCH,
181 STRESS_CAT_INPUT,
182 STRESS_DESC_TOUCH,
183 STRESS_BTN_TOUCH,
184 1.5,
185 ),
186 make_idle_case(
187 STRESS_ID_HIDPI_SHADOW,
188 STRESS_TITLE_HIDPI,
189 STRESS_CAT_RASTER,
190 STRESS_DESC_HIDPI,
191 STRESS_BTN_HIDPI,
192 16.67,
193 ),
194 make_idle_case(
195 STRESS_ID_CJK_ATLAS,
196 STRESS_TITLE_CJK,
197 STRESS_CAT_TEXT,
198 STRESS_DESC_CJK,
199 STRESS_BTN_CJK,
200 4.0,
201 ),
202 make_idle_case(
203 STRESS_ID_GAME_2D_3D,
204 STRESS_TITLE_GAME,
205 STRESS_CAT_ENGINE,
206 STRESS_DESC_GAME,
207 STRESS_BTN_GAME,
208 16.67,
209 ),
210 make_idle_case(
211 STRESS_ID_MACRO_MOUNT,
212 STRESS_TITLE_MACRO,
213 STRESS_CAT_MACRO,
214 STRESS_DESC_MACRO,
215 STRESS_BTN_MACRO,
216 6.0,
217 ),
218 ]
219}
220
221fn finalize_case(entry: &mut StressCaseResult, samples: &[f64], is_fps: bool, details: String) {
230 let (avg_ms, p95_ms, max_ms): (f64, f64, f64) = summarize_samples(samples);
231 let pass: bool = avg_ms <= entry.get_budget_ms();
232 let status: String = if pass {
233 STRESS_STATUS_PASS.to_string()
234 } else {
235 STRESS_STATUS_WARN.to_string()
236 };
237 let next_runs: u32 = entry.get_runs().saturating_add(1);
238 entry
239 .set_status(status)
240 .set_iterations(samples.len())
241 .set_avg_ms(avg_ms)
242 .set_p95_ms(p95_ms)
243 .set_max_ms(max_ms)
244 .set_throughput(format_rate(avg_ms, is_fps))
245 .set_details(details)
246 .set_runs(next_runs);
247}
248
249fn run_stress_vlist_100k(entry: &mut StressCaseResult) {
255 let (scope, (samples, details)): (Scope, (Vec<f64>, String)) = Scope::run(|_: Scope| {
256 let tokens: ThemeTokens = ThemeTokens::resolve(DesignScheme::Shadcn, ThemeMode::Light);
257 let p: ThemePalette = tokens.get_palette();
258 let g: ThemeGeometry = tokens.get_geometry();
259 let mut win: WindowConfig = WindowConfig::default();
260 win.set_size(360, 640).set_render(RenderConfig::software());
261 let mut cfg: AppConfig = AppConfig::default();
262 cfg.set_window(win);
263 let Ok(mut app) = App::headless(cfg) else {
264 return (Vec::new(), STRESS_UNIT_NA.to_string());
265 };
266 let scroll_y: Signal<f32> = Signal::new(0.0);
267 let _: NodeId = app.mount(|| {
268 let vlist: EuvVirtualList =
269 EuvVirtualList::new(100_000, 36.0, scroll_y, tokens).viewport_height(600.0);
270 vlist.mount_with(move |idx: usize| {
271 view! {
272 row {
273 width: Length::Percent(100.0)
274 height: Length::Px(36.0)
275 padding: Edges::symmetric(SPACE_XS, SPACE_MD)
276 align: AlignItems::Center
277 border: (g.get_border_width(), p.get_border())
278 text {
279 font_size: 13.0
280 color: p.get_foreground()
281 { format!("{STRESS_ROW_PREFIX} #{idx}") }
282 }
283 }
284 }
285 })
286 });
287 let _: Result<FrameStats, PlatformError> = app.step_frame();
288 let mut samples: Vec<f64> = Vec::with_capacity(24);
289 let mut last_shaded: usize = 0;
290 let mut mounted_nodes: usize = 0;
291 for step in 1..=24usize {
292 let next_y: f32 = ((step as f32) * 144.0) % 3_500_000.0;
293 let dt: f64 = measure_ms(|| {
294 let _: bool = scroll_y.set_if_changed(next_y);
295 if let Ok(stats) = app.step_frame() {
296 last_shaded = stats.get_pixels_shaded();
297 }
298 });
299 samples.push(dt);
300 }
301 mounted_nodes = app.get_scene().with_read(
302 |tree: &SceneTree| {
303 tree.get_nodes()
304 .iter()
305 .filter(|n: &&SceneNode| n.get_alive())
306 .count()
307 },
308 mounted_nodes,
309 );
310 let info: String = format!(
311 "rows=100k mounted_nodes={mounted_nodes} scroll={:.0}px shaded={last_shaded}",
312 scroll_y.get_untracked()
313 );
314 (samples, info)
315 });
316 scope.dispose();
317 finalize_case(entry, &samples, true, details);
318}
319
320fn run_stress_layout_2000(entry: &mut StressCaseResult) {
326 let scene: SceneHandle = SceneHandle::new_tree();
327 let ctx: Context = Context::new(scene.clone(), PlatformKind::Headless);
328 let (leaf_nodes, page): (Vec<NodeId>, NodeId) = with_context(ctx, || {
329 let mut leaves: Vec<NodeId> = Vec::with_capacity(50);
330 let mut sections: Vec<NodeId> = Vec::with_capacity(50);
331 for section_idx in 0..50usize {
332 let mut first_title: NodeId = NodeId::default();
333 let grid_node: NodeId = view! {
334 grid {
335 columns: 4
336 width: Length::Percent(100.0)
337 gap: SPACE_SM
338 for card_idx in 0..8usize {
339 column {
340 width: Length::Percent(100.0)
341 padding: Edges::all(SPACE_SM)
342 gap: SPACE_XS
343 row {
344 width: Length::Percent(100.0)
345 justify: JustifyContent::SpaceBetween
346 if card_idx == 0 {
347 text {
348 node_ref: first_title
349 font_size: 13.0
350 { format!("{STRESS_CELL_PREFIX} {section_idx}-{card_idx}") }
351 }
352 } else {
353 text {
354 font_size: 13.0
355 { format!("{STRESS_CELL_PREFIX} {section_idx}-{card_idx}") }
356 }
357 }
358 text {
359 font_size: 11.0
360 { format!("{section_idx}") }
361 }
362 }
363 }
364 }
365 }
366 };
367 leaves.push(first_title);
368 sections.push(grid_node);
369 }
370 let p_node: NodeId = view! {
371 column {
372 width: Length::Px(1280.0)
373 padding: Edges::all(SPACE_MD)
374 gap: SPACE_SM
375 ..sections
376 }
377 };
378 (leaves, p_node)
379 });
380 scene.with_write(
381 |tree: &mut SceneTree| {
382 let root: NodeId = tree.get_root();
383 tree.replace_children(root, vec![page]);
384 },
385 (),
386 );
387 let mut engine: LayoutEngine = LayoutEngine::default();
388 let viewport: Size = Size::new(1280.0, 800.0);
389 let mut init_nodes: usize = 0;
390 let init_ms: f64 = measure_ms(|| {
391 let st: LayoutStats = scene.with_write(
392 |tree: &mut SceneTree| engine.compute(tree, viewport),
393 LayoutStats::default(),
394 );
395 init_nodes = st.get_nodes_computed();
396 });
397 let mut samples: Vec<f64> = Vec::with_capacity(40);
398 let mut total_computed: usize = 0;
399 let mut total_skipped: usize = 0;
400 for step in 0..40usize {
401 let target: NodeId = leaf_nodes[step % leaf_nodes.len()];
402 let dt: f64 = measure_ms(|| {
403 scene.with_write(
404 |tree: &mut SceneTree| {
405 tree.set_text(target, format!("{STRESS_CELL_PREFIX} #{step}"));
406 let stats: LayoutStats = engine.compute(tree, viewport);
407 total_computed += stats.get_nodes_computed();
408 total_skipped += stats.get_subtrees_skipped();
409 },
410 (),
411 );
412 });
413 samples.push(dt);
414 }
415 let details: String = format!(
416 "nodes={init_nodes} init={init_ms:.2}ms avg_recomputed={} skipped={}",
417 total_computed / 40,
418 total_skipped / 40
419 );
420 finalize_case(entry, &samples, false, details);
421}
422
423fn run_stress_reactive_1000(entry: &mut StressCaseResult) {
429 let (scope, (samples, details)): (Scope, (Vec<f64>, String)) = Scope::run(|_: Scope| {
430 let tokens: ThemeTokens = ThemeTokens::resolve(DesignScheme::Shadcn, ThemeMode::Light);
431 let p: ThemePalette = tokens.get_palette();
432 let mut win: WindowConfig = WindowConfig::default();
433 win.set_size(800, 600).set_render(RenderConfig::hardware());
434 let mut cfg: AppConfig = AppConfig::default();
435 cfg.set_window(win);
436 let Ok(mut app) = App::headless(cfg) else {
437 return (Vec::new(), STRESS_UNIT_NA.to_string());
438 };
439 let mut signals: Vec<Signal<u32>> = Vec::with_capacity(1_000);
440 for idx in 0..1_000u32 {
441 signals.push(Signal::new(idx));
442 }
443 let signals_mount: Vec<Signal<u32>> = signals.clone();
444 let _: NodeId = app.mount(move || {
445 let derived_memos: Vec<Memo<u32>> = signals_mount
446 .into_iter()
447 .map(|sig: Signal<u32>| {
448 Memo::new(move || sig.get().wrapping_mul(3).wrapping_add(1))
449 })
450 .collect();
451 view! {
452 scroll {
453 width: Length::Percent(100.0)
454 height: Length::Percent(100.0)
455 gap: 2.0
456 for derived in derived_memos.into_iter() {
457 text {
458 font_size: 12.0
459 color: p.get_foreground()
460 { move || format!("{STRESS_CELL_PREFIX} {}", derived.get()) }
461 }
462 }
463 }
464 }
465 });
466 let _: Result<FrameStats, PlatformError> = app.step_frame();
467 let mut samples: Vec<f64> = Vec::with_capacity(16);
468 let mut last_rev: u64 = 0;
469 for tick in 1..=16u32 {
470 let dt: f64 = measure_ms(|| {
471 batch(|| {
472 for (idx, sig) in signals.iter().enumerate() {
473 let _: bool = sig.set_if_changed(tick.wrapping_add(idx as u32));
474 }
475 });
476 flush_effects();
477 if app.step_frame().is_ok() {
478 last_rev = app.get_last_rendered_revision();
479 }
480 });
481 samples.push(dt);
482 }
483 let info: String = format!("signals=1000 memos=1000 rev={last_rev}");
484 (samples, info)
485 });
486 scope.dispose();
487 finalize_case(entry, &samples, false, details);
488}
489
490fn run_stress_wasm_hotswap(entry: &mut StressCaseResult) {
496 let (scope, (samples, details)): (Scope, (Vec<f64>, String)) = Scope::run(|_: Scope| {
497 let mut win: WindowConfig = WindowConfig::default();
498 win.set_size(640, 480).set_render(RenderConfig::hardware());
499 let mut cfg: AppConfig = AppConfig::default();
500 cfg.set_window(win);
501 let Ok(mut app) = App::headless(cfg) else {
502 return (Vec::new(), STRESS_UNIT_NA.to_string());
503 };
504 let hub: DynamicUpdateHub = app.get_dynamic_hub().clone();
505 let registry: RegistryWasmFetcher = RegistryWasmFetcher::default();
506 let wasm_v1: Vec<u8> = build_partial_widget_wasm(STRESS_WASM_TITLE_V1, 1, 0x2563EB);
507 let wasm_v2: Vec<u8> = build_partial_widget_wasm(STRESS_WASM_TITLE_V2, 2, 0x7C3AED);
508 let csum_v1: u64 = compute_wasm_checksum(&wasm_v1);
509 let csum_v2: u64 = compute_wasm_checksum(&wasm_v2);
510 registry.register(
511 STRESS_WASM_URL_V1.to_string(),
512 wasm_v1,
513 STRESS_WASM_ETAG_V1.to_string(),
514 WasmFaultKind::None,
515 );
516 registry.register(
517 STRESS_WASM_URL_V2.to_string(),
518 wasm_v2,
519 STRESS_WASM_ETAG_V2.to_string(),
520 WasmFaultKind::None,
521 );
522 let manager: WasmDynamicManager =
523 WasmDynamicManager::new(hub.clone(), Rc::new(registry), WasmSandboxConfig::default());
524 let hub_slot: DynamicUpdateHub = hub;
525 let _: NodeId = app.mount(move || {
526 view! {
527 slot {
528 id: STRESS_WASM_SLOT
529 hub: hub_slot
530 text {
531 font_size: 14.0
532 { STRESS_WASM_FALLBACK }
533 }
534 }
535 }
536 });
537 let _: Result<FrameStats, PlatformError> = app.step_frame();
538 let mut samples: Vec<f64> = Vec::with_capacity(12);
539 let mut completed: usize = 0;
540 for cycle in 0..12usize {
541 let base_ver: u64 = ((cycle as u64) * 2) + 1;
542 let dt: f64 = measure_ms(|| {
543 let req_v1: WasmDownloadRequest = WasmDownloadRequest::partial(
544 STRESS_WASM_URL_V1.to_string(),
545 STRESS_WASM_SLOT.to_string(),
546 base_ver,
547 )
548 .with_checksum(csum_v1)
549 .with_allow_downgrade(true);
550 let req_v2: WasmDownloadRequest = WasmDownloadRequest::partial(
551 STRESS_WASM_URL_V2.to_string(),
552 STRESS_WASM_SLOT.to_string(),
553 base_ver + 1,
554 )
555 .with_checksum(csum_v2)
556 .with_allow_downgrade(true);
557 if manager.load_and_mount(req_v1, STRESS_WASM_KEY).is_ok()
558 && manager.load_and_mount(req_v2, STRESS_WASM_KEY).is_ok()
559 && manager
560 .rollback_partial(STRESS_WASM_SLOT, STRESS_WASM_RB_REASON)
561 .is_ok()
562 {
563 let _: Result<FrameStats, PlatformError> = app.step_frame();
564 completed += 1;
565 }
566 });
567 samples.push(dt);
568 }
569 let info: String = format!("cycles={completed}/12 cache={}", manager.cache_len());
570 (samples, info)
571 });
572 scope.dispose();
573 finalize_case(entry, &samples, false, details);
574}
575
576fn run_stress_drawer_anim(entry: &mut StressCaseResult) {
582 let (scope, (samples, details)): (Scope, (Vec<f64>, String)) = Scope::run(|_: Scope| {
583 let tokens: ThemeTokens = ThemeTokens::resolve(DesignScheme::Shadcn, ThemeMode::Light);
584 let p: ThemePalette = tokens.get_palette();
585 let mut win: WindowConfig = WindowConfig::default();
586 win.set_size(360, 780).set_render(RenderConfig::software());
587 let mut cfg: AppConfig = AppConfig::default();
588 cfg.set_window(win);
589 let Ok(mut app) = App::headless(cfg) else {
590 return (Vec::new(), STRESS_UNIT_NA.to_string());
591 };
592 let drawer_open: Signal<bool> = Signal::new(false);
593 let _: NodeId = app.mount(|| {
594 let drawer_body: NodeId = view! {
595 column {
596 width: Length::Percent(100.0)
597 gap: SPACE_SM
598 for idx in 0..8usize {
599 text {
600 font_size: 14.0
601 color: p.get_foreground()
602 { format!("{STRESS_DRAWER_ITEM} {idx}") }
603 }
604 }
605 }
606 };
607 view! {
608 column {
609 width: Length::Percent(100.0)
610 height: Length::Percent(100.0)
611 padding: Edges::all(SPACE_MD)
612 gap: SPACE_MD
613 background: p.get_background()
614 for idx in 0..6usize {
615 EuvCard {
616 title: format!("{STRESS_CARD_PREFIX} #{idx}")
617 tokens: tokens
618 subtitle: STRESS_CARD_SUB
619 EuvBadge {
620 label: STRESS_BADGE_TXT.to_string()
621 tone: EuvTone::Primary
622 tokens: tokens
623 }
624 }
625 }
626 EuvDrawer {
627 open: drawer_open
628 title: STRESS_DRAWER_TITLE.to_string()
629 body: drawer_body
630 tokens: tokens
631 }
632 }
633 }
634 });
635 app.set_exact_physical_viewport(720, 1560, 2.0);
636 let _: Result<FrameStats, PlatformError> = app.step_frame();
637 let _: bool = drawer_open.set_if_changed(true);
638 let mut samples: Vec<f64> = Vec::with_capacity(30);
639 let mut active_frames: usize = 0;
640 for step in 0..30usize {
641 if step == 16 {
642 let _: bool = drawer_open.set_if_changed(false);
643 }
644 let dt: f64 = measure_ms(|| {
645 if app.step_game_frame(1.0 / 120.0).is_ok() && app.has_active_animations() {
646 active_frames += 1;
647 }
648 });
649 samples.push(dt);
650 }
651 let info: String = format!("720x1560@2x anim_frames={active_frames} backdrop_cache=on");
652 (samples, info)
653 });
654 scope.dispose();
655 finalize_case(entry, &samples, true, details);
656}
657
658fn run_stress_touch_hittest(entry: &mut StressCaseResult) {
664 let (scope, (samples, details)): (Scope, (Vec<f64>, String)) = Scope::run(|_: Scope| {
665 let tokens: ThemeTokens = ThemeTokens::resolve(DesignScheme::Shadcn, ThemeMode::Light);
666 let p: ThemePalette = tokens.get_palette();
667 let mut win: WindowConfig = WindowConfig::default();
668 win.set_size(400, 800).set_render(RenderConfig::hardware());
669 let mut cfg: AppConfig = AppConfig::default();
670 cfg.set_window(win);
671 let Ok(mut app) = App::headless(cfg) else {
672 return (Vec::new(), STRESS_UNIT_NA.to_string());
673 };
674 let mut scroll_id: NodeId = NodeId::default();
675 let _: NodeId = app.mount(|| {
676 view! {
677 scroll {
678 node_ref: scroll_id
679 width: Length::Percent(100.0)
680 height: Length::Percent(100.0)
681 gap: SPACE_XS
682 padding: Edges::all(SPACE_SM)
683 for idx in 0..250usize {
684 row {
685 width: Length::Percent(100.0)
686 height: Length::Px(32.0)
687 gap: SPACE_XS
688 text { font_size: 12.0 color: p.get_foreground() { format!("{STRESS_ROW_PREFIX} {idx}") } }
689 text { font_size: 11.0 color: p.get_muted_foreground() { STRESS_BADGE_TXT } }
690 text { font_size: 11.0 color: p.get_primary() { format!("#{idx}") } }
691 }
692 }
693 }
694 }
695 });
696 let _: Result<FrameStats, PlatformError> = app.step_frame();
697 let wid: WindowId = app.get_window_state().get_id();
698 app.dispatch_window_event(WindowEvent::PointerDown(
699 wid,
700 PointerEvent::touch(99, 200.0, 400.0),
701 ));
702 app.dispatch_window_event(WindowEvent::PointerMove(
703 wid,
704 PointerEvent::touch(99, 204.0, 406.0),
705 ));
706 app.dispatch_window_event(WindowEvent::PointerUp(
707 wid,
708 PointerEvent::touch(99, 204.0, 406.0),
709 ));
710 let _: Result<FrameStats, PlatformError> = app.step_frame();
711 let tap_drift: f32 = app.get_scene().with_read(
712 |tree: &SceneTree| {
713 tree.get_node(scroll_id)
714 .map(|n: &SceneNode| n.get_layout_box().get_scroll_offset().get_y())
715 .unwrap_or(0.0)
716 },
717 0.0,
718 );
719 let mut samples: Vec<f64> = Vec::with_capacity(120);
720 for step in 0..120usize {
721 let y: f32 = 120.0 + ((step * 19) % 580) as f32;
722 let dt: f64 = measure_ms(|| {
723 app.dispatch_window_event(WindowEvent::PointerMove(
724 wid,
725 PointerEvent::mouse(200.0, y),
726 ));
727 app.dispatch_window_event(WindowEvent::Scroll(wid, Point::new(0.0, 14.0)));
728 let _: Result<FrameStats, PlatformError> = app.step_game_frame(1.0 / 240.0);
729 });
730 samples.push(dt);
731 }
732 let final_scroll: f32 = app.get_scene().with_read(
733 |tree: &SceneTree| {
734 tree.get_node(scroll_id)
735 .map(|n: &SceneNode| n.get_layout_box().get_scroll_offset().get_y())
736 .unwrap_or(0.0)
737 },
738 0.0,
739 );
740 let info: String =
741 format!("nodes=1000 tap_drift={tap_drift:.2}px scrolled={final_scroll:.0}px");
742 (samples, info)
743 });
744 scope.dispose();
745 finalize_case(entry, &samples, false, details);
746}
747
748fn run_stress_hidpi_shadow(entry: &mut StressCaseResult) {
754 let (scope, (samples, details)): (Scope, (Vec<f64>, String)) = Scope::run(|_: Scope| {
755 let tokens: ThemeTokens = ThemeTokens::resolve(DesignScheme::Shadcn, ThemeMode::Light);
756 let mut win: WindowConfig = WindowConfig::default();
757 win.set_size(360, 640).set_render(RenderConfig::software());
758 let mut cfg: AppConfig = AppConfig::default();
759 cfg.set_window(win);
760 let Ok(mut app) = App::headless(cfg) else {
761 return (Vec::new(), STRESS_UNIT_NA.to_string());
762 };
763 let mut scroll_id: NodeId = NodeId::default();
764 let _: NodeId = app.mount(|| {
765 view! {
766 scroll {
767 node_ref: scroll_id
768 width: Length::Percent(100.0)
769 height: Length::Percent(100.0)
770 padding: Edges::all(SPACE_MD)
771 gap: SPACE_MD
772 background: tokens.get_palette().get_background()
773 for idx in 0..12usize {
774 EuvCard {
775 title: format!("{STRESS_CARD_PREFIX} #{idx}")
776 tokens: tokens
777 subtitle: STRESS_CARD_SUB
778 EuvBadge {
779 label: STRESS_BADGE_TXT.to_string()
780 tone: EuvTone::Primary
781 tokens: tokens
782 }
783 EuvProgress {
784 value: ((idx % 9) as f32 + 1.0) * 0.1
785 tokens: tokens
786 }
787 }
788 }
789 }
790 }
791 });
792 app.set_exact_physical_viewport(1080, 1920, 3.0);
793 let _: Result<FrameStats, PlatformError> = app.step_frame();
794 let mut samples: Vec<f64> = Vec::with_capacity(12);
795 let mut last_shaded: usize = 0;
796 for step in 1..=12usize {
797 let offset_y: f32 = ((step as f32) * 24.0) % 600.0;
798 let dt: f64 = measure_ms(|| {
799 app.get_scene().with_write(
800 |tree: &mut SceneTree| {
801 tree.set_scroll_offset(scroll_id, Point::new(0.0, offset_y));
802 },
803 (),
804 );
805 if let Ok(stats) = app.step_frame() {
806 last_shaded = stats.get_pixels_shaded();
807 }
808 });
809 samples.push(dt);
810 }
811 let info: String = format!("1080x1920@3x shaded={last_shaded}px/f");
812 (samples, info)
813 });
814 scope.dispose();
815 finalize_case(entry, &samples, true, details);
816}
817
818fn run_stress_cjk_atlas(entry: &mut StressCaseResult) {
824 let sample_chars: [char; 16] = [
825 'A', 'W', 'g', '9', '跨', '端', '原', '生', '框', '架', '高', '性', '能', '渲', '染', '器',
826 ];
827 let provider: NativeSystemFont = NativeSystemFont::deterministic();
828 let mut samples: Vec<f64> = Vec::with_capacity(16);
829 let mut packed_regions: usize = 0;
830 let mut atlas_w: u32 = 0;
831 let mut atlas_h: u32 = 0;
832 for _ in 0..16usize {
833 let dt: f64 = measure_ms(|| {
834 let mut atlas: GlyphAtlas = GlyphAtlas::default();
835 for sz in [120u16, 160u16, 220u16].into_iter() {
836 for ch in sample_chars.iter() {
837 let key: GlyphKey = GlyphKey::new(*ch, sz, sz >= 220);
838 let _: &RasterizedGlyph = atlas.get_or_rasterize_with(key, &provider);
839 }
840 }
841 let packed: PackedGlyphAtlas = atlas.pack_rgba_atlas();
842 packed_regions = packed.get_regions().len();
843 atlas_w = packed.get_width();
844 atlas_h = packed.get_height();
845 });
846 samples.push(dt);
847 }
848 let details: String = format!("glyphs={packed_regions} atlas={atlas_w}x{atlas_h}");
849 finalize_case(entry, &samples, false, details);
850}
851
852fn run_stress_game_2d_3d(entry: &mut StressCaseResult) {
858 let mut world2d: GameWorld = GameWorld::with_capacity(256);
859 for idx in 0..256usize {
860 let col: f32 = (idx % 16) as f32;
861 let row: f32 = (idx / 16) as f32;
862 let eid: EntityId = world2d.spawn(
863 EntityTag::Enemy,
864 Point::new(40.0 + col * 52.0, 40.0 + row * 40.0),
865 );
866 if let Some(ent) = world2d.get_entity_mut(eid) {
867 ent.set_velocity(Velocity2D::new(
868 if idx % 2 == 0 { 110.0 } else { -95.0 },
869 if idx % 3 == 0 { 85.0 } else { -75.0 },
870 0.0,
871 ));
872 ent.set_body(Some(RigidBody2D::dynamic(1.0, 0.9, 0.02)));
873 ent.set_collider(Some(Collider2D::circle(
874 10.0,
875 COLLISION_LAYER_ENEMY,
876 COLLISION_LAYER_ALL,
877 false,
878 )));
879 }
880 }
881 let mut phys_cfg: PhysicsConfig = PhysicsConfig::default();
882 phys_cfg.set_arena_bounds(Some(Rect::new(0.0, 0.0, 960.0, 720.0)));
883 let mut physics: PhysicsWorld2D = PhysicsWorld2D::with_config(phys_cfg);
884 let mut particles: ParticleSystem = ParticleSystem::with_capacity(1024);
885 let mut emit_cfg: ParticleEmitterConfig = ParticleEmitterConfig::default();
886 emit_cfg.set_min_life(10.0).set_max_life(20.0);
887 particles.emit_burst(Point::new(400.0, 300.0), 1024, emit_cfg);
888 let mut collisions: usize = 0;
889 let phys_ms: f64 = measure_ms(|| {
890 for _ in 0..60usize {
891 collisions += physics.step(&mut world2d, 1.0 / 60.0).len();
892 let _: usize = particles.update(1.0 / 60.0);
893 }
894 });
895 let mut world3d: World3D = World3D::create_open_world_city();
896 let mut renderer3d: Renderer3D = Renderer3D::default();
897 let cfg3d: RenderQualityConfig = RenderQualityConfig::from_preset(QualityPreset::High);
898 let mut samples: Vec<f64> = Vec::with_capacity(4);
899 let mut last_tris: usize = 0;
900 let mut last_rays: usize = 0;
901 for _ in 0..4usize {
902 let dt: f64 = measure_ms(|| {
903 let _: ImageBuffer = renderer3d.render_world(&mut world3d, 320, 180, &cfg3d);
904 let st: RenderStats3D = renderer3d.get_last_stats();
905 last_tris = st.get_triangles_drawn();
906 last_rays = st.get_rays_traced();
907 });
908 samples.push(dt);
909 }
910 let details: String =
911 format!("2d_60t={phys_ms:.2}ms col={collisions} 3d_tris={last_tris} rays={last_rays}");
912 finalize_case(entry, &samples, true, details);
913}
914
915fn run_stress_macro_mount(entry: &mut StressCaseResult) {
921 let tokens: ThemeTokens = ThemeTokens::resolve(DesignScheme::Shadcn, ThemeMode::Light);
922 let p: ThemePalette = tokens.get_palette();
923 let mut samples: Vec<f64> = Vec::with_capacity(8);
924 let mut last_nodes: usize = 0;
925 for _ in 0..8usize {
926 let dt: f64 = measure_ms(|| {
927 let scene: SceneHandle = SceneHandle::new_tree();
928 let ctx: Context = Context::new(scene.clone(), PlatformKind::Headless);
929 let tree_root: NodeId = with_context(ctx, || {
930 view! {
931 column {
932 width: Length::Px(1000.0)
933 gap: SPACE_XS
934 for idx in 0..160usize {
935 row {
936 width: Length::Percent(100.0)
937 justify: JustifyContent::SpaceBetween
938 align: AlignItems::Center
939 padding: Edges::symmetric(SPACE_XS, SPACE_SM)
940 background: p.get_card()
941 text {
942 font_size: 13.0
943 color: p.get_foreground()
944 { format!("{STRESS_CARD_PREFIX} {idx}") }
945 }
946 EuvBadge {
947 label: STRESS_BADGE_TXT.to_string()
948 tone: EuvTone::Primary
949 tokens: tokens
950 }
951 }
952 }
953 }
954 }
955 });
956 let mut engine: LayoutEngine = LayoutEngine::default();
957 scene.with_write(
958 |tree: &mut SceneTree| {
959 let root: NodeId = tree.get_root();
960 tree.replace_children(root, vec![tree_root]);
961 let st: LayoutStats = engine.compute(tree, Size::new(1000.0, 800.0));
962 last_nodes = st.get_nodes_computed();
963 },
964 (),
965 );
966 });
967 samples.push(dt);
968 }
969 let details: String = format!("cards=160 nodes={last_nodes} zero_alloc_macro=ok");
970 finalize_case(entry, &samples, false, details);
971}
972
973pub fn execute_stress_case(state: &ShowcaseState, scenario_id: &str) {
980 let results_sig: Signal<Vec<StressCaseResult>> = state.get_stress_results();
981 let summary_sig: Signal<String> = state.get_stress_summary();
982 let mut rows: Vec<StressCaseResult> = results_sig.get_untracked();
983 let Some(entry) = rows
984 .iter_mut()
985 .find(|item: &&mut StressCaseResult| item.get_id().as_str() == scenario_id)
986 else {
987 return;
988 };
989 match scenario_id {
990 STRESS_ID_VLIST_100K => run_stress_vlist_100k(entry),
991 STRESS_ID_LAYOUT_2000 => run_stress_layout_2000(entry),
992 STRESS_ID_REACTIVE_1000 => run_stress_reactive_1000(entry),
993 STRESS_ID_WASM_HOTSWAP => run_stress_wasm_hotswap(entry),
994 STRESS_ID_DRAWER_ANIM => run_stress_drawer_anim(entry),
995 STRESS_ID_TOUCH_HITTEST => run_stress_touch_hittest(entry),
996 STRESS_ID_HIDPI_SHADOW => run_stress_hidpi_shadow(entry),
997 STRESS_ID_CJK_ATLAS => run_stress_cjk_atlas(entry),
998 STRESS_ID_GAME_2D_3D => run_stress_game_2d_3d(entry),
999 STRESS_ID_MACRO_MOUNT => run_stress_macro_mount(entry),
1000 _ => return,
1001 }
1002 let summary: String = format!(
1003 "{} -> {} | avg={:.2}ms p95={:.2}ms max={:.2}ms ({}) [{}]",
1004 entry.get_title(),
1005 entry.get_status(),
1006 entry.get_avg_ms(),
1007 entry.get_p95_ms(),
1008 entry.get_max_ms(),
1009 entry.get_throughput(),
1010 entry.get_details()
1011 );
1012 batch(|| {
1013 let _: bool = results_sig.set(rows);
1014 let _: bool = summary_sig.set_if_changed(summary);
1015 });
1016}
1017
1018pub fn execute_stress_batch(state: &ShowcaseState, ids: &[&str]) {
1025 let mut total_ms: f64 = 0.0;
1026 for scenario_id in ids.iter() {
1027 let dt: f64 = measure_ms(|| execute_stress_case(state, scenario_id));
1028 total_ms += dt;
1029 }
1030 let rows: Vec<StressCaseResult> = state.get_stress_results().get_untracked();
1031 let completed: usize = rows
1032 .iter()
1033 .filter(|r: &&StressCaseResult| r.get_runs() > 0)
1034 .count();
1035 let passed: usize = rows
1036 .iter()
1037 .filter(|r: &&StressCaseResult| r.get_status().as_str() == STRESS_STATUS_PASS)
1038 .count();
1039 let summary: String = format!(
1040 "Completed {completed}/{} scenarios ({passed}/{completed} within budget) in {total_ms:.1}ms total.",
1041 rows.len()
1042 );
1043 let _: bool = state.get_stress_summary().set_if_changed(summary);
1044}
1045
1046pub fn mount_stress_page(state: &ShowcaseState, tokens: ThemeTokens) -> NodeId {
1057 let p: ThemePalette = tokens.get_palette();
1058 let g: ThemeGeometry = tokens.get_geometry();
1059 let results_sig: Signal<Vec<StressCaseResult>> = state.get_stress_results();
1060 let summary_sig: Signal<String> = state.get_stress_summary();
1061 let st_all: ShowcaseState = state.clone();
1062 let st_core: ShowcaseState = state.clone();
1063 let st_reset: ShowcaseState = state.clone();
1064 let st_list: ShowcaseState = state.clone();
1065 view! {
1066 EuvPage {
1067 title: STRESS_PAGE_TITLE.to_string()
1068 subtitle: STRESS_PAGE_SUBTITLE.to_string()
1069 tokens: tokens
1070 column {
1071 width: Length::Percent(100.0)
1072 bind_children: move || {
1073 let rows: Vec<StressCaseResult> = results_sig.get();
1074 let total: usize = rows.len();
1075 let done: usize = rows.iter().filter(|r: &&StressCaseResult| r.get_runs() > 0).count();
1076 let passed: usize = rows
1077 .iter()
1078 .filter(|r: &&StressCaseResult| r.get_status().as_str() == STRESS_STATUS_PASS)
1079 .count();
1080 let latest_opt: Option<&StressCaseResult> = rows
1081 .iter()
1082 .filter(|r: &&StressCaseResult| r.get_runs() > 0)
1083 .max_by_key(|r: &&StressCaseResult| r.get_runs());
1084 let (latest_val, latest_cap): (String, String) = match latest_opt {
1085 Some(item) => (
1086 format!("{:.2} ms", item.get_avg_ms()),
1087 format!("{} ({})", item.get_title(), item.get_throughput()),
1088 ),
1089 None => (
1090 STRESS_KPI_IDLE_VAL.to_string(),
1091 STRESS_KPI_IDLE_CAP.to_string(),
1092 ),
1093 };
1094 let kpi_grid: NodeId = view! {
1095 EuvStatGrid {
1096 EuvStatCard {
1097 label: STRESS_KPI_COMPLETED_LABEL.to_string()
1098 value: format!("{done} / {total}")
1099 caption: format!("{total} interactive workloads ready")
1100 tokens: tokens
1101 }
1102 EuvStatCard {
1103 label: STRESS_KPI_BUDGET_LABEL.to_string()
1104 value: if done == 0 {
1105 STRESS_KPI_IDLE_VAL.to_string()
1106 } else {
1107 format!("{passed} / {done} {STRESS_STATUS_PASS}")
1108 }
1109 caption: STRESS_KPI_BUDGET_CAP.to_string()
1110 tokens: tokens
1111 }
1112 EuvStatCard {
1113 label: STRESS_KPI_LATEST_LABEL.to_string()
1114 value: latest_val
1115 caption: latest_cap
1116 tokens: tokens
1117 }
1118 }
1119 };
1120 vec![kpi_grid]
1121 }
1122 }
1123 EuvCard {
1124 title: STRESS_CTRL_TITLE.to_string()
1125 tokens: tokens
1126 subtitle: STRESS_CTRL_SUBTITLE
1127 EuvActionRow {
1128 EuvButton {
1129 label: STRESS_BTN_RUN_ALL.to_string()
1130 tokens: tokens
1131 on_click: move |_: &UiEvent| {
1132 let all_ids: [&str; 10] = [
1133 STRESS_ID_VLIST_100K,
1134 STRESS_ID_LAYOUT_2000,
1135 STRESS_ID_REACTIVE_1000,
1136 STRESS_ID_WASM_HOTSWAP,
1137 STRESS_ID_DRAWER_ANIM,
1138 STRESS_ID_TOUCH_HITTEST,
1139 STRESS_ID_HIDPI_SHADOW,
1140 STRESS_ID_CJK_ATLAS,
1141 STRESS_ID_GAME_2D_3D,
1142 STRESS_ID_MACRO_MOUNT,
1143 ];
1144 execute_stress_batch(&st_all, &all_ids);
1145 }
1146 }
1147 EuvButton {
1148 label: STRESS_BTN_RUN_CORE.to_string()
1149 tokens: tokens
1150 secondary()
1151 on_click: move |_: &UiEvent| {
1152 let core_ids: [&str; 5] = [
1153 STRESS_ID_VLIST_100K,
1154 STRESS_ID_LAYOUT_2000,
1155 STRESS_ID_REACTIVE_1000,
1156 STRESS_ID_WASM_HOTSWAP,
1157 STRESS_ID_DRAWER_ANIM,
1158 ];
1159 execute_stress_batch(&st_core, &core_ids);
1160 }
1161 }
1162 EuvButton {
1163 label: STRESS_BTN_RESET.to_string()
1164 tokens: tokens
1165 outline()
1166 on_click: move |_: &UiEvent| {
1167 batch(|| {
1168 let _: bool = st_reset
1169 .get_stress_results()
1170 .set(default_stress_results());
1171 let _: bool = st_reset
1172 .get_stress_summary()
1173 .set_if_changed(STRESS_SUMMARY_READY.to_string());
1174 });
1175 }
1176 }
1177 }
1178 text {
1179 font_size: 13.0
1180 color: p.get_primary()
1181 { move || summary_sig.get() }
1182 }
1183 }
1184 EuvCard {
1185 title: STRESS_SCENARIOS_TITLE.to_string()
1186 tokens: tokens
1187 subtitle: STRESS_SCENARIOS_SUB
1188 column {
1189 width: Length::Percent(100.0)
1190 gap: SPACE_MD
1191 bind_children: move || {
1192 let rows: Vec<StressCaseResult> = results_sig.get();
1193 let mut cards: Vec<NodeId> = Vec::with_capacity(rows.len());
1194 for item in rows.into_iter() {
1195 let sid: String = item.get_id().clone();
1196 let st_run: ShowcaseState = st_list.clone();
1197 let status_tone: EuvTone = match item.get_status().as_str() {
1198 STRESS_STATUS_PASS => EuvTone::Success,
1199 STRESS_STATUS_WARN => EuvTone::Warning,
1200 _ => EuvTone::Neutral,
1201 };
1202 let metric_line: String = if item.get_runs() == 0 {
1203 format!(
1204 "Budget <= {:.2}ms | Status: {} | Click button to run",
1205 item.get_budget_ms(),
1206 item.get_status()
1207 )
1208 } else {
1209 format!(
1210 "Avg: {:.2}ms | P95: {:.2}ms | Max: {:.2}ms | Budget <= {:.2}ms | {} (runs={})",
1211 item.get_avg_ms(),
1212 item.get_p95_ms(),
1213 item.get_max_ms(),
1214 item.get_budget_ms(),
1215 item.get_throughput(),
1216 item.get_runs()
1217 )
1218 };
1219 let detail_line: String = if item.get_runs() == 0 {
1220 item.get_description().clone()
1221 } else {
1222 format!("{} | {}", item.get_description(), item.get_details())
1223 };
1224 let item_card: NodeId = view! {
1225 column {
1226 width: Length::Percent(100.0)
1227 padding: Edges::all(SPACE_MD)
1228 gap: SPACE_SM
1229 background: p.get_card()
1230 border: (g.get_border_width(), p.get_border())
1231 radius: g.get_radius_md()
1232 row {
1233 width: Length::Percent(100.0)
1234 flex_wrap: FlexWrap::Wrap
1235 justify: JustifyContent::SpaceBetween
1236 align: AlignItems::Center
1237 gap: SPACE_SM
1238 text {
1239 font_size: 14.0
1240 font_weight: FontWeight::Bold
1241 color: p.get_foreground()
1242 { item.get_title().clone() }
1243 }
1244 row {
1245 gap: SPACE_XS
1246 align: AlignItems::Center
1247 EuvBadge {
1248 label: item.get_category().clone()
1249 tone: EuvTone::Primary
1250 tokens: tokens
1251 }
1252 EuvBadge {
1253 label: item.get_status().clone()
1254 tone: status_tone
1255 tokens: tokens
1256 }
1257 }
1258 }
1259 text {
1260 font_size: 12.5
1261 color: p.get_muted_foreground()
1262 { detail_line }
1263 }
1264 text {
1265 font_size: 12.5
1266 font_weight: FontWeight::SemiBold
1267 color: p.get_foreground()
1268 { metric_line }
1269 }
1270 EuvActionRow {
1271 EuvButton {
1272 label: item.get_button_label().clone()
1273 tokens: tokens
1274 secondary()
1275 sm()
1276 on_click: move |_: &UiEvent| {
1277 execute_stress_case(&st_run, &sid);
1278 }
1279 }
1280 }
1281 }
1282 };
1283 cards.push(item_card);
1284 }
1285 cards
1286 }
1287 }
1288 }
1289 }
1290 }
1291}