Skip to main content

gpui/fast/layers/
scene.rs

1// Modified by Longbridge for gpui-fast.
2//! What the core hands a renderer about scroll layers: the tiles it
3//! composites, as polychrome sprites whose texture id lies in a range no
4//! atlas allocates, and the content those tiles are rasterized from.
5
6use crate::{
7    AtlasTextureId, AtlasTextureKind, Bounds, Point, Rgba, ScaledPixels, Scene, TileId, point,
8    scene::{PaintOperation, Primitive, TransformationMatrix},
9    size,
10};
11use std::rc::Rc;
12
13/// A live scroll layer, stable while it lives.
14#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
15pub struct LayerKey(pub u32);
16
17/// A tile of a layer's content space, in units of the tile size.
18#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
19pub struct TileCoord {
20    /// The tile's column; tile `x` starts at `x * tile_size` device pixels.
21    pub x: i32,
22    /// The tile's row; tile `y` starts at `y * tile_size` device pixels.
23    pub y: i32,
24}
25
26/// The first texture index of layer tiles; atlases allocate indices from 0.
27pub const LAYER_TILE_TEXTURE_BASE: u32 = 0xF000_0000;
28pub(crate) const LAYER_KEY_LIMIT: u32 = 0x0100_0000;
29const TILE_COORD_BIAS: i32 = 2048;
30
31/// The texture id the tiles of `layer` are composited with.
32pub fn layer_tile_texture_id(layer: LayerKey) -> AtlasTextureId {
33    debug_assert!(layer.0 < LAYER_KEY_LIMIT);
34    AtlasTextureId {
35        index: LAYER_TILE_TEXTURE_BASE + layer.0,
36        kind: AtlasTextureKind::Polychrome,
37    }
38}
39
40/// The tile id a composited `tile` carries.
41pub fn layer_tile_id(tile: TileCoord) -> TileId {
42    debug_assert!((-TILE_COORD_BIAS..TILE_COORD_BIAS).contains(&tile.x));
43    debug_assert!((-TILE_COORD_BIAS..TILE_COORD_BIAS).contains(&tile.y));
44    let x = (tile.x + TILE_COORD_BIAS) as u32;
45    let y = (tile.y + TILE_COORD_BIAS) as u32;
46    TileId((x << 16) | y)
47}
48
49/// The layer and tile a composited sprite stands for, if it is one.
50pub fn decode_layer_tile(texture: AtlasTextureId, tile: TileId) -> Option<(LayerKey, TileCoord)> {
51    if texture.kind != AtlasTextureKind::Polychrome
52        || texture.index < LAYER_TILE_TEXTURE_BASE
53        || texture.index - LAYER_TILE_TEXTURE_BASE >= LAYER_KEY_LIMIT
54    {
55        return None;
56    }
57    let layer = LayerKey(texture.index - LAYER_TILE_TEXTURE_BASE);
58    let x = (tile.0 >> 16) as i32 - TILE_COORD_BIAS;
59    let y = (tile.0 & 0xFFFF) as i32 - TILE_COORD_BIAS;
60    Some((layer, TileCoord { x, y }))
61}
62
63/// The scroll layers a frame composites, for the renderer to rasterize their
64/// tiles from.
65#[derive(Default)]
66pub struct SceneLayers {
67    /// One per layer the frame composites.
68    pub frames: Vec<LayerFrame>,
69}
70
71impl SceneLayers {
72    /// Forgets the frame's layers, as [`Scene::clear`] forgets its primitives.
73    pub fn clear(&mut self) {
74        self.frames.clear();
75    }
76}
77
78/// A layer the frame composites: the content its tiles are rasterized from.
79#[derive(Clone)]
80pub struct LayerFrame {
81    /// The layer, stable while it lives.
82    pub key: LayerKey,
83    /// Bumps whenever `content` is replaced.
84    pub generation: u64,
85    /// The opaque colour every tile is cleared with before its content is drawn.
86    pub background: Rgba,
87    /// The side of a tile, in device pixels.
88    pub tile_size: u32,
89    /// The painted content in content space.
90    pub content: LayerContent,
91    /// The tiles whose content changed in this generation.
92    pub dirty_tiles: Vec<TileCoord>,
93}
94
95impl LayerFrame {
96    /// The rectangle `tile` covers in content space.
97    pub fn tile_bounds(&self, tile: TileCoord) -> Bounds<ScaledPixels> {
98        let side = self.tile_size as f32;
99        Bounds {
100            origin: point(
101                ScaledPixels(tile.x as f32 * side),
102                ScaledPixels(tile.y as f32 * side),
103            ),
104            size: size(ScaledPixels(side), ScaledPixels(side)),
105        }
106    }
107
108    /// The primitives of `content` that are visible over `tile`, translated
109    /// into the tile's space (its top-left corner at the origin), in drawing
110    /// order, finished and ready to batch.
111    pub fn tile_scene(&self, tile: TileCoord) -> Scene {
112        let bounds = self.tile_bounds(tile);
113        let delta = point(
114            ScaledPixels(-bounds.origin.x.0),
115            ScaledPixels(-bounds.origin.y.0),
116        );
117        let mut scene = Scene::default();
118        for operation in self.content.operations_over(bounds) {
119            match operation {
120                PaintOperation::Primitive(primitive) => {
121                    if visible_bounds(primitive).intersects(&bounds) {
122                        scene.insert_primitive(translate_primitive(primitive, delta));
123                    }
124                }
125                PaintOperation::StartLayer(layer_bounds) => {
126                    scene.push_layer(translate_bounds(*layer_bounds, delta))
127                }
128                PaintOperation::EndLayer => scene.pop_layer(),
129            }
130        }
131        scene.finish();
132        scene
133    }
134}
135
136/// A layer's content, in content space: one or more parts drawn one after
137/// another. A scrolling `div`'s content is one part, a finished scene; a
138/// virtual list's is one part per row, so that a frame adding or changing
139/// rows hands the renderer the rows it kept as they were, without copying
140/// them.
141#[derive(Clone, Default)]
142pub struct LayerContent {
143    parts: Rc<[LayerPart]>,
144}
145
146/// A part of a layer's content.
147#[derive(Clone)]
148pub(crate) struct LayerPart {
149    /// Where the part's primitives can draw, if known: a tile it misses
150    /// draws nothing of it.
151    pub(crate) bounds: Option<Bounds<ScaledPixels>>,
152    /// The part's paint operations, in drawing order. A row's scene holds
153    /// nothing else.
154    pub(crate) scene: Rc<Scene>,
155}
156
157impl From<Scene> for LayerContent {
158    fn from(scene: Scene) -> Self {
159        Self::from(Rc::new(scene))
160    }
161}
162
163impl From<Rc<Scene>> for LayerContent {
164    fn from(scene: Rc<Scene>) -> Self {
165        LayerContent {
166            parts: Rc::new([LayerPart {
167                bounds: None,
168                scene,
169            }]),
170        }
171    }
172}
173
174impl LayerContent {
175    /// Content made of `parts`, drawn in order.
176    pub(crate) fn from_parts(parts: impl IntoIterator<Item = LayerPart>) -> Self {
177        LayerContent {
178            parts: parts.into_iter().collect(),
179        }
180    }
181
182    /// The content's scene, when it is one part, as a `div`'s is.
183    pub fn scene(&self) -> Option<&Scene> {
184        match &*self.parts {
185            [part] => Some(&part.scene),
186            _ => None,
187        }
188    }
189
190    /// The scenes of the content's parts, in order.
191    #[cfg(test)]
192    pub(crate) fn part_scenes(&self) -> impl Iterator<Item = &Rc<Scene>> {
193        self.parts.iter().map(|part| &part.scene)
194    }
195
196    /// Whether `self` and `other` are the same content, shared.
197    pub fn ptr_eq(&self, other: &Self) -> bool {
198        Rc::ptr_eq(&self.parts, &other.parts)
199    }
200
201    /// Every paint operation of the content, in drawing order.
202    pub(crate) fn operations(&self) -> impl Iterator<Item = &PaintOperation> {
203        self.parts
204            .iter()
205            .flat_map(|part| part.scene.paint_operations.iter())
206    }
207
208    /// The paint operations of the parts that can draw over `bounds`, in
209    /// drawing order. Leaving out a part that draws nothing there changes
210    /// no pixel there: a layer it pushed only raises the draw orders of what
211    /// follows, keeping every overlapping pair in order.
212    pub(crate) fn operations_over(
213        &self,
214        bounds: Bounds<ScaledPixels>,
215    ) -> impl Iterator<Item = &PaintOperation> {
216        self.parts
217            .iter()
218            .filter(move |part| part.bounds.is_none_or(|part| part.intersects(&bounds)))
219            .flat_map(|part| part.scene.paint_operations.iter())
220    }
221}
222
223fn translate_bounds(
224    bounds: Bounds<ScaledPixels>,
225    delta: Point<ScaledPixels>,
226) -> Bounds<ScaledPixels> {
227    Bounds {
228        origin: bounds.origin + delta,
229        size: bounds.size,
230    }
231}
232
233/// The part of window (or content) space `primitive` can draw into: what
234/// the renderer rasterizes for it, clipped to its content mask. A drop
235/// shadow reaches three blur radii past its bounds and an inset one fills
236/// its element's bounds (`vs_shadow`); a mono or subpixel sprite's bounds
237/// are transformed (`to_device_position_transformed`).
238pub(crate) fn visible_bounds(primitive: &Primitive) -> Bounds<ScaledPixels> {
239    drawn_bounds(primitive).intersect(&primitive.content_mask().bounds)
240}
241
242/// The part of window (or content) space `primitive` can draw into, its
243/// content mask aside. See [`visible_bounds`].
244pub(crate) fn drawn_bounds(primitive: &Primitive) -> Bounds<ScaledPixels> {
245    match primitive {
246        Primitive::Shadow(shadow) if shadow.inset != 0 => shadow.element_bounds,
247        Primitive::Shadow(shadow) => {
248            let margin = ScaledPixels(3. * shadow.blur_radius.0.max(0.));
249            Bounds {
250                origin: point(
251                    shadow.bounds.origin.x - margin,
252                    shadow.bounds.origin.y - margin,
253                ),
254                size: size(
255                    shadow.bounds.size.width + margin * 2.,
256                    shadow.bounds.size.height + margin * 2.,
257                ),
258            }
259        }
260        Primitive::MonochromeSprite(sprite) => {
261            transformed_bounds(sprite.bounds, &sprite.transformation)
262        }
263        Primitive::SubpixelSprite(sprite) => {
264            transformed_bounds(sprite.bounds, &sprite.transformation)
265        }
266        primitive => *primitive.bounds(),
267    }
268}
269
270/// The smallest rectangle holding `bounds` transformed by `matrix`.
271fn transformed_bounds(
272    bounds: Bounds<ScaledPixels>,
273    matrix: &TransformationMatrix,
274) -> Bounds<ScaledPixels> {
275    if *matrix == TransformationMatrix::unit() {
276        return bounds;
277    }
278    let apply = |x: f32, y: f32| {
279        let m = &matrix.rotation_scale;
280        (
281            m[0][0] * x + m[0][1] * y + matrix.translation[0],
282            m[1][0] * x + m[1][1] * y + matrix.translation[1],
283        )
284    };
285    let (x0, y0) = (bounds.origin.x.0, bounds.origin.y.0);
286    let (x1, y1) = (x0 + bounds.size.width.0, y0 + bounds.size.height.0);
287    let corners = [apply(x0, y0), apply(x1, y0), apply(x0, y1), apply(x1, y1)];
288    let min_x = corners.iter().map(|c| c.0).fold(f32::INFINITY, f32::min);
289    let max_x = corners
290        .iter()
291        .map(|c| c.0)
292        .fold(f32::NEG_INFINITY, f32::max);
293    let min_y = corners.iter().map(|c| c.1).fold(f32::INFINITY, f32::min);
294    let max_y = corners
295        .iter()
296        .map(|c| c.1)
297        .fold(f32::NEG_INFINITY, f32::max);
298    Bounds {
299        origin: point(ScaledPixels(min_x), ScaledPixels(min_y)),
300        size: size(ScaledPixels(max_x - min_x), ScaledPixels(max_y - min_y)),
301    }
302}
303
304/// `primitive` moved by `delta`: every position it carries, its content mask
305/// included, so it draws the same pixels `delta` away.
306pub(crate) fn translate_primitive(primitive: &Primitive, delta: Point<ScaledPixels>) -> Primitive {
307    let mut primitive = primitive.clone();
308    move_primitive(&mut primitive, delta);
309    primitive
310}
311
312/// Moves `primitive` by `delta`, as [`translate_primitive`] does, in place.
313pub(crate) fn move_primitive(primitive: &mut Primitive, delta: Point<ScaledPixels>) {
314    let mv = |bounds: &mut Bounds<ScaledPixels>| *bounds = translate_bounds(*bounds, delta);
315    match primitive {
316        Primitive::Shadow(shadow) => {
317            mv(&mut shadow.bounds);
318            mv(&mut shadow.element_bounds);
319            mv(&mut shadow.content_mask.bounds);
320        }
321        Primitive::Quad(quad) => {
322            mv(&mut quad.bounds);
323            mv(&mut quad.content_mask.bounds);
324        }
325        Primitive::Path(path) => {
326            mv(&mut path.bounds);
327            mv(&mut path.content_mask.bounds);
328            for vertex in &mut path.vertices {
329                vertex.xy_position = vertex.xy_position + delta;
330                mv(&mut vertex.content_mask.bounds);
331            }
332        }
333        Primitive::Underline(underline) => {
334            mv(&mut underline.bounds);
335            mv(&mut underline.content_mask.bounds);
336        }
337        Primitive::MonochromeSprite(sprite) => {
338            mv(&mut sprite.bounds);
339            mv(&mut sprite.content_mask.bounds);
340            translate_transformation(&mut sprite.transformation, delta);
341        }
342        Primitive::SubpixelSprite(sprite) => {
343            mv(&mut sprite.bounds);
344            mv(&mut sprite.content_mask.bounds);
345            translate_transformation(&mut sprite.transformation, delta);
346        }
347        Primitive::PolychromeSprite(sprite) => {
348            mv(&mut sprite.bounds);
349            mv(&mut sprite.content_mask.bounds);
350        }
351        Primitive::Surface(surface) => {
352            mv(&mut surface.bounds);
353            mv(&mut surface.content_mask.bounds);
354        }
355    }
356}
357
358/// A sprite's transformation applies to window positions (`R·p + t`, see
359/// `to_device_position_transformed` in the shaders), so for the sprite to
360/// move by `delta` with it, `t` becomes `t + (I − R)·delta`. The unit
361/// transformation stays the unit.
362fn translate_transformation(matrix: &mut TransformationMatrix, delta: Point<ScaledPixels>) {
363    let r = matrix.rotation_scale;
364    let (dx, dy) = (delta.x.0, delta.y.0);
365    matrix.translation[0] += dx - (r[0][0] * dx + r[0][1] * dy);
366    matrix.translation[1] += dy - (r[1][0] * dx + r[1][1] * dy);
367}