Skip to main content

velox_engine/platform/
testing.rs

1//! 确定性无头自动化测试平台 `TestingPlatform`。
2//!
3//! 支持 `#![no_std]` 环境,提供泛型像素格式 `P: PixelFormat`(默认 [`Rgb565`],亦可指定 [`Rgba8888`] 或 [`crate::display::Xrgb8888`])、
4//! 虚拟单调时钟步进、输入事件队列注入、异形屏安全区与离屏像素帧缓冲断言。
5
6use core::time::Duration;
7
8use crate::arena::SmallVec;
9use crate::display::{PixelFormat, Rgb565, Rgba8888};
10use crate::engine::VeloxEngine;
11use crate::platform::mobile::{CDirtyRect, DeviceOrientation, TouchPhase};
12use crate::platform::{FlushReport, Platform, PlatformControlFlow, PlatformSurface};
13use crate::pod::{InputEvent, KeyCode, SafeAreaInsets};
14use crate::solver::Region;
15
16/// 确定性无头测试平台(支持泛型像素格式 `P`,默认 `320x240` `Rgb565`)。
17///
18/// 同时作为 `#![no_std]` 固定分辨率移动端([`MobilePlatform`](crate::platform::mobile::MobilePlatform))与
19/// WebAssembly `<canvas>`([`WebPlatform`](crate::platform::web::WebPlatform))的统一底层实现。
20pub struct TestingPlatform<
21    const W: usize = 320,
22    const H: usize = 240,
23    P: PixelFormat = Rgb565,
24> {
25    pub framebuffer: [[P; W]; H],
26    pending_events: SmallVec<InputEvent, 32>,
27    last_dirty: SmallVec<Region, 8>,
28    last_dirty_rects: SmallVec<CDirtyRect, 8>,
29    primary_touch_id: Option<u32>,
30    orientation: DeviceOrientation,
31    safe_area: SafeAreaInsets,
32    safe_area_dirty: bool,
33    elapsed_ms: u64,
34    pub total_frames_rendered: u32,
35}
36
37impl<const W: usize, const H: usize, P: PixelFormat> Default for TestingPlatform<W, H, P> {
38    fn default() -> Self {
39        Self::new()
40    }
41}
42
43impl<const W: usize, const H: usize, P: PixelFormat> TestingPlatform<W, H, P> {
44    pub const fn new() -> Self {
45        let is_portrait = H > W;
46        Self {
47            framebuffer: [[P::BLACK; W]; H],
48            pending_events: SmallVec::new(),
49            last_dirty: SmallVec::new(),
50            last_dirty_rects: SmallVec::new(),
51            primary_touch_id: None,
52            orientation: DeviceOrientation::Portrait,
53            safe_area: if is_portrait {
54                SafeAreaInsets::phone_portrait()
55            } else {
56                SafeAreaInsets::new(0, 0, 0, 0)
57            },
58            safe_area_dirty: is_portrait,
59            elapsed_ms: 0,
60            total_frames_rendered: 0,
61        }
62    }
63
64    /// 注入一条模拟输入事件。
65    pub fn send_event(&mut self, event: InputEvent) {
66        self.pending_events.push(event);
67    }
68
69    /// 模拟在 `(x, y)` 处按下并抬起完成一次点击。
70    pub fn send_click(&mut self, x: i16, y: i16) {
71        self.pending_events.push(InputEvent::PointerDown { x, y });
72        self.pending_events.push(InputEvent::PointerUp { x, y });
73    }
74
75    /// 注入浏览器/桌面 `pointerdown` 事件。
76    pub fn on_pointer_down(&mut self, x: i16, y: i16) {
77        self.pending_events.push(InputEvent::PointerDown { x, y });
78    }
79
80    /// 注入浏览器/桌面 `pointermove` 事件(自动合并连续移动事件)。
81    pub fn on_pointer_move(&mut self, x: i16, y: i16) {
82        if let Some(InputEvent::PointerMove {
83            x: last_x,
84            y: last_y,
85        }) = self.pending_events.as_mut_slice().last_mut()
86        {
87            *last_x = x;
88            *last_y = y;
89        } else {
90            self.pending_events.push(InputEvent::PointerMove { x, y });
91        }
92    }
93
94    /// 注入浏览器/桌面 `pointerup` 事件。
95    pub fn on_pointer_up(&mut self, x: i16, y: i16) {
96        self.pending_events.push(InputEvent::PointerUp { x, y });
97    }
98
99    /// 注入浏览器/桌面 `pointercancel` 事件。
100    pub fn on_pointer_cancel(&mut self) {
101        self.pending_events.push(InputEvent::PointerCancel);
102    }
103
104    /// 注入滚轮滚动事件。
105    pub fn on_wheel(&mut self, x: i16, y: i16, delta_y: i16) {
106        self.pending_events
107            .push(InputEvent::Scroll { x, y, delta_y });
108    }
109
110    /// 注入键盘按下事件。
111    pub fn on_key_down(&mut self, key: KeyCode) {
112        self.pending_events.push(InputEvent::KeyDown(key));
113    }
114
115    /// 注入浏览器 `popstate` 后退事件。
116    pub fn on_popstate_back(&mut self) {
117        self.pending_events.push(InputEvent::NavigateBack);
118    }
119
120    /// 注入移动端单指/多指触控事件(自动锁定主触控点 `primary_touch_id` 并合并高频 `Moved` 事件)。
121    pub fn on_touch(&mut self, touch_id: u32, phase: TouchPhase, x: i16, y: i16) {
122        match phase {
123            TouchPhase::Began => {
124                if self.primary_touch_id.is_none() {
125                    self.primary_touch_id = Some(touch_id);
126                    self.pending_events.push(InputEvent::PointerDown { x, y });
127                }
128            }
129            TouchPhase::Moved => {
130                if self.primary_touch_id == Some(touch_id) {
131                    self.on_pointer_move(x, y);
132                }
133            }
134            TouchPhase::Ended => {
135                if self.primary_touch_id == Some(touch_id) {
136                    self.primary_touch_id = None;
137                    self.pending_events.push(InputEvent::PointerUp { x, y });
138                }
139            }
140            TouchPhase::Cancelled => {
141                if self.primary_touch_id == Some(touch_id) {
142                    self.primary_touch_id = None;
143                    self.pending_events.push(InputEvent::PointerCancel);
144                }
145            }
146        }
147    }
148
149    /// 切换移动设备屏幕朝向并同步更新默认异形屏安全区域。
150    pub fn set_orientation(&mut self, orientation: DeviceOrientation) {
151        if self.orientation != orientation {
152            self.orientation = orientation;
153            self.safe_area = match orientation {
154                DeviceOrientation::Portrait => SafeAreaInsets::phone_portrait(),
155                DeviceOrientation::LandscapeLeft => SafeAreaInsets::new(0, 0, 21, 44),
156                DeviceOrientation::LandscapeRight => SafeAreaInsets::new(0, 44, 21, 0),
157                DeviceOrientation::PortraitUpsideDown => SafeAreaInsets::new(34, 0, 44, 0),
158            };
159            self.safe_area_dirty = true;
160        }
161    }
162
163    /// 更新异形屏安全区域内边距。
164    pub fn set_safe_area(&mut self, insets: SafeAreaInsets) {
165        self.safe_area = insets;
166        self.safe_area_dirty = false;
167        self.pending_events.push(InputEvent::SafeAreaChanged(insets));
168    }
169
170    /// 触发系统返回导航(Android 返回键 / 边缘右滑返回),返回是否被当前页面消费。
171    pub fn handle_back(&mut self, engine: &mut VeloxEngine) -> bool {
172        engine.dispatch_navigate_back()
173    }
174
175    /// 获取最近一帧合并计算的脏矩形切片([`Region`] 格式)。
176    #[inline(always)]
177    pub fn last_dirty_regions(&self) -> &[Region] {
178        self.last_dirty.as_slice()
179    }
180
181    /// 获取最近一帧合并计算的脏矩形切片(FFI 兼容 [`CDirtyRect`] 格式)。
182    #[inline(always)]
183    pub fn dirty_rects(&self) -> &[CDirtyRect] {
184        self.last_dirty_rects.as_slice()
185    }
186
187    /// 获取展平的只读像素帧缓冲切片。
188    pub fn pixels(&self) -> &[P] {
189        unsafe { core::slice::from_raw_parts(self.framebuffer.as_ptr() as *const P, W * H) }
190    }
191}
192
193impl<const W: usize, const H: usize> TestingPlatform<W, H, Rgba8888> {
194    /// 获取供 FFI / WebAssembly `Uint8ClampedArray` 直接引用的 `RGBA8888` 像素首地址。
195    #[inline(always)]
196    pub fn rgba_ptr(&self) -> *const u8 {
197        self.framebuffer.as_ptr() as *const u8
198    }
199
200    /// 获取 `RGBA8888` 帧缓冲区的总字节长度(`W * H * 4`)。
201    #[inline(always)]
202    pub const fn rgba_byte_len(&self) -> usize {
203        W * H * 4
204    }
205}
206
207impl<const W: usize, const H: usize, P: PixelFormat> PlatformSurface
208    for TestingPlatform<W, H, P>
209{
210    #[inline(always)]
211    fn surface_size(&self) -> (i16, i16) {
212        (W as i16, H as i16)
213    }
214
215    fn flush_frame_dt(&mut self, engine: &mut VeloxEngine, dt_ms: u16) -> FlushReport {
216        self.last_dirty.clear();
217        self.last_dirty_rects.clear();
218        for &r in engine.step_frame_dt(dt_ms) {
219            self.last_dirty.push(r);
220            self.last_dirty_rects.push(CDirtyRect {
221                x: r.x,
222                y: r.y,
223                w: r.w,
224                h: r.h,
225            });
226        }
227        if self.last_dirty.is_empty() {
228            return FlushReport::default();
229        }
230        let fb_slice = unsafe {
231            core::slice::from_raw_parts_mut(self.framebuffer.as_mut_ptr() as *mut P, W * H)
232        };
233        let mut px_count = 0usize;
234        for &reg in self.last_dirty.as_slice() {
235            engine.rasterize_region(reg, fb_slice);
236            px_count += (reg.w.max(0) as usize) * (reg.h.max(0) as usize);
237        }
238        self.total_frames_rendered += 1;
239        FlushReport {
240            dirty_regions: self.last_dirty.len(),
241            strips_or_buffers: 1,
242            pixels_updated: px_count,
243        }
244    }
245}
246
247impl<const W: usize, const H: usize, P: PixelFormat> Platform for TestingPlatform<W, H, P> {
248    #[inline(always)]
249    fn duration_since_start(&self) -> Duration {
250        Duration::from_millis(self.elapsed_ms)
251    }
252
253    fn step_platform(&mut self, engine: &mut VeloxEngine, dt_ms: u16) -> PlatformControlFlow {
254        self.elapsed_ms = self.elapsed_ms.saturating_add(dt_ms as u64);
255        if self.safe_area_dirty {
256            self.safe_area_dirty = false;
257            engine.set_safe_area(self.safe_area);
258        }
259        let mut events: SmallVec<InputEvent, 32> = SmallVec::new();
260        for ev in self.pending_events.as_slice() {
261            events.push(*ev);
262        }
263        self.pending_events.clear();
264        for ev in events.as_slice() {
265            engine.dispatch_event(*ev);
266        }
267        let report = self.flush_frame_dt(engine, dt_ms);
268        if report.has_updates() || engine.needs_redraw() {
269            PlatformControlFlow::Poll
270        } else {
271            PlatformControlFlow::Wait
272        }
273    }
274}