devpage_design/display/chunk.rs
1//! A chunk: one scene node's own commands, in its own coordinates, under
2//! property-tree nodes, with an R-tree over them; and the builder that makes
3//! them, opening a node's layers as property-tree nodes.
4
5use kurbo::{BezPath, Rect as KRect, Shape, Vec2};
6use rstar::{AABB, RTree, RTreeObject};
7
8use super::Draw;
9
10use super::*;
11
12/// A drawing command and the property state it is drawn under: its clip and
13/// its effect, if any. Its transform is its chunk's.
14pub struct Command {
15 /// What it paints, in its chunk's coordinates.
16 pub draw: Draw,
17 /// The clip node it is drawn inside.
18 pub clip: Id,
19 /// The effect node whose layer it is drawn in; `None` when it is in none.
20 pub effect: Option<Id>,
21 /// Every pixel it can touch, in its chunk's coordinates.
22 pub bounds: KRect,
23}
24
25/// Builds one chunk's commands, turning the layers they are drawn in into
26/// property-tree nodes under the chunk's transform.
27pub struct Builder<'a> {
28 /// The property trees its layers' clip and effect nodes are added to.
29 pub(super) trees: &'a mut Trees,
30 /// The chunk's transform node, which every clip and effect it opens is
31 /// placed by.
32 pub(super) transform: Id,
33 /// The clip and effect a command is drawn under, innermost last; the first
34 /// is the chunk's own and is never popped.
35 pub(super) stack: Vec<(Id, Option<Id>)>,
36 /// The commands drawn so far, in paint order.
37 pub(super) commands: Vec<Command>,
38 /// The property-tree nodes made for layers, to be freed with the chunk.
39 pub(super) made: Made,
40}
41
42/// The property-tree nodes a chunk's own layers made.
43#[derive(Default, Clone)]
44pub struct Made {
45 /// The clip nodes, in the order they were opened.
46 pub clips: Vec<Id>,
47 /// The effect nodes, in the order they were opened.
48 pub effects: Vec<Id>,
49}
50
51impl<'a> Builder<'a> {
52 /// Commands drawn under `transform`, inside `clip` and `effect`.
53 pub fn new(trees: &'a mut Trees, transform: Id, clip: Id, effect: Option<Id>) -> Builder<'a> {
54 Builder {
55 trees,
56 transform,
57 stack: vec![(clip, effect)],
58 commands: Vec::new(),
59 made: Made::default(),
60 }
61 }
62
63 /// A fill or a stroke, covering what its path covers.
64 pub fn draw(&mut self, draw: Draw) {
65 let bounds = match &draw {
66 Draw::Fill(path, _) => path.bounding_box(),
67 Draw::Stroke(path, width, _) => {
68 let half = *width as f64 / 2.0;
69 path.bounding_box().inflate(half, half)
70 }
71 Draw::Glyphs(_, size, _, _, glyphs) => glyph_bounds(*size, glyphs),
72 };
73 let (clip, effect) = *self.stack.last().expect("balanced layers");
74 // Anti-aliasing reaches the pixel an edge passes through.
75 self.commands.push(Command {
76 draw,
77 clip,
78 effect,
79 bounds: bounds.inflate(1.0, 1.0),
80 });
81 }
82
83 /// Opens a clip to `path`, in the chunk's coordinates.
84 pub fn push_clip(&mut self, path: BezPath) {
85 let (clip, effect) = *self.stack.last().expect("balanced layers");
86 let id = self.trees.clips.add(Clip {
87 parent: Some(clip),
88 transform: self.transform,
89 path,
90 });
91 self.made.clips.push(id);
92 self.stack.push((id, effect));
93 }
94
95 /// Opens a layer with `blend`, bounded by `bounds`.
96 pub fn push_layer(&mut self, blend: Blend, bounds: Option<BezPath>) {
97 let (clip, effect) = *self.stack.last().expect("balanced layers");
98 let id = self.trees.effects.add(Effect {
99 parent: effect,
100 clip,
101 transform: self.transform,
102 blend,
103 bounds,
104 });
105 self.made.effects.push(id);
106 self.stack.push((clip, Some(id)));
107 }
108
109 /// Closes the last layer or clip opened.
110 pub fn pop(&mut self) {
111 if self.stack.len() > 1 {
112 self.stack.pop();
113 }
114 }
115
116 /// The commands drawn, in paint order, and the property-tree nodes their
117 /// layers made.
118 pub fn finish(self) -> (Vec<Command>, Made) {
119 (self.commands, self.made)
120 }
121}
122
123/// What a glyph run can touch: its glyphs' origins widened by an em each
124/// way, which holds any glyph's outline — accents, descenders and italic
125/// overhang included — at that size.
126pub(super) fn glyph_bounds(size: f32, glyphs: &[super::Glyph]) -> KRect {
127 let mut r: Option<KRect> = None;
128 for g in glyphs {
129 let p = KRect::new(g.x as f64, g.y as f64, g.x as f64, g.y as f64);
130 r = Some(r.map_or(p, |r| r.union(p)));
131 }
132 let em = size as f64;
133 r.unwrap_or_default().inflate(em, em)
134}
135
136/// A command's entry in its chunk's index.
137pub(super) struct Local {
138 /// The command's place in its chunk's `commands`.
139 pub(super) at: usize,
140 /// The command's bounds, in its chunk's coordinates.
141 pub(super) bounds: KRect,
142}
143
144impl RTreeObject for Local {
145 type Envelope = AABB<[f64; 2]>;
146 fn envelope(&self) -> Self::Envelope {
147 aabb(self.bounds)
148 }
149}
150
151/// `r` as an R-tree envelope.
152pub(super) fn aabb(r: KRect) -> AABB<[f64; 2]> {
153 AABB::from_corners([r.x0, r.y0], [r.x1, r.y1])
154}
155
156/// A node's paint order: the order keys from the root down to it. A node
157/// paints before its children, and children in order.
158pub use crate::tree::Order;
159
160/// What a click on a node does, and where it lands: its box in the design's
161/// coordinates, cut by its clipping frames.
162#[derive(Clone, Debug, PartialEq)]
163pub struct Hit {
164 /// The action the node's `on_click` names.
165 pub action: String,
166 /// Where the click lands, in the design's coordinates.
167 pub area: KRect,
168}
169
170/// One scene node's own commands, in its own coordinates, and their index.
171pub struct Chunk {
172 /// Its node's transform node, which every clip and effect it opens is
173 /// under.
174 pub transform: Id,
175 /// The space its coordinates are in: the design's, or a run child's.
176 pub space: Space,
177 /// Where its coordinates' origin is in its space's.
178 pub origin: Vec2,
179 /// Its node's own commands, in paint order and in its own coordinates.
180 pub commands: Vec<Command>,
181 /// The R-tree over `commands`' bounds.
182 pub(super) index: RTree<Local>,
183 /// What cuts it in its space's coordinates: its clipping frames' boxes,
184 /// those inside its space.
185 pub cut: Option<KRect>,
186 /// What it covers for the drawing's area, in its own coordinates, uncut:
187 /// each shape, line and blur by itself.
188 pub covers: Vec<KRect>,
189 /// What its commands can touch in the design's coordinates, cut —
190 /// `None` when that is nothing.
191 pub bounds: Option<KRect>,
192 /// Its node's interaction, if it has one, in its own coordinates: the
193 /// box `(0, 0, width, height)`.
194 pub action: Option<(String, KRect)>,
195 /// The property-tree nodes its own layers made.
196 pub made: Made,
197}
198
199impl Chunk {
200 /// The chunk of `commands`, placed at `origin` in `space` and cut by
201 /// `cut`.
202 #[allow(clippy::too_many_arguments)]
203 pub fn new(
204 transform: Id,
205 space: Space,
206 origin: Vec2,
207 (commands, made): (Vec<Command>, Made),
208 covers: Vec<KRect>,
209 action: Option<(String, KRect)>,
210 cut: Option<KRect>,
211 ) -> Chunk {
212 let index = RTree::bulk_load(
213 commands
214 .iter()
215 .enumerate()
216 .map(|(at, c)| Local {
217 at,
218 bounds: c.bounds,
219 })
220 .collect(),
221 );
222 let mut chunk = Chunk {
223 transform,
224 space,
225 origin,
226 commands,
227 index,
228 cut,
229 covers,
230 bounds: None,
231 action,
232 made,
233 };
234 chunk.place(origin, cut);
235 chunk
236 }
237
238 /// The chunk with its origin at `origin` and cut by `cut`.
239 pub fn moved(mut self, origin: Vec2, cut: Option<KRect>) -> Chunk {
240 self.place(origin, cut);
241 self
242 }
243
244 /// Moves the chunk's origin to `origin` and its cut to `cut`, and works
245 /// out its `bounds` again.
246 pub(super) fn place(&mut self, origin: Vec2, cut: Option<KRect>) {
247 let local = self
248 .commands
249 .iter()
250 .map(|c| c.bounds)
251 .reduce(|a, b| a.union(b));
252 self.bounds = local.and_then(|r| cut_to(r + origin, cut));
253 self.origin = origin;
254 self.cut = cut;
255 }
256
257 /// What it covers in the design's coordinates for the drawing's area:
258 /// each cover cut by itself, then joined.
259 pub fn cover(&self) -> Option<KRect> {
260 self.covers
261 .iter()
262 .filter_map(|&r| cut_to(r + self.origin, self.cut))
263 .reduce(|a, b| a.union(b))
264 }
265
266 /// Where its entry in the top-level index reaches: what it paints and
267 /// where it can be clicked.
268 pub(super) fn reach(&self) -> Option<KRect> {
269 let hit = self
270 .hit()
271 .map(|h| h.area)
272 .filter(|r| r.width() > 0.0 && r.height() > 0.0);
273 match (self.bounds, hit) {
274 (Some(a), Some(b)) => Some(a.union(b)),
275 (a, b) => a.or(b),
276 }
277 }
278}
279
280/// `r` cut by `cut`, or nothing when nothing is left.
281pub(super) fn cut_to(r: KRect, cut: Option<KRect>) -> Option<KRect> {
282 let r = cut.map_or(r, |c| r.intersect(c));
283 (r.width() > 0.0 && r.height() > 0.0).then_some(r)
284}