Skip to main content

mgui_core/
composition.rs

1//! Layer 合成数学 — GPU 与 CPU 软件光栅器共用。
2//!
3//! 每个 RepaintBoundary layer 只包含自己的内容;合成到 surface 时,
4//! 父层的 Transform / Opacity / ClipRRect 必须显式传给子层,否则子层既不会被
5//! 父层变换,也不会继承透明度/裁剪。本模块把每个 layer 的变换折叠成一个
6//! 仿射矩阵(局部坐标 → surface 逻辑坐标),并携带祖先 clip 与累计透明度。
7//!
8//! 以前 `mgui-runtime::renderer::composition` 与 `mgui-software::layers` 各有一份
9//! 近 190 行的逐行复制实现;任何语义改动都要改两处且容易漂移。现在统一在这里,
10//! 两个后端只负责把 `LayerComposition` 转成各自的着色器/像素操作。
11
12use std::collections::{HashMap, HashSet};
13
14use crate::element::LayerPaint;
15use crate::geometry::{Point, Rect, Size};
16use crate::id::LayerId;
17use crate::paint::LayerEffect;
18
19/// 2D 仿射变换(列向量约定):p' = A·p + t
20#[derive(Clone, Copy, Debug, PartialEq)]
21pub struct Affine2D {
22    pub a: f32,
23    pub b: f32,
24    pub c: f32,
25    pub d: f32,
26    pub tx: f32,
27    pub ty: f32,
28}
29
30impl Affine2D {
31    pub const IDENTITY: Self = Self { a: 1.0, b: 0.0, c: 0.0, d: 1.0, tx: 0.0, ty: 0.0 };
32
33    pub fn translate(x: f32, y: f32) -> Self {
34        Self { tx: x, ty: y, ..Self::IDENTITY }
35    }
36
37    /// self ∘ inner(先 inner,再 self)
38    pub fn then(&self, inner: &Self) -> Self {
39        Self {
40            a: self.a * inner.a + self.b * inner.c,
41            b: self.a * inner.b + self.b * inner.d,
42            c: self.c * inner.a + self.d * inner.c,
43            d: self.c * inner.b + self.d * inner.d,
44            tx: self.a * inner.tx + self.b * inner.ty + self.tx,
45            ty: self.c * inner.tx + self.d * inner.ty + self.ty,
46        }
47    }
48
49    pub fn apply(&self, p: Point) -> Point {
50        Point::new(self.a * p.x + self.b * p.y + self.tx, self.c * p.x + self.d * p.y + self.ty)
51    }
52
53    pub fn apply_rect(&self, rect: Rect) -> Rect {
54        let p0 = self.apply(Point::new(rect.x, rect.y));
55        let p1 = self.apply(Point::new(rect.x + rect.width, rect.y));
56        let p2 = self.apply(Point::new(rect.x, rect.y + rect.height));
57        let p3 = self.apply(Point::new(rect.x + rect.width, rect.y + rect.height));
58        let min_x = p0.x.min(p1.x).min(p2.x).min(p3.x);
59        let min_y = p0.y.min(p1.y).min(p2.y).min(p3.y);
60        let max_x = p0.x.max(p1.x).max(p2.x).max(p3.x);
61        let max_y = p0.y.max(p1.y).max(p2.y).max(p3.y);
62        Rect::new(min_x, min_y, max_x - min_x, max_y - min_y)
63    }
64
65    /// 轴向缩放均值,用于近似圆角半径在父变换下的缩放
66    pub fn scale_hint(&self) -> f32 {
67        let sx = (self.a * self.a + self.c * self.c).sqrt();
68        let sy = (self.b * self.b + self.d * self.d).sqrt();
69        (sx + sy) * 0.5
70    }
71}
72
73#[derive(Clone, Copy, Debug, PartialEq)]
74pub struct ClipShape {
75    /// surface 逻辑坐标(AABB;旋转裁剪按包围盒近似)
76    pub rect: Rect,
77    pub radius: f32,
78}
79
80#[derive(Clone, Debug)]
81pub struct LayerComposition {
82    /// layer 局部坐标 → surface 逻辑坐标
83    pub affine: Affine2D,
84    pub opacity: f32,
85    /// 祖先(含自己)的裁剪,最多保留最内两层
86    pub clips: Vec<ClipShape>,
87}
88
89impl LayerComposition {
90    pub fn single(layer: &LayerPaint, size: Size) -> Self {
91        let own = own_effect(layer.effect, size);
92        let placement = Affine2D::translate(layer.offset.x, layer.offset.y);
93        let affine = placement.then(&own.affine);
94        let mut clips = Vec::new();
95        if let Some(radius) = own.clip_radius {
96            if radius > 0.0 {
97                clips.push(ClipShape {
98                    rect: affine.apply_rect(Rect::new(0.0, 0.0, size.width, size.height)),
99                    radius: radius * affine.scale_hint(),
100                });
101            }
102        }
103        Self { affine, opacity: own.opacity, clips }
104    }
105}
106
107pub struct OwnEffect {
108    pub affine: Affine2D,
109    pub opacity: f32,
110    pub clip_radius: Option<f32>,
111}
112
113pub fn own_effect(effect: LayerEffect, size: Size) -> OwnEffect {
114    match effect {
115        LayerEffect::None => OwnEffect { affine: Affine2D::IDENTITY, opacity: 1.0, clip_radius: None },
116        LayerEffect::Opacity(a) => {
117            OwnEffect { affine: Affine2D::IDENTITY, opacity: a.clamp(0.0, 1.0), clip_radius: None }
118        }
119        LayerEffect::Transform(t) if !t.is_identity() => {
120            let (sin, cos) = t.rotation.sin_cos();
121            let cx = size.width * 0.5;
122            let cy = size.height * 0.5;
123            let a = cos * t.scale_x;
124            let b = -sin * t.scale_y;
125            let c = sin * t.scale_x;
126            let d = cos * t.scale_y;
127            OwnEffect {
128                affine: Affine2D {
129                    a,
130                    b,
131                    c,
132                    d,
133                    tx: cx + t.translate.x - (a * cx + b * cy),
134                    ty: cy + t.translate.y - (c * cx + d * cy),
135                },
136                opacity: 1.0,
137                clip_radius: None,
138            }
139        }
140        LayerEffect::Transform(_) => OwnEffect { affine: Affine2D::IDENTITY, opacity: 1.0, clip_radius: None },
141        LayerEffect::ClipRRect(def) => {
142            OwnEffect { affine: Affine2D::IDENTITY, opacity: 1.0, clip_radius: Some(def.radius.max(0.0)) }
143        }
144    }
145}
146
147/// 根据 `LayerPaint` 的父子关系计算每个 layer 的累积合成参数。
148///
149/// `sizes`:layer 的实际逻辑尺寸(由各后端决定 fallback)。
150///
151/// 该便捷入口每次创建 scratch;每帧复用的后端应持有 [`CompositionScratch`]。
152pub fn resolve_layer_compositions(
153    layers: &[LayerPaint],
154    sizes: &HashMap<LayerId, Size>,
155) -> HashMap<LayerId, LayerComposition> {
156    let mut scratch = CompositionScratch::default();
157    scratch.resolve(layers, sizes);
158    scratch.into_map()
159}
160
161/// P2:可跨帧复用的 composition scratch。
162///
163/// `by_id` / `memo` / `visiting` 在 `resolve` 时 clear 后复用容量,避免每帧分配
164/// 三张表;GPU Renderer 持有一份,软件光栅器可按需使用。
165#[derive(Default)]
166pub struct CompositionScratch {
167    by_id: HashMap<LayerId, usize>,
168    memo: HashMap<LayerId, LayerComposition>,
169    visiting: HashSet<LayerId>,
170}
171
172impl CompositionScratch {
173    /// 重算本帧所有 layer 的合成参数(复用内部容器)。
174    pub fn resolve(&mut self, layers: &[LayerPaint], sizes: &HashMap<LayerId, Size>) {
175        self.by_id.clear();
176        self.by_id.extend(layers.iter().enumerate().map(|(i, lp)| (lp.layer_id, i)));
177        self.memo.clear();
178        self.visiting.clear();
179        for i in 0..layers.len() {
180            self.resolve_one(i, layers, sizes);
181        }
182    }
183
184    /// 查询某个 layer 的合成参数。
185    pub fn get(&self, layer_id: LayerId) -> Option<&LayerComposition> {
186        self.memo.get(&layer_id)
187    }
188
189    fn into_map(mut self) -> HashMap<LayerId, LayerComposition> {
190        std::mem::take(&mut self.memo)
191    }
192
193    fn resolve_one(&mut self, idx: usize, layers: &[LayerPaint], sizes: &HashMap<LayerId, Size>) -> LayerComposition {
194        let lp = &layers[idx];
195        if let Some(c) = self.memo.get(&lp.layer_id) {
196            return c.clone();
197        }
198        if !self.visiting.insert(lp.layer_id) {
199            // 异常环(不应发生):断开继承,避免栈溢出
200            let comp = LayerComposition::single(lp, layer_size(lp, sizes));
201            self.memo.insert(lp.layer_id, comp.clone());
202            return comp;
203        }
204
205        let size = layer_size(lp, sizes);
206        let own = own_effect(lp.effect, size);
207        let parent_idx = lp.parent.and_then(|pid| self.by_id.get(&pid).copied());
208        let (parent_affine, parent_opacity, mut clips, parent_offset) = match parent_idx {
209            Some(pi) => {
210                let pc = self.resolve_one(pi, layers, sizes);
211                (pc.affine, pc.opacity, pc.clips, layers[pi].offset)
212            }
213            None => (Affine2D::IDENTITY, 1.0, Vec::new(), Point::ZERO),
214        };
215
216        let local_offset = Point::new(lp.offset.x - parent_offset.x, lp.offset.y - parent_offset.y);
217        let affine = parent_affine.then(&Affine2D::translate(local_offset.x, local_offset.y)).then(&own.affine);
218
219        if let Some(radius) = own.clip_radius {
220            if radius > 0.0 {
221                clips.push(ClipShape {
222                    rect: affine.apply_rect(Rect::new(0.0, 0.0, size.width, size.height)),
223                    radius: radius * affine.scale_hint(),
224                });
225                // BlitUniform 支持两层裁剪;更多祖先裁剪极少见,保留最内两层
226                if clips.len() > 2 {
227                    clips.remove(0);
228                }
229            }
230        }
231
232        self.visiting.remove(&lp.layer_id);
233        let comp = LayerComposition { affine, opacity: (parent_opacity * own.opacity).clamp(0.0, 1.0), clips };
234        self.memo.insert(lp.layer_id, comp.clone());
235        comp
236    }
237}
238
239fn layer_size(lp: &LayerPaint, sizes: &HashMap<LayerId, Size>) -> Size {
240    sizes.get(&lp.layer_id).copied().or(lp.logical_size).unwrap_or(Size::ZERO)
241}
242
243#[cfg(test)]
244mod tests {
245    use super::*;
246    use crate::arena::Arena;
247
248    fn new_ids(n: usize) -> Vec<LayerId> {
249        let mut arena = Arena::<LayerId, ()>::new();
250        (0..n).map(|_| arena.insert(())).collect()
251    }
252
253    fn layer(id: LayerId, offset: Point, effect: LayerEffect) -> LayerPaint {
254        LayerPaint {
255            layer_id: id,
256            paint_list: std::rc::Rc::new(crate::paint::PaintList::new()),
257            is_dirty: false,
258            parent: None,
259            offset,
260            logical_size: Some(Size::new(100.0, 50.0)),
261            effect,
262        }
263    }
264
265    #[test]
266    fn opacity_and_translation_accumulate() {
267        let ids = new_ids(2);
268        let mut child = layer(ids[1], Point::new(10.0, 20.0), LayerEffect::Opacity(0.5));
269        child.parent = Some(ids[0]);
270        let parent = layer(ids[0], Point::new(5.0, 6.0), LayerEffect::Opacity(0.4));
271        let layers = vec![parent, child];
272        let sizes =
273            layers.iter().map(|lp| (lp.layer_id, lp.logical_size.unwrap_or(Size::ZERO))).collect::<HashMap<_, _>>();
274        let comps = resolve_layer_compositions(&layers, &sizes);
275        let c = &comps[&ids[1]];
276        assert!((c.opacity - 0.2).abs() < 1e-6, "父透明度应乘到子层");
277        // 子层 offset 是 surface 绝对坐标,父 offset 不重复累加
278        assert_eq!(c.affine.apply(Point::ZERO), Point::new(10.0, 20.0));
279    }
280
281    #[test]
282    fn clip_keeps_at_most_two_layers() {
283        let ids = new_ids(3);
284        let mut l1 = layer(ids[0], Point::ZERO, LayerEffect::ClipRRect(crate::RRectDef { radius: 4.0 }));
285        let mut l2 = layer(ids[1], Point::ZERO, LayerEffect::ClipRRect(crate::RRectDef { radius: 6.0 }));
286        let mut l3 = layer(ids[2], Point::ZERO, LayerEffect::ClipRRect(crate::RRectDef { radius: 8.0 }));
287        l2.parent = Some(l1.layer_id);
288        l3.parent = Some(l2.layer_id);
289        l1.parent = None;
290        let layers = vec![l1, l2, l3];
291        let sizes =
292            layers.iter().map(|lp| (lp.layer_id, lp.logical_size.unwrap_or(Size::ZERO))).collect::<HashMap<_, _>>();
293        let comps = resolve_layer_compositions(&layers, &sizes);
294        assert_eq!(comps[&ids[2]].clips.len(), 2, "最多保留最内两层 clip");
295    }
296
297    /// P2:复用 scratch 的结果必须与一次性 API 完全一致,且下一帧清掉旧 layer。
298    #[test]
299    fn composition_scratch_matches_eager_and_clears_between_frames() {
300        let ids = new_ids(3);
301        let mut parent = layer(ids[0], Point::new(10.0, 20.0), LayerEffect::Opacity(0.5));
302        let mut child = layer(ids[1], Point::new(12.0, 26.0), LayerEffect::None);
303        child.parent = Some(parent.layer_id);
304        parent.parent = None;
305        let layers = vec![parent, child];
306        let sizes =
307            layers.iter().map(|lp| (lp.layer_id, lp.logical_size.unwrap_or(Size::ZERO))).collect::<HashMap<_, _>>();
308
309        let eager = resolve_layer_compositions(&layers, &sizes);
310        let mut scratch = CompositionScratch::default();
311        scratch.resolve(&layers, &sizes);
312        for lp in &layers {
313            let a = &eager[&lp.layer_id];
314            let b = scratch.get(lp.layer_id).expect("scratch composition");
315            assert_eq!(a.affine, b.affine);
316            assert_eq!(a.opacity, b.opacity);
317            assert_eq!(a.clips, b.clips);
318        }
319
320        // 下一帧只剩一个 layer:旧 id 必须被清掉
321        let one = vec![layer(ids[0], Point::new(10.0, 20.0), LayerEffect::Opacity(0.5))];
322        scratch.resolve(&one, &sizes);
323        assert!(scratch.get(ids[0]).is_some());
324        assert!(scratch.get(ids[1]).is_none(), "新一帧不应保留旧 layer 的 composition");
325    }
326}