mgui_core/render_object/mod.rs
1//! RenderObject 子系统
2//!
3//! RenderObject 是 GUI 框架的渲染节点,负责布局(layout)和绘制(paint)。
4//! 每个 RenderObject 是一棵树上的节点,父节点向子节点传递 `BoxConstraints`,
5//! 子节点返回自身 `Size`,然后父节点确定子节点位置。
6//!
7//! 阶段 1 提供:
8//! - `RenderObject` trait
9//! - 叶子: `RRectRenderObject`(圆角矩形)
10//! - 容器: `ColumnRenderObject`(垂直堆叠)、`PaddingRenderObject`(四边等值内边距)
11//! - 绝对定位: `PositionedRenderObject`(在父容器内按 offset 摆放)
12//! - 多子叠加: `StackRenderObject`(多个子节点按各自 offset 叠加,适合 root)
13
14use crate::id::ElementId;
15use crate::paint::PaintList;
16use crate::reactive::Signal;
17use crate::{Color, Point, Rect, Size};
18use std::any::Any;
19use std::cell::{Cell, Ref, RefCell, RefMut};
20use std::rc::Rc;
21
22/// state → RO 就地更新的结果(P0-1 API,见架构审查 §11)
23#[derive(Clone, Copy, Debug, PartialEq, Eq)]
24pub enum StateApply {
25 /// 当前 RO 不支持由 state 就地更新(默认;框架回退 create_render_object)
26 Unsupported,
27 /// 已读取 state,但 layout/paint 的输入没有变化(无需标脏)
28 Unchanged,
29 /// 已就地更新,现有 layout/paint 需要重跑
30 Updated,
31}
32
33/// 共享 RO 的内部单元:RO 本体 + 跨帧布局缓存。
34struct RoCell {
35 ro: RefCell<Box<dyn RenderObject>>,
36 /// 子树内有影响布局的变化,下一次 layout_cached 必须真正执行。
37 layout_dirty: Cell<bool>,
38 /// 上次 layout 的约束与结果(约束相同且 clean 时直接复用)。
39 layout_cache: Cell<Option<(BoxConstraints, Size)>>,
40}
41
42/// 共享 RO —— `Rc<RoCell>`
43///
44/// 除 RO 本体的 `RefCell` 外,还携带布局 dirty/约束缓存,供容器在
45/// `layout_cached` 中跳过 clean 子树(容器级脏子树裁剪)。
46#[derive(Clone)]
47pub struct SharedRO(Rc<RoCell>);
48
49impl SharedRO {
50 pub fn borrow(&self) -> Ref<'_, Box<dyn RenderObject>> {
51 self.0.ro.borrow()
52 }
53
54 pub fn borrow_mut(&self) -> RefMut<'_, Box<dyn RenderObject>> {
55 self.0.ro.borrow_mut()
56 }
57
58 pub fn ptr_eq(&self, other: &SharedRO) -> bool {
59 Rc::ptr_eq(&self.0, &other.0)
60 }
61
62 pub fn mark_layout_dirty(&self) {
63 self.0.layout_dirty.set(true);
64 }
65
66 pub fn is_layout_dirty(&self) -> bool {
67 self.0.layout_dirty.get()
68 }
69
70 /// 只读快照:上一次 `layout_cached` 使用的约束与返回尺寸(从未布局过时为 None)。
71 ///
72 /// 供 Inspector 的布局 overlay 展示「这个元素被告知可用多大」;
73 /// 纯读取,不改 dirty/cache,因此不影响渲染路径。
74 pub fn layout_snapshot(&self) -> Option<(BoxConstraints, Size)> {
75 self.0.layout_cache.get()
76 }
77
78 /// 带缓存的 layout:clean 且约束与上次相同时直接返回上次 size。
79 pub fn layout_cached(&self, constraints: BoxConstraints, ctx: &mut LayoutContext) -> Size {
80 if !self.0.layout_dirty.get() {
81 if let Some((cached_constraints, size)) = self.0.layout_cache.get() {
82 if cached_constraints == constraints {
83 return size;
84 }
85 }
86 }
87 let size = self.0.ro.borrow_mut().layout(constraints, ctx);
88 self.0.layout_dirty.set(false);
89 self.0.layout_cache.set(Some((constraints, size)));
90 size
91 }
92}
93
94/// 便捷构造:`Box<dyn RO>` → SharedRO
95/// 避免到处写 `Rc::new(RefCell::new(ro))`
96pub fn make_ro_shared(ro: Box<dyn RenderObject>) -> SharedRO {
97 SharedRO(Rc::new(RoCell { ro: RefCell::new(ro), layout_dirty: Cell::new(true), layout_cache: Cell::new(None) }))
98}
99
100/// 布局约束(Flutter 范式:父→子 min/max,子→父 size)
101#[derive(Clone, Copy, Debug, PartialEq)]
102pub struct BoxConstraints {
103 pub min_width: f32,
104 pub max_width: f32,
105 pub min_height: f32,
106 pub max_height: f32,
107}
108
109impl BoxConstraints {
110 /// 无约束(子节点可以无限大)
111 pub const UNBOUNDED: Self =
112 Self { min_width: 0.0, max_width: f32::INFINITY, min_height: 0.0, max_height: f32::INFINITY };
113
114 /// 强制子节点等于给定尺寸
115 pub fn tight(size: Size) -> Self {
116 Self { min_width: size.width, max_width: size.width, min_height: size.height, max_height: size.height }
117 }
118
119 /// 松约束(子节点可在 0..size 内自由决定)
120 pub fn loose(size: Size) -> Self {
121 Self { min_width: 0.0, max_width: size.width, min_height: 0.0, max_height: size.height }
122 }
123
124 /// 把一个尺寸夹紧到约束范围内
125 pub fn constrain(&self, size: Size) -> Size {
126 Size::new(size.width.clamp(self.min_width, self.max_width), size.height.clamp(self.min_height, self.max_height))
127 }
128
129 /// 四边均匀内缩(用于带边框/焦点环的容器给 child 的约束)。
130 /// min 归 0(child 可以任意小),max 减去两侧 inset 并 clamp ≥0
131 /// (防 max < min)。∞ 减有限值仍为 ∞。
132 pub fn inset_uniform(&self, inset: f32) -> Self {
133 Self {
134 min_width: 0.0,
135 max_width: (self.max_width - inset * 2.0).max(0.0),
136 min_height: 0.0,
137 max_height: (self.max_height - inset * 2.0).max(0.0),
138 }
139 }
140
141 /// 约束是否在每个轴上都强制为唯一值(上下界相等)
142 pub fn is_tight(&self) -> bool {
143 self.min_width == self.max_width && self.min_height == self.max_height
144 }
145
146 /// 宽度轴是否被限制为有限值
147 pub fn is_bounded_width(&self) -> bool {
148 self.max_width.is_finite()
149 }
150
151 /// 高度轴是否被限制为有限值
152 pub fn is_bounded_height(&self) -> bool {
153 self.max_height.is_finite()
154 }
155
156 /// 收紧约束到指定的 width/height(等价于 tight + constrain)
157 pub fn tighten(&self, width: f32, height: f32) -> Self {
158 let w = width.clamp(self.min_width, self.max_width);
159 let h = height.clamp(self.min_height, self.max_height);
160 Self::tight(Size::new(w, h))
161 }
162
163 /// 把最小尺寸放宽为 0(返回只保留上限的松约束)
164 pub fn loosen(&self) -> Self {
165 Self { min_width: 0.0, max_width: self.max_width, min_height: 0.0, max_height: self.max_height }
166 }
167}
168
169impl Default for BoxConstraints {
170 fn default() -> Self {
171 Self::UNBOUNDED
172 }
173}
174
175/// 布局上下文(阶段 1 留空,后续可加 baseline、文字方向等)
176#[derive(Default)]
177pub struct LayoutContext;
178
179/// RenderObject 核心 trait
180///
181/// 负责:
182/// - `layout`:在给定约束下确定自身和子节点尺寸,返回自身最终尺寸
183/// - `paint`:在 `offset` 偏移处把绘制命令追加到 `PaintList`
184/// - `hit_test`:在 `position` 处做命中测试,返回命中的 `ElementId`
185/// - `set_element_id`:Element 树 mount 时注入自身 id,默认 noop
186/// - `propagate_element_ids`:容器 RO 把子 element_id 注入到内部子 RO(默认 noop)
187#[deny(missing_docs)]
188pub trait RenderObject {
189 /// 在给定约束下计算并缓存自身尺寸,返回最终 content size。
190 ///
191 /// 容器应在此递归布局子节点(优先走 `SharedRO::layout_cached`),并把
192 /// 子节点相对本 RO 的偏移记录下来供 `child_slots` / `for_each_child` 使用。
193 fn layout(&mut self, constraints: BoxConstraints, ctx: &mut LayoutContext) -> Size;
194
195 /// 把自身内容追加到 `painter`;`offset` 是本 RO 原点在目标坐标系中的位置。
196 fn paint(&self, offset: Point, painter: &mut PaintList);
197
198 /// 命中测试:`position` 为目标坐标系,`offset` 为本 RO 原点;返回命中的 element id。
199 fn hit_test(&self, position: Point, offset: Point) -> Option<ElementId> {
200 let _ = (position, offset);
201 None
202 }
203 /// 本 RO 的**滚动条车道**是否覆盖这个本地坐标点(`local` = 相对本 RO 原点)。
204 ///
205 /// 用途:滚动条画在内容之上,命中测试又是"子树优先"(为了让嵌套容器的滚动条
206 /// 不被外层抢走)。于是一颗**按下即生效**的控件(NavigationMenu / TabBar 等)
207 /// 躺在滚动条下面时,抓滚动条会顺带把它点一下。派发 `PointerDown` 时框架沿命中
208 /// 元素的祖先链向上问这个方法,**最近的那个声明者**接管这颗粒按下(`ElementTree`)。
209 ///
210 /// 只有自带滚动条的容器需要 override(ScrollView / ListView / DataGrid / TreeView);
211 /// 判定范围应当与自己的 `hit_test` / 拖拽判定同源,否则"能拖但下面还是被点了"。
212 /// 默认 `false`(普通控件没有车道概念)。
213 fn scrollbar_lane_hit(&self, _local: Point) -> bool {
214 false
215 }
216 /// Element 树 mount 时调用,让 RO 记录自己归属哪个 Element。
217 /// 阶段 2 仅 `RRectRenderObject` 有 element_id 字段,其他 RO 默认 noop。
218 fn set_element_id(&mut self, _id: ElementId) {}
219 /// 把子 element_id 注入到 RO 内部的子 RO。
220 ///
221 /// 阶段 2 协议:父 RO 在 mount 时调用此方法,把子 Element 的 id 传给自己的子 RO。
222 /// 容器 RO(Stack/Column/Positioned/Padding)override 此方法,叶子 RRect 已经有 element_id 不再需要。
223 ///
224 /// 阶段 3 扩展:`stateful_ros[i] = Some(ro)` 时,父 RO 把第 i 个 child slot 的 RO
225 /// 替换为这个 state-driven RO(覆盖 `widget.create_render_object()` 创建的 widget-driven RO)。
226 /// 这是 state 上提到 Element 层后的关键同步:state 持有 pressed/hover 等可变状态,
227 /// state.create_render_object() 返回的 RO 反映当前状态;但 Element 树的 root RO
228 /// 是从 `widget.create_render_object()` 递归构建的,默认是 widget-driven(不变),
229 /// 所以必须显式把 stateful child slot 替换成 state-driven RO,才能让 paint 反映 state。
230 fn propagate_element_ids(&mut self, _child_ids: &[ElementId], _stateful_ros: &mut [SharedRO]) {}
231
232 /// 阶段 4-D(候选 2):返回 RO 的内容 size(已 layout 后)。
233 ///
234 /// 用于 paint_frame 时把 layer 自己的 size 写到 `Layer.size`,
235 /// Renderer 据此创建对应大小的 GPU texture(小 layer 用小 texture,省 fillrate)。
236 ///
237 /// 默认 ZERO(让 Renderer fallback 全屏 texture 兼容)。叶子 RO + LayerProxy RO
238 /// override 返回真实 size;容器 RO(Stack/Column/Padding)布局复杂,默认 ZERO 即可
239 /// (这些一般不被包在 RepaintBoundary 里,直接走 root layer 全屏 paint)。
240 fn content_size(&self) -> Size {
241 Size::ZERO
242 }
243
244 /// P1-7:显式的有效内容尺寸(finite 且 > 0)。
245 ///
246 /// 默认由 `content_size()` 推导;容器/自定义 RO 可 override 以区分
247 /// “尚未布局”与“真实 ZERO”。layer sizing 不再依赖 ZERO 哨兵。
248 fn content_size_opt(&self) -> Option<Size> {
249 let size = self.content_size();
250 (size.width.is_finite() && size.height.is_finite() && size.width > 0.0 && size.height > 0.0).then_some(size)
251 }
252
253 /// P1-7:layer texture 的尺寸提示:优先真实内容尺寸,其次边界盒子尺寸。
254 ///
255 /// `content_size` 对 FittedBox/RotatedBox 是未缩放/未旋转的纹理尺寸,
256 /// `layer_layout_size` 是父布局中的盒子尺寸;两者都未知时由调用方回退
257 /// layout 返回值/视口,并记录日志。
258 fn layer_size_hint(&self) -> Option<Size> {
259 self.content_size_opt().or_else(|| {
260 self.layer_layout_size()
261 .filter(|s| s.width.is_finite() && s.height.is_finite() && s.width > 0.0 && s.height > 0.0)
262 })
263 }
264
265 /// 边界 RO 在父布局中实际占用的尺寸(供嵌套 layer 局部重排)。
266 ///
267 /// 与 `content_size()` 的区别:FittedBox/RotatedBox 的 content_size 是
268 /// **未缩放/未旋转的纹理尺寸**,而父布局尺寸才是子层再次 layout 时的盒子。
269 /// 默认 None = 未知(调用方保持原 UNBOUNDED 行为)。
270 fn layer_layout_size(&self) -> Option<Size> {
271 None
272 }
273
274 /// 嵌套 layer 局部重排时对该边界根使用的约束(默认 loose:允许内容收缩)。
275 ///
276 /// 变换类边界(FittedBox/RotatedBox)的盒子尺寸由 `constrain(child)` 推导,
277 /// 用 loose(已知盒子) 重排会把它收缩到 child 自然尺寸、把 transform 算错;
278 /// 它们覆盖为 tight(已知盒子),保证重排幂等。
279 fn layer_relayout_constraints(&self, layout_size: Size) -> BoxConstraints {
280 BoxConstraints::loose(layout_size)
281 }
282
283 /// bugfix(showcase effect 色块不显示):作为 **layer root** 收集本层内容时调用
284 /// (paint_layer_recursive 专用)。
285 ///
286 /// 边界 RO(RepaintBoundary / Transform / Opacity / ClipRRect)的 `paint` 是
287 /// noop —— 语义是"父层的 paint 走到这里必须跳过子树,内容由子 layer 的 GPU
288 /// texture 合成"。但这要求 effect 容器的 child 自己也是一个 boundary(有自己的
289 /// layer),否则**没有任何人把 child 内容画进 effect layer** → cmds=0 → 整层
290 /// 不可见(fx 区 effect layer 回归 fx_zone_effect_layers_paint_all_rects 实锤)。
291 ///
292 /// 默认实现 = `self.paint`(普通容器 RO 就是本层内容本身);边界 RO override
293 /// 为 `child.paint`(透传内容)。透传递归中若再遇到边界 RO(嵌套 layer),
294 /// 其 `paint` 仍是 noop,自动排除 —— 不会与子 layer 的 texture 重复。
295 fn paint_as_layer_root(&self, offset: Point, painter: &mut PaintList) {
296 self.paint(offset, painter);
297 }
298
299 /// 阶段 4-D:容器 RO 暴露 push_child 让 Element 层在 mount 时填 children RO。
300 /// 默认 noop(叶子 RO)。容器 RO(Stack/Column/ListView)override 实现 push 语义。
301 ///
302 /// **可扩展**:加 Padding/Positioned/ClipRRect 等容器时,override 此方法实现各自 push 语义。
303 /// leaf RO 不需要 override。
304 fn push_child(&mut self, _offset: Point, _child: SharedRO) {
305 // 叶子 RO 默认 noop
306 }
307
308 /// 阶段 4-D:容器 RO 的 children 数量(让 Element 层知道 RO 是否还有空 slot)
309 /// 默认 0(叶子 RO 没有 children)
310 fn children_count(&self) -> usize {
311 0
312 }
313
314 /// 阶段 5:返回此 RO 携带的 layer 视觉效果(Transform / Opacity / ClipRRect...)
315 ///
316 /// Element 层 mount RepaintBoundary 子类时调 `ro.layer_effect()` 把 effect
317 /// 写到 `Layer.effect`,Renderer Pass 2 blit 走 shader 对应分支。
318 ///
319 /// 默认 `None`(无效果 — 90% 的 layer 不需要 effect,shader 走快速路径)。
320 /// - RRect / Text / Image 等叶子 RO:None(自己直接画,没 layer 概念)
321 /// - RepaintBoundary 叶子 RO:None(只是个 layer 边界,不带 effect)
322 /// - **TransformRenderObject** / **OpacityRenderObject** / **ClipRRectRenderObject**:
323 /// override 返回对应 effect
324 fn layer_effect(&self) -> crate::paint::LayerEffect {
325 crate::paint::LayerEffect::None
326 }
327
328 /// 阶段 2-E:RO 持有的 element_id(未设置 = None)
329 ///
330 /// 用于 `ElementTree::element_origin` 等 RO 树遍历(IME 光标定位:
331 /// 焦点 element 的窗口坐标)。叶子 RO override 返回自己的 element_id。
332 fn element_id(&self) -> Option<ElementId> {
333 None
334 }
335
336 /// 阶段 5-G:由 ElementTree 在 mount/update 时调用,把 element 的
337 /// `SubscriberId` 注入 RO。**只在 paint/hit_test 期间作为 signal 的
338 /// subscriber 用**——PositionedRenderObject 之类持 Signal 的 RO override 此钩子;
339 /// 其他 RO 默认 noop。
340 fn set_subscriber_id(&mut self, _id: crate::reactive::SubscriberId) {}
341
342 /// 阶段 2-E:子 (offset, RO) 槽位 — layout 后的最终位置(相对本 RO 原点)
343 ///
344 /// `element_origin` 沿 RO 树 DFS 时用。容器 RO override。
345 /// **局限**:嵌套 layer(RepaintBoundary)内的子树,其 layer 相对父 layer
346 /// 的 blit offset 不在此遍历内(阶段 2-E 简化;TextField 演示不包 RB)。
347 fn child_slots(&self) -> Vec<(Point, SharedRO)> {
348 Vec::new()
349 }
350
351 /// P1-7:无分配遍历直接子槽(offset 相对本 RO 原点)。
352 ///
353 /// 默认委托 `child_slots()`(会分配 Vec);容器 RO 应 override 为直接迭代。
354 /// origin / a11y bounds / 协议审计等 DFS 热路径使用此入口。
355 fn for_each_child(&self, f: &mut dyn FnMut(Point, &SharedRO)) {
356 for (offset, child) in self.child_slots() {
357 f(offset, &child);
358 }
359 }
360
361 /// P0-1:由具体 RO 从 state 读取可变量并**就地**写回自身。
362 ///
363 /// 默认 `Unsupported` = 框架回退 `State::create_render_object`(行为不变)。
364 /// 实现约定(详见架构审查 §11):
365 /// - 只能修改自身字段;不得替换自身、child slot 或任何子 RO;
366 /// - 修改了几何输入必须失效自身布局缓存;
367 /// - 结构/类型变化,或实现不确定时返回 `Unsupported`;
368 /// - 必须可重复调用,不得依赖调用次数。
369 fn apply_state(&mut self, _state: &mut dyn Any) -> StateApply {
370 StateApply::Unsupported
371 }
372}
373
374/// 让 `Box<T>` 自动转发 `RenderObject` 方法,
375/// 这样 `ColumnRenderObject::push(Box<dyn RenderObject>)` 等能直接通过。
376///
377/// orphan rule:`RenderObject` 是本 crate 的 trait,所以即使 `Box` 来自 std,
378/// 给 `Box<T: RenderObject + ?Sized>` impl 也是允许的。
379impl<T: RenderObject + ?Sized> RenderObject for Box<T> {
380 fn layout(&mut self, constraints: BoxConstraints, ctx: &mut LayoutContext) -> Size {
381 (**self).layout(constraints, ctx)
382 }
383 fn paint(&self, offset: Point, painter: &mut PaintList) {
384 (**self).paint(offset, painter);
385 }
386 fn hit_test(&self, position: Point, offset: Point) -> Option<ElementId> {
387 (**self).hit_test(position, offset)
388 }
389 fn scrollbar_lane_hit(&self, local: Point) -> bool {
390 (**self).scrollbar_lane_hit(local)
391 }
392 fn set_element_id(&mut self, id: ElementId) {
393 (**self).set_element_id(id);
394 }
395 fn propagate_element_ids(&mut self, child_ids: &[ElementId], stateful_ros: &mut [SharedRO]) {
396 (**self).propagate_element_ids(child_ids, stateful_ros);
397 }
398 /// 阶段 4-D:Box 必须转发 content_size,否则 `Box<dyn RenderObject>` 调 content_size
399 /// 会走 RenderObject trait 默认实现(返回 ZERO),丢失真正的 size。
400 fn content_size(&self) -> Size {
401 (**self).content_size()
402 }
403 fn content_size_opt(&self) -> Option<Size> {
404 (**self).content_size_opt()
405 }
406 fn layer_size_hint(&self) -> Option<Size> {
407 (**self).layer_size_hint()
408 }
409 fn layer_layout_size(&self) -> Option<Size> {
410 (**self).layer_layout_size()
411 }
412 fn layer_relayout_constraints(&self, layout_size: Size) -> BoxConstraints {
413 (**self).layer_relayout_constraints(layout_size)
414 }
415 /// bugfix:Box 转发 paint_as_layer_root 到内层(否则边界 RO 被包在 Box 里时
416 /// 会走默认 self.paint,丢失透传语义)。
417 fn paint_as_layer_root(&self, offset: Point, painter: &mut PaintList) {
418 (**self).paint_as_layer_root(offset, painter)
419 }
420 /// 阶段 5:Box 转发 layer_effect 到内层
421 fn layer_effect(&self) -> crate::paint::LayerEffect {
422 (**self).layer_effect()
423 }
424 /// 阶段 5-G:Box 转发 set_subscriber_id 到内层(否则 Box 默认 noop 会吞掉
425 /// PositionedRenderObject 等 override 的钩子调用,导致 Signal 订阅链路断裂)
426 fn set_subscriber_id(&mut self, id: crate::reactive::SubscriberId) {
427 (**self).set_subscriber_id(id);
428 }
429 /// 阶段 2-E:Box 转发 element_id
430 fn element_id(&self) -> Option<ElementId> {
431 (**self).element_id()
432 }
433 /// 阶段 2-E:Box 转发 child_slots
434 fn child_slots(&self) -> Vec<(Point, SharedRO)> {
435 (**self).child_slots()
436 }
437 /// 阶段 4-D:Box 必须转发 push_child,否则 `Box<dyn RenderObject>` 走默认 noop,
438 /// Element 层 mount 时填不进子 RO。
439 fn push_child(&mut self, offset: Point, child: SharedRO) {
440 (**self).push_child(offset, child);
441 }
442 /// 阶段 4-D:Box 必须转发 children_count,否则默认 0 会让 slot 计数失真。
443 fn children_count(&self) -> usize {
444 (**self).children_count()
445 }
446 fn for_each_child(&self, f: &mut dyn FnMut(Point, &SharedRO)) {
447 (**self).for_each_child(f)
448 }
449 /// P0-1:Box 必须转发 apply_state,否则 `Box<dyn RenderObject>` 会走默认
450 /// `Unsupported`,所有就地更新都被静默跳过。
451 fn apply_state(&mut self, state: &mut dyn Any) -> StateApply {
452 (**self).apply_state(state)
453 }
454}
455
456// =================================================================
457// 阶段 5:effect 几何辅助函数
458// =================================================================
459
460/// 阶段 5:点是否在圆角矩形内(几何等价于 shader 的 RRect alpha mask)
461pub fn point_in_rrect(p: Point, rect_origin: Point, size: Size, radius: f32) -> bool {
462 if size.width <= 0.0 || size.height <= 0.0 {
463 return false;
464 }
465 let r = radius.max(0.0);
466 let left = rect_origin.x;
467 let top = rect_origin.y;
468 let right = left + size.width;
469 let bottom = top + size.height;
470 if p.x < left || p.x > right || p.y < top || p.y > bottom {
471 return false;
472 }
473 // 4 个角区域:以 corner center 为圆心,半径 r,点在圆外则不在 rrect 内
474 let r = r.min(size.width * 0.5).min(size.height * 0.5);
475 if r <= 0.0 {
476 return true; // 直角矩形,前面 bounds 判定通过即可
477 }
478 // 4 个 corner center
479 let c_tl = Point::new(left + r, top + r);
480 let c_tr = Point::new(right - r, top + r);
481 let c_bl = Point::new(left + r, bottom - r);
482 let c_br = Point::new(right - r, bottom - r);
483 // 左上角
484 if p.x < c_tl.x && p.y < c_tl.y {
485 return dist_sq(p, c_tl) <= r * r;
486 }
487 // 右上角
488 if p.x > c_tr.x && p.y < c_tr.y {
489 return dist_sq(p, c_tr) <= r * r;
490 }
491 // 左下角
492 if p.x < c_bl.x && p.y > c_bl.y {
493 return dist_sq(p, c_bl) <= r * r;
494 }
495 // 右下角
496 if p.x > c_br.x && p.y > c_br.y {
497 return dist_sq(p, c_br) <= r * r;
498 }
499 // 不在 corner 区域,前面 bounds 判定通过即可
500 true
501}
502
503fn dist_sq(a: Point, b: Point) -> f32 {
504 let dx = a.x - b.x;
505 let dy = a.y - b.y;
506 dx * dx + dy * dy
507}
508
509/// 阶段 5:把世界坐标 `p` 通过 Transform2D 反向变换到 layer 局部坐标
510///
511/// `forward(world_p) = R(rot) * S(sx, sy) * (local_p - center) + center + translate`
512/// 反向:
513/// `local_p = S(1/sx, 1/sy) * R(-rot) * (world_p - center - translate) + center`
514pub fn inverse_apply_transform(world_p: Point, t: crate::Transform2D, cx: f32, cy: f32) -> Point {
515 // 正向 = c + t + R(θ)·S·(p-c);逆变换必须按 S⁻¹·R⁻¹ 的顺序:
516 // 先反旋转,再反缩放。非均匀缩放时 R⁻¹·S⁻¹ 与 S⁻¹·R⁻¹ 不相等,
517 // 先除缩放会导致旋转+拉伸组合的命中坐标偏移。
518 let px = world_p.x - cx - t.translate.x;
519 let py = world_p.y - cy - t.translate.y;
520 let c = (-t.rotation).cos();
521 let sn = (-t.rotation).sin();
522 let rx = px * c - py * sn;
523 let ry = px * sn + py * c;
524 // 反向缩放(两轴独立;退化值兜底为 1.0 避免除零)
525 let sx = if t.scale_x.abs() < 1e-6 { 1.0 } else { t.scale_x };
526 let sy = if t.scale_y.abs() < 1e-6 { 1.0 } else { t.scale_y };
527 Point::new(rx / sx + cx, ry / sy + cy)
528}
529
530// =================================================================
531// 容器节点共享 slot
532// =================================================================
533
534struct ChildSlot {
535 child: SharedRO,
536 cached_size: Size,
537}
538
539// =================================================================
540// Submodule declarations
541// =================================================================
542
543pub mod border;
544pub mod clip_rrect;
545pub mod column;
546pub mod layer_proxy;
547pub mod margin;
548pub mod opacity;
549pub mod padding;
550pub mod positioned;
551pub mod proxy;
552pub mod rrect;
553pub mod stack;
554pub mod transform;
555
556// 组件专属 RO 已迁到 mgui-components/src/render_object/ (button/checkbox/slider/switch_ro/progress/focus_scope/scroll_view)
557
558// #[cfg(test)]
559// pub mod tests; // 已迁到 crates/mgui-test/tests/render_object.rs
560
561// =================================================================
562// Re-exports (保持全部原始 pub 名)
563// =================================================================
564
565pub use border::{Border, BorderRenderObject};
566pub use clip_rrect::ClipRRectRenderObject;
567pub use column::ColumnRenderObject;
568pub use layer_proxy::LayerProxyRenderObject;
569pub use margin::MarginRenderObject;
570pub use opacity::OpacityRenderObject;
571pub use padding::EdgeInsets;
572pub use padding::PaddingRenderObject;
573pub use positioned::PositionedRenderObject;
574pub use proxy::ProxyRenderObject;
575pub use rrect::RRectRenderObject;
576pub use stack::StackRenderObject;
577pub use transform::TransformRenderObject;