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
302 .get_scene()
303 .with_read(SceneTree::live_node_count, mounted_nodes);
304 let info: String = format!(
305 "rows=100k mounted_nodes={mounted_nodes} scroll={:.0}px shaded={last_shaded}",
306 scroll_y.get_untracked()
307 );
308 (samples, info)
309 });
310 scope.dispose();
311 finalize_case(entry, &samples, true, details);
312}
313
314fn run_stress_layout_2000(entry: &mut StressCaseResult) {
320 let scene: SceneHandle = SceneHandle::new_tree();
321 let ctx: Context = Context::new(scene.clone(), PlatformKind::Headless);
322 let (leaf_nodes, page): (Vec<NodeId>, NodeId) = with_context(ctx, || {
323 let mut leaves: Vec<NodeId> = Vec::with_capacity(50);
324 let mut sections: Vec<NodeId> = Vec::with_capacity(50);
325 for section_idx in 0..50usize {
326 let mut first_title: NodeId = NodeId::default();
327 let grid_node: NodeId = view! {
328 grid {
329 columns: 4
330 width: Length::Percent(100.0)
331 gap: SPACE_SM
332 for card_idx in 0..8usize {
333 column {
334 width: Length::Percent(100.0)
335 padding: Edges::all(SPACE_SM)
336 gap: SPACE_XS
337 row {
338 width: Length::Percent(100.0)
339 justify: JustifyContent::SpaceBetween
340 if card_idx == 0 {
341 text {
342 node_ref: first_title
343 font_size: 13.0
344 { format!("{STRESS_CELL_PREFIX} {section_idx}-{card_idx}") }
345 }
346 } else {
347 text {
348 font_size: 13.0
349 { format!("{STRESS_CELL_PREFIX} {section_idx}-{card_idx}") }
350 }
351 }
352 text {
353 font_size: 11.0
354 { format!("{section_idx}") }
355 }
356 }
357 }
358 }
359 }
360 };
361 leaves.push(first_title);
362 sections.push(grid_node);
363 }
364 let p_node: NodeId = view! {
365 column {
366 width: Length::Px(1280.0)
367 padding: Edges::all(SPACE_MD)
368 gap: SPACE_SM
369 ..sections
370 }
371 };
372 (leaves, p_node)
373 });
374 scene.with_write(
375 |tree: &mut SceneTree| {
376 let root: NodeId = tree.get_root();
377 tree.replace_children(root, vec![page]);
378 },
379 (),
380 );
381 let mut engine: LayoutEngine = LayoutEngine::default();
382 let viewport: Size = Size::new(1280.0, 800.0);
383 let mut init_nodes: usize = 0;
384 let init_ms: f64 = measure_ms(|| {
385 let st: LayoutStats = scene.with_write(
386 |tree: &mut SceneTree| engine.compute(tree, viewport),
387 LayoutStats::default(),
388 );
389 init_nodes = st.get_nodes_computed();
390 });
391 let mut samples: Vec<f64> = Vec::with_capacity(40);
392 let mut total_computed: usize = 0;
393 let mut total_skipped: usize = 0;
394 for step in 0..40usize {
395 let target: NodeId = leaf_nodes[step % leaf_nodes.len()];
396 let dt: f64 = measure_ms(|| {
397 scene.with_write(
398 |tree: &mut SceneTree| {
399 tree.set_text(target, format!("{STRESS_CELL_PREFIX} #{step}"));
400 let stats: LayoutStats = engine.compute(tree, viewport);
401 total_computed += stats.get_nodes_computed();
402 total_skipped += stats.get_subtrees_skipped();
403 },
404 (),
405 );
406 });
407 samples.push(dt);
408 }
409 let details: String = format!(
410 "nodes={init_nodes} init={init_ms:.2}ms avg_recomputed={} skipped={}",
411 total_computed / 40,
412 total_skipped / 40
413 );
414 finalize_case(entry, &samples, false, details);
415}
416
417fn run_stress_reactive_1000(entry: &mut StressCaseResult) {
423 let (scope, (samples, details)): (Scope, (Vec<f64>, String)) = Scope::run(|_: Scope| {
424 let tokens: ThemeTokens = ThemeTokens::resolve(DesignScheme::Shadcn, ThemeMode::Light);
425 let p: ThemePalette = tokens.get_palette();
426 let mut win: WindowConfig = WindowConfig::default();
427 win.set_size(800, 600).set_render(RenderConfig::hardware());
428 let mut cfg: AppConfig = AppConfig::default();
429 cfg.set_window(win);
430 let Ok(mut app) = App::headless(cfg) else {
431 return (Vec::new(), STRESS_UNIT_NA.to_string());
432 };
433 let mut signals: Vec<Signal<u32>> = Vec::with_capacity(1_000);
434 for idx in 0..1_000u32 {
435 signals.push(Signal::new(idx));
436 }
437 let signals_mount: Vec<Signal<u32>> = signals.clone();
438 let _: NodeId = app.mount(move || {
439 let derived_memos: Vec<Memo<u32>> = signals_mount
440 .into_iter()
441 .map(|sig: Signal<u32>| {
442 Memo::new(move || sig.get().wrapping_mul(3).wrapping_add(1))
443 })
444 .collect();
445 view! {
446 scroll {
447 width: Length::Percent(100.0)
448 height: Length::Percent(100.0)
449 gap: 2.0
450 for derived in derived_memos.into_iter() {
451 text {
452 font_size: 12.0
453 color: p.get_foreground()
454 { move || format!("{STRESS_CELL_PREFIX} {}", derived.get()) }
455 }
456 }
457 }
458 }
459 });
460 let _: Result<FrameStats, PlatformError> = app.step_frame();
461 let mut samples: Vec<f64> = Vec::with_capacity(16);
462 let mut last_rev: u64 = 0;
463 for tick in 1..=16u32 {
464 let dt: f64 = measure_ms(|| {
465 batch(|| {
466 for (idx, sig) in signals.iter().enumerate() {
467 let _: bool = sig.set_if_changed(tick.wrapping_add(idx as u32));
468 }
469 });
470 flush_effects();
471 if app.step_frame().is_ok() {
472 last_rev = app.get_last_rendered_revision();
473 }
474 });
475 samples.push(dt);
476 }
477 let info: String = format!("signals=1000 memos=1000 rev={last_rev}");
478 (samples, info)
479 });
480 scope.dispose();
481 finalize_case(entry, &samples, false, details);
482}
483
484fn run_stress_wasm_hotswap(entry: &mut StressCaseResult) {
490 let (scope, (samples, details)): (Scope, (Vec<f64>, String)) = Scope::run(|_: Scope| {
491 let mut win: WindowConfig = WindowConfig::default();
492 win.set_size(640, 480).set_render(RenderConfig::hardware());
493 let mut cfg: AppConfig = AppConfig::default();
494 cfg.set_window(win);
495 let Ok(mut app) = App::headless(cfg) else {
496 return (Vec::new(), STRESS_UNIT_NA.to_string());
497 };
498 let hub: DynamicUpdateHub = app.get_dynamic_hub().clone();
499 let registry: RegistryWasmFetcher = RegistryWasmFetcher::default();
500 let wasm_v1: Vec<u8> = build_partial_widget_wasm(STRESS_WASM_TITLE_V1, 1, 0x2563EB);
501 let wasm_v2: Vec<u8> = build_partial_widget_wasm(STRESS_WASM_TITLE_V2, 2, 0x7C3AED);
502 let csum_v1: u64 = compute_wasm_checksum(&wasm_v1);
503 let csum_v2: u64 = compute_wasm_checksum(&wasm_v2);
504 registry.register(
505 STRESS_WASM_URL_V1.to_string(),
506 wasm_v1,
507 STRESS_WASM_ETAG_V1.to_string(),
508 WasmFaultKind::None,
509 );
510 registry.register(
511 STRESS_WASM_URL_V2.to_string(),
512 wasm_v2,
513 STRESS_WASM_ETAG_V2.to_string(),
514 WasmFaultKind::None,
515 );
516 let manager: WasmDynamicManager =
517 WasmDynamicManager::new(hub.clone(), Rc::new(registry), WasmSandboxConfig::default());
518 let hub_slot: DynamicUpdateHub = hub;
519 let _: NodeId = app.mount(move || {
520 view! {
521 slot {
522 id: STRESS_WASM_SLOT
523 hub: hub_slot
524 text {
525 font_size: 14.0
526 { STRESS_WASM_FALLBACK }
527 }
528 }
529 }
530 });
531 let _: Result<FrameStats, PlatformError> = app.step_frame();
532 let mut samples: Vec<f64> = Vec::with_capacity(12);
533 let mut completed: usize = 0;
534 for cycle in 0..12usize {
535 let base_ver: u64 = ((cycle as u64) * 2) + 1;
536 let dt: f64 = measure_ms(|| {
537 let req_v1: WasmDownloadRequest = WasmDownloadRequest::partial(
538 STRESS_WASM_URL_V1.to_string(),
539 STRESS_WASM_SLOT.to_string(),
540 base_ver,
541 )
542 .with_checksum(csum_v1)
543 .with_allow_downgrade(true);
544 let req_v2: WasmDownloadRequest = WasmDownloadRequest::partial(
545 STRESS_WASM_URL_V2.to_string(),
546 STRESS_WASM_SLOT.to_string(),
547 base_ver + 1,
548 )
549 .with_checksum(csum_v2)
550 .with_allow_downgrade(true);
551 if manager.load_and_mount(req_v1, STRESS_WASM_KEY).is_ok()
552 && manager.load_and_mount(req_v2, STRESS_WASM_KEY).is_ok()
553 && manager
554 .rollback_partial(STRESS_WASM_SLOT, STRESS_WASM_RB_REASON)
555 .is_ok()
556 {
557 let _: Result<FrameStats, PlatformError> = app.step_frame();
558 completed += 1;
559 }
560 });
561 samples.push(dt);
562 }
563 let info: String = format!("cycles={completed}/12 cache={}", manager.cache_len());
564 (samples, info)
565 });
566 scope.dispose();
567 finalize_case(entry, &samples, false, details);
568}
569
570fn run_stress_drawer_anim(entry: &mut StressCaseResult) {
576 let (scope, (samples, details)): (Scope, (Vec<f64>, String)) = Scope::run(|_: Scope| {
577 let tokens: ThemeTokens = ThemeTokens::resolve(DesignScheme::Shadcn, ThemeMode::Light);
578 let p: ThemePalette = tokens.get_palette();
579 let mut win: WindowConfig = WindowConfig::default();
580 win.set_size(360, 780).set_render(RenderConfig::software());
581 let mut cfg: AppConfig = AppConfig::default();
582 cfg.set_window(win);
583 let Ok(mut app) = App::headless(cfg) else {
584 return (Vec::new(), STRESS_UNIT_NA.to_string());
585 };
586 let drawer_open: Signal<bool> = Signal::new(false);
587 let _: NodeId = app.mount(|| {
588 let drawer_body: NodeId = view! {
589 column {
590 width: Length::Percent(100.0)
591 gap: SPACE_SM
592 for idx in 0..8usize {
593 text {
594 font_size: 14.0
595 color: p.get_foreground()
596 { format!("{STRESS_DRAWER_ITEM} {idx}") }
597 }
598 }
599 }
600 };
601 view! {
602 column {
603 width: Length::Percent(100.0)
604 height: Length::Percent(100.0)
605 padding: Edges::all(SPACE_MD)
606 gap: SPACE_MD
607 background: p.get_background()
608 for idx in 0..6usize {
609 EuvCard {
610 title: format!("{STRESS_CARD_PREFIX} #{idx}")
611 tokens: tokens
612 subtitle: STRESS_CARD_SUB
613 EuvBadge {
614 label: STRESS_BADGE_TXT.to_string()
615 tone: EuvTone::Primary
616 tokens: tokens
617 }
618 }
619 }
620 EuvDrawer {
621 open: drawer_open
622 title: STRESS_DRAWER_TITLE.to_string()
623 body: drawer_body
624 tokens: tokens
625 }
626 }
627 }
628 });
629 app.set_exact_physical_viewport(720, 1560, 2.0);
630 let _: Result<FrameStats, PlatformError> = app.step_frame();
631 let _: bool = drawer_open.set_if_changed(true);
632 let mut samples: Vec<f64> = Vec::with_capacity(30);
633 let mut active_frames: usize = 0;
634 for step in 0..30usize {
635 if step == 16 {
636 let _: bool = drawer_open.set_if_changed(false);
637 }
638 let dt: f64 = measure_ms(|| {
639 if app.step_game_frame(1.0 / 120.0).is_ok() && app.has_active_animations() {
640 active_frames += 1;
641 }
642 });
643 samples.push(dt);
644 }
645 let info: String = format!("720x1560@2x anim_frames={active_frames} backdrop_cache=on");
646 (samples, info)
647 });
648 scope.dispose();
649 finalize_case(entry, &samples, true, details);
650}
651
652fn run_stress_touch_hittest(entry: &mut StressCaseResult) {
658 let (scope, (samples, details)): (Scope, (Vec<f64>, String)) = Scope::run(|_: Scope| {
659 let tokens: ThemeTokens = ThemeTokens::resolve(DesignScheme::Shadcn, ThemeMode::Light);
660 let p: ThemePalette = tokens.get_palette();
661 let mut win: WindowConfig = WindowConfig::default();
662 win.set_size(400, 800).set_render(RenderConfig::hardware());
663 let mut cfg: AppConfig = AppConfig::default();
664 cfg.set_window(win);
665 let Ok(mut app) = App::headless(cfg) else {
666 return (Vec::new(), STRESS_UNIT_NA.to_string());
667 };
668 let mut scroll_id: NodeId = NodeId::default();
669 let _: NodeId = app.mount(|| {
670 view! {
671 scroll {
672 node_ref: scroll_id
673 width: Length::Percent(100.0)
674 height: Length::Percent(100.0)
675 gap: SPACE_XS
676 padding: Edges::all(SPACE_SM)
677 for idx in 0..250usize {
678 row {
679 width: Length::Percent(100.0)
680 height: Length::Px(32.0)
681 gap: SPACE_XS
682 text { font_size: 12.0 color: p.get_foreground() { format!("{STRESS_ROW_PREFIX} {idx}") } }
683 text { font_size: 11.0 color: p.get_muted_foreground() { STRESS_BADGE_TXT } }
684 text { font_size: 11.0 color: p.get_primary() { format!("#{idx}") } }
685 }
686 }
687 }
688 }
689 });
690 let _: Result<FrameStats, PlatformError> = app.step_frame();
691 let wid: WindowId = app.get_window_state().get_id();
692 app.dispatch_window_event(WindowEvent::PointerDown(
693 wid,
694 PointerEvent::touch(99, 200.0, 400.0),
695 ));
696 app.dispatch_window_event(WindowEvent::PointerMove(
697 wid,
698 PointerEvent::touch(99, 204.0, 406.0),
699 ));
700 app.dispatch_window_event(WindowEvent::PointerUp(
701 wid,
702 PointerEvent::touch(99, 204.0, 406.0),
703 ));
704 let _: Result<FrameStats, PlatformError> = app.step_frame();
705 let tap_drift: f32 = app.get_scene().with_read(
706 |tree: &SceneTree| {
707 tree.get_node(scroll_id)
708 .map(|n: &SceneNode| n.get_layout_box().get_scroll_offset().get_y())
709 .unwrap_or(0.0)
710 },
711 0.0,
712 );
713 let mut samples: Vec<f64> = Vec::with_capacity(120);
714 for step in 0..120usize {
715 let y: f32 = 120.0 + ((step * 19) % 580) as f32;
716 let dt: f64 = measure_ms(|| {
717 app.dispatch_window_event(WindowEvent::PointerMove(
718 wid,
719 PointerEvent::mouse(200.0, y),
720 ));
721 app.dispatch_window_event(WindowEvent::Scroll(wid, Point::new(0.0, 14.0)));
722 let _: Result<FrameStats, PlatformError> = app.step_game_frame(1.0 / 240.0);
723 });
724 samples.push(dt);
725 }
726 let final_scroll: f32 = app.get_scene().with_read(
727 |tree: &SceneTree| {
728 tree.get_node(scroll_id)
729 .map(|n: &SceneNode| n.get_layout_box().get_scroll_offset().get_y())
730 .unwrap_or(0.0)
731 },
732 0.0,
733 );
734 let info: String =
735 format!("nodes=1000 tap_drift={tap_drift:.2}px scrolled={final_scroll:.0}px");
736 (samples, info)
737 });
738 scope.dispose();
739 finalize_case(entry, &samples, false, details);
740}
741
742fn run_stress_hidpi_shadow(entry: &mut StressCaseResult) {
748 let (scope, (samples, details)): (Scope, (Vec<f64>, String)) = Scope::run(|_: Scope| {
749 let tokens: ThemeTokens = ThemeTokens::resolve(DesignScheme::Shadcn, ThemeMode::Light);
750 let mut win: WindowConfig = WindowConfig::default();
751 win.set_size(360, 640).set_render(RenderConfig::software());
752 let mut cfg: AppConfig = AppConfig::default();
753 cfg.set_window(win);
754 let Ok(mut app) = App::headless(cfg) else {
755 return (Vec::new(), STRESS_UNIT_NA.to_string());
756 };
757 let mut scroll_id: NodeId = NodeId::default();
758 let _: NodeId = app.mount(|| {
759 view! {
760 scroll {
761 node_ref: scroll_id
762 width: Length::Percent(100.0)
763 height: Length::Percent(100.0)
764 padding: Edges::all(SPACE_MD)
765 gap: SPACE_MD
766 background: tokens.get_palette().get_background()
767 for idx in 0..12usize {
768 EuvCard {
769 title: format!("{STRESS_CARD_PREFIX} #{idx}")
770 tokens: tokens
771 subtitle: STRESS_CARD_SUB
772 EuvBadge {
773 label: STRESS_BADGE_TXT.to_string()
774 tone: EuvTone::Primary
775 tokens: tokens
776 }
777 EuvProgress {
778 value: ((idx % 9) as f32 + 1.0) * 0.1
779 tokens: tokens
780 }
781 }
782 }
783 }
784 }
785 });
786 app.set_exact_physical_viewport(1080, 1920, 3.0);
787 let _: Result<FrameStats, PlatformError> = app.step_frame();
788 let mut samples: Vec<f64> = Vec::with_capacity(12);
789 let mut last_shaded: usize = 0;
790 for step in 1..=12usize {
791 let offset_y: f32 = ((step as f32) * 24.0) % 600.0;
792 let dt: f64 = measure_ms(|| {
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 samples.push(dt);
804 }
805 let info: String = format!("1080x1920@3x shaded={last_shaded}px/f");
806 (samples, info)
807 });
808 scope.dispose();
809 finalize_case(entry, &samples, true, details);
810}
811
812fn run_stress_cjk_atlas(entry: &mut StressCaseResult) {
818 let sample_chars: [char; 16] = [
819 'A', 'W', 'g', '9', '跨', '端', '原', '生', '框', '架', '高', '性', '能', '渲', '染', '器',
820 ];
821 let provider: NativeSystemFont = NativeSystemFont::deterministic();
822 let mut samples: Vec<f64> = Vec::with_capacity(16);
823 let mut packed_regions: usize = 0;
824 let mut atlas_w: u32 = 0;
825 let mut atlas_h: u32 = 0;
826 for _ in 0..16usize {
827 let dt: f64 = measure_ms(|| {
828 let mut atlas: GlyphAtlas = GlyphAtlas::default();
829 for sz in [120u16, 160u16, 220u16].into_iter() {
830 for ch in sample_chars.iter() {
831 let key: GlyphKey = GlyphKey::new(*ch, sz, sz >= 220);
832 let _: &RasterizedGlyph = atlas.get_or_rasterize_with(key, &provider);
833 }
834 }
835 let packed: PackedGlyphAtlas = atlas.pack_rgba_atlas();
836 packed_regions = packed.get_regions().len();
837 atlas_w = packed.get_width();
838 atlas_h = packed.get_height();
839 });
840 samples.push(dt);
841 }
842 let details: String = format!("glyphs={packed_regions} atlas={atlas_w}x{atlas_h}");
843 finalize_case(entry, &samples, false, details);
844}
845
846fn run_stress_game_2d_3d(entry: &mut StressCaseResult) {
852 let mut world2d: GameWorld = GameWorld::with_capacity(256);
853 for idx in 0..256usize {
854 let col: f32 = (idx % 16) as f32;
855 let row: f32 = (idx / 16) as f32;
856 let eid: EntityId = world2d.spawn(
857 EntityTag::Enemy,
858 Point::new(40.0 + col * 52.0, 40.0 + row * 40.0),
859 );
860 if let Some(ent) = world2d.get_entity_mut(eid) {
861 ent.set_velocity(Velocity2D::new(
862 if idx % 2 == 0 { 110.0 } else { -95.0 },
863 if idx % 3 == 0 { 85.0 } else { -75.0 },
864 0.0,
865 ));
866 ent.set_body(Some(RigidBody2D::dynamic(1.0, 0.9, 0.02)));
867 ent.set_collider(Some(Collider2D::circle(
868 10.0,
869 COLLISION_LAYER_ENEMY,
870 COLLISION_LAYER_ALL,
871 false,
872 )));
873 }
874 }
875 let mut phys_cfg: PhysicsConfig = PhysicsConfig::default();
876 phys_cfg.set_arena_bounds(Some(Rect::new(0.0, 0.0, 960.0, 720.0)));
877 let mut physics: PhysicsWorld2D = PhysicsWorld2D::with_config(phys_cfg);
878 let mut particles: ParticleSystem = ParticleSystem::with_capacity(1024);
879 let mut emit_cfg: ParticleEmitterConfig = ParticleEmitterConfig::default();
880 emit_cfg.set_min_life(10.0).set_max_life(20.0);
881 particles.emit_burst(Point::new(400.0, 300.0), 1024, emit_cfg);
882 let mut collisions: usize = 0;
883 let phys_ms: f64 = measure_ms(|| {
884 for _ in 0..60usize {
885 collisions += physics.step(&mut world2d, 1.0 / 60.0).len();
886 let _: usize = particles.update(1.0 / 60.0);
887 }
888 });
889 let mut world3d: World3D = World3D::create_open_world_city();
890 let mut renderer3d: Renderer3D = Renderer3D::default();
891 let cfg3d: RenderQualityConfig = RenderQualityConfig::from_preset(QualityPreset::High);
892 let mut samples: Vec<f64> = Vec::with_capacity(4);
893 let mut last_tris: usize = 0;
894 let mut last_rays: usize = 0;
895 for _ in 0..4usize {
896 let dt: f64 = measure_ms(|| {
897 let _: ImageBuffer = renderer3d.render_world(&mut world3d, 320, 180, &cfg3d);
898 let st: RenderStats3D = renderer3d.get_last_stats();
899 last_tris = st.get_triangles_drawn();
900 last_rays = st.get_rays_traced();
901 });
902 samples.push(dt);
903 }
904 let details: String =
905 format!("2d_60t={phys_ms:.2}ms col={collisions} 3d_tris={last_tris} rays={last_rays}");
906 finalize_case(entry, &samples, true, details);
907}
908
909fn run_stress_macro_mount(entry: &mut StressCaseResult) {
915 let tokens: ThemeTokens = ThemeTokens::resolve(DesignScheme::Shadcn, ThemeMode::Light);
916 let p: ThemePalette = tokens.get_palette();
917 let mut samples: Vec<f64> = Vec::with_capacity(8);
918 let mut last_nodes: usize = 0;
919 for _ in 0..8usize {
920 let dt: f64 = measure_ms(|| {
921 let scene: SceneHandle = SceneHandle::new_tree();
922 let ctx: Context = Context::new(scene.clone(), PlatformKind::Headless);
923 let tree_root: NodeId = with_context(ctx, || {
924 view! {
925 column {
926 width: Length::Px(1000.0)
927 gap: SPACE_XS
928 for idx in 0..160usize {
929 row {
930 width: Length::Percent(100.0)
931 justify: JustifyContent::SpaceBetween
932 align: AlignItems::Center
933 padding: Edges::symmetric(SPACE_XS, SPACE_SM)
934 background: p.get_card()
935 text {
936 font_size: 13.0
937 color: p.get_foreground()
938 { format!("{STRESS_CARD_PREFIX} {idx}") }
939 }
940 EuvBadge {
941 label: STRESS_BADGE_TXT.to_string()
942 tone: EuvTone::Primary
943 tokens: tokens
944 }
945 }
946 }
947 }
948 }
949 });
950 let mut engine: LayoutEngine = LayoutEngine::default();
951 scene.with_write(
952 |tree: &mut SceneTree| {
953 let root: NodeId = tree.get_root();
954 tree.replace_children(root, vec![tree_root]);
955 let st: LayoutStats = engine.compute(tree, Size::new(1000.0, 800.0));
956 last_nodes = st.get_nodes_computed();
957 },
958 (),
959 );
960 });
961 samples.push(dt);
962 }
963 let details: String = format!("cards=160 nodes={last_nodes} zero_alloc_macro=ok");
964 finalize_case(entry, &samples, false, details);
965}
966
967pub fn execute_stress_case(state: &ShowcaseState, scenario_id: &str) {
974 let results_sig: Signal<Vec<StressCaseResult>> = state.get_stress_results();
975 let summary_sig: Signal<String> = state.get_stress_summary();
976 let mut rows: Vec<StressCaseResult> = results_sig.get_untracked();
977 let Some(entry) = rows
978 .iter_mut()
979 .find(|item: &&mut StressCaseResult| item.get_id().as_str() == scenario_id)
980 else {
981 return;
982 };
983 match scenario_id {
984 STRESS_ID_VLIST_100K => run_stress_vlist_100k(entry),
985 STRESS_ID_LAYOUT_2000 => run_stress_layout_2000(entry),
986 STRESS_ID_REACTIVE_1000 => run_stress_reactive_1000(entry),
987 STRESS_ID_WASM_HOTSWAP => run_stress_wasm_hotswap(entry),
988 STRESS_ID_DRAWER_ANIM => run_stress_drawer_anim(entry),
989 STRESS_ID_TOUCH_HITTEST => run_stress_touch_hittest(entry),
990 STRESS_ID_HIDPI_SHADOW => run_stress_hidpi_shadow(entry),
991 STRESS_ID_CJK_ATLAS => run_stress_cjk_atlas(entry),
992 STRESS_ID_GAME_2D_3D => run_stress_game_2d_3d(entry),
993 STRESS_ID_MACRO_MOUNT => run_stress_macro_mount(entry),
994 _ => return,
995 }
996 let summary: String = format!(
997 "{} -> {} | avg={:.2}ms p95={:.2}ms max={:.2}ms ({}) [{}]",
998 entry.get_title(),
999 entry.get_status(),
1000 entry.get_avg_ms(),
1001 entry.get_p95_ms(),
1002 entry.get_max_ms(),
1003 entry.get_throughput(),
1004 entry.get_details()
1005 );
1006 batch(|| {
1007 let _: bool = results_sig.set(rows);
1008 let _: bool = summary_sig.set_if_changed(summary);
1009 });
1010}
1011
1012pub fn execute_stress_batch(state: &ShowcaseState, ids: &[&str]) {
1019 let mut total_ms: f64 = 0.0;
1020 for scenario_id in ids.iter() {
1021 let dt: f64 = measure_ms(|| execute_stress_case(state, scenario_id));
1022 total_ms += dt;
1023 }
1024 let rows: Vec<StressCaseResult> = state.get_stress_results().get_untracked();
1025 let completed: usize = rows
1026 .iter()
1027 .filter(|r: &&StressCaseResult| r.get_runs() > 0)
1028 .count();
1029 let passed: usize = rows
1030 .iter()
1031 .filter(|r: &&StressCaseResult| r.get_status().as_str() == STRESS_STATUS_PASS)
1032 .count();
1033 let summary: String = format!(
1034 "Completed {completed}/{} scenarios ({passed}/{completed} within budget) in {total_ms:.1}ms total.",
1035 rows.len()
1036 );
1037 let _: bool = state.get_stress_summary().set_if_changed(summary);
1038}
1039
1040pub fn mount_stress_page(state: &ShowcaseState, tokens: ThemeTokens) -> NodeId {
1051 let p: ThemePalette = tokens.get_palette();
1052 let g: ThemeGeometry = tokens.get_geometry();
1053 let results_sig: Signal<Vec<StressCaseResult>> = state.get_stress_results();
1054 let summary_sig: Signal<String> = state.get_stress_summary();
1055 let st_all: ShowcaseState = state.clone();
1056 let st_core: ShowcaseState = state.clone();
1057 let st_reset: ShowcaseState = state.clone();
1058 let st_list: ShowcaseState = state.clone();
1059 view! {
1060 EuvPage {
1061 title: STRESS_PAGE_TITLE.to_string()
1062 subtitle: STRESS_PAGE_SUBTITLE.to_string()
1063 tokens: tokens
1064 column {
1065 width: Length::Percent(100.0)
1066 bind_children: move || {
1067 let rows: Vec<StressCaseResult> = results_sig.get();
1068 let total: usize = rows.len();
1069 let done: usize = rows.iter().filter(|r: &&StressCaseResult| r.get_runs() > 0).count();
1070 let passed: usize = rows
1071 .iter()
1072 .filter(|r: &&StressCaseResult| r.get_status().as_str() == STRESS_STATUS_PASS)
1073 .count();
1074 let latest_opt: Option<&StressCaseResult> = rows
1075 .iter()
1076 .filter(|r: &&StressCaseResult| r.get_runs() > 0)
1077 .max_by_key(|r: &&StressCaseResult| r.get_runs());
1078 let (latest_val, latest_cap): (String, String) = match latest_opt {
1079 Some(item) => (
1080 format!("{:.2} ms", item.get_avg_ms()),
1081 format!("{} ({})", item.get_title(), item.get_throughput()),
1082 ),
1083 None => (
1084 STRESS_KPI_IDLE_VAL.to_string(),
1085 STRESS_KPI_IDLE_CAP.to_string(),
1086 ),
1087 };
1088 let kpi_grid: NodeId = view! {
1089 EuvStatGrid {
1090 EuvStatCard {
1091 label: STRESS_KPI_COMPLETED_LABEL.to_string()
1092 value: format!("{done} / {total}")
1093 caption: format!("{total} interactive workloads ready")
1094 tokens: tokens
1095 }
1096 EuvStatCard {
1097 label: STRESS_KPI_BUDGET_LABEL.to_string()
1098 value: if done == 0 {
1099 STRESS_KPI_IDLE_VAL.to_string()
1100 } else {
1101 format!("{passed} / {done} {STRESS_STATUS_PASS}")
1102 }
1103 caption: STRESS_KPI_BUDGET_CAP.to_string()
1104 tokens: tokens
1105 }
1106 EuvStatCard {
1107 label: STRESS_KPI_LATEST_LABEL.to_string()
1108 value: latest_val
1109 caption: latest_cap
1110 tokens: tokens
1111 }
1112 }
1113 };
1114 vec![kpi_grid]
1115 }
1116 }
1117 EuvCard {
1118 title: STRESS_CTRL_TITLE.to_string()
1119 tokens: tokens
1120 subtitle: STRESS_CTRL_SUBTITLE
1121 EuvActionRow {
1122 EuvButton {
1123 label: STRESS_BTN_RUN_ALL.to_string()
1124 tokens: tokens
1125 on_click: move |_: &UiEvent| {
1126 let all_ids: [&str; 10] = [
1127 STRESS_ID_VLIST_100K,
1128 STRESS_ID_LAYOUT_2000,
1129 STRESS_ID_REACTIVE_1000,
1130 STRESS_ID_WASM_HOTSWAP,
1131 STRESS_ID_DRAWER_ANIM,
1132 STRESS_ID_TOUCH_HITTEST,
1133 STRESS_ID_HIDPI_SHADOW,
1134 STRESS_ID_CJK_ATLAS,
1135 STRESS_ID_GAME_2D_3D,
1136 STRESS_ID_MACRO_MOUNT,
1137 ];
1138 execute_stress_batch(&st_all, &all_ids);
1139 }
1140 }
1141 EuvButton {
1142 label: STRESS_BTN_RUN_CORE.to_string()
1143 tokens: tokens
1144 secondary()
1145 on_click: move |_: &UiEvent| {
1146 let core_ids: [&str; 5] = [
1147 STRESS_ID_VLIST_100K,
1148 STRESS_ID_LAYOUT_2000,
1149 STRESS_ID_REACTIVE_1000,
1150 STRESS_ID_WASM_HOTSWAP,
1151 STRESS_ID_DRAWER_ANIM,
1152 ];
1153 execute_stress_batch(&st_core, &core_ids);
1154 }
1155 }
1156 EuvButton {
1157 label: STRESS_BTN_RESET.to_string()
1158 tokens: tokens
1159 outline()
1160 on_click: move |_: &UiEvent| {
1161 batch(|| {
1162 let _: bool = st_reset
1163 .get_stress_results()
1164 .set(default_stress_results());
1165 let _: bool = st_reset
1166 .get_stress_summary()
1167 .set_if_changed(STRESS_SUMMARY_READY.to_string());
1168 });
1169 }
1170 }
1171 }
1172 text {
1173 font_size: 13.0
1174 color: p.get_primary()
1175 { move || summary_sig.get() }
1176 }
1177 }
1178 EuvCard {
1179 title: STRESS_SCENARIOS_TITLE.to_string()
1180 tokens: tokens
1181 subtitle: STRESS_SCENARIOS_SUB
1182 column {
1183 width: Length::Percent(100.0)
1184 gap: SPACE_MD
1185 bind_children: move || {
1186 let rows: Vec<StressCaseResult> = results_sig.get();
1187 let mut cards: Vec<NodeId> = Vec::with_capacity(rows.len());
1188 for item in rows.into_iter() {
1189 let sid: String = item.get_id().clone();
1190 let st_run: ShowcaseState = st_list.clone();
1191 let status_tone: EuvTone = match item.get_status().as_str() {
1192 STRESS_STATUS_PASS => EuvTone::Success,
1193 STRESS_STATUS_WARN => EuvTone::Warning,
1194 _ => EuvTone::Neutral,
1195 };
1196 let metric_line: String = if item.get_runs() == 0 {
1197 format!(
1198 "Budget <= {:.2}ms | Status: {} | Click button to run",
1199 item.get_budget_ms(),
1200 item.get_status()
1201 )
1202 } else {
1203 format!(
1204 "Avg: {:.2}ms | P95: {:.2}ms | Max: {:.2}ms | Budget <= {:.2}ms | {} (runs={})",
1205 item.get_avg_ms(),
1206 item.get_p95_ms(),
1207 item.get_max_ms(),
1208 item.get_budget_ms(),
1209 item.get_throughput(),
1210 item.get_runs()
1211 )
1212 };
1213 let detail_line: String = if item.get_runs() == 0 {
1214 item.get_description().clone()
1215 } else {
1216 format!("{} | {}", item.get_description(), item.get_details())
1217 };
1218 let item_card: NodeId = view! {
1219 column {
1220 width: Length::Percent(100.0)
1221 padding: Edges::all(SPACE_MD)
1222 gap: SPACE_SM
1223 background: p.get_card()
1224 border: (g.get_border_width(), p.get_border())
1225 radius: g.get_radius_md()
1226 row {
1227 width: Length::Percent(100.0)
1228 flex_wrap: FlexWrap::Wrap
1229 justify: JustifyContent::SpaceBetween
1230 align: AlignItems::Center
1231 gap: SPACE_SM
1232 text {
1233 font_size: 14.0
1234 font_weight: FontWeight::Bold
1235 color: p.get_foreground()
1236 { item.get_title().clone() }
1237 }
1238 row {
1239 gap: SPACE_XS
1240 align: AlignItems::Center
1241 EuvBadge {
1242 label: item.get_category().clone()
1243 tone: EuvTone::Primary
1244 tokens: tokens
1245 }
1246 EuvBadge {
1247 label: item.get_status().clone()
1248 tone: status_tone
1249 tokens: tokens
1250 }
1251 }
1252 }
1253 text {
1254 font_size: 12.5
1255 color: p.get_muted_foreground()
1256 { detail_line }
1257 }
1258 text {
1259 font_size: 12.5
1260 font_weight: FontWeight::SemiBold
1261 color: p.get_foreground()
1262 { metric_line }
1263 }
1264 EuvActionRow {
1265 EuvButton {
1266 label: item.get_button_label().clone()
1267 tokens: tokens
1268 secondary()
1269 sm()
1270 on_click: move |_: &UiEvent| {
1271 execute_stress_case(&st_run, &sid);
1272 }
1273 }
1274 }
1275 }
1276 };
1277 cards.push(item_card);
1278 }
1279 cards
1280 }
1281 }
1282 }
1283 }
1284 }
1285}