Skip to main content

vello_encoding/
estimate.rs

1// Copyright 2024 the Vello Authors
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3
4//! This utility provides conservative size estimation for buffer allocations backing
5//! GPU bump memory. This estimate relies on heuristics and naturally overestimates.
6
7use super::{BumpAllocatorMemory, BumpAllocators, Transform};
8use peniko::kurbo::{Cap, Join, PathEl, Point, Stroke, Vec2};
9
10const RSQRT_OF_TOL: f64 = 2.2360679775; // tol = 0.2
11
12#[derive(Clone, Default)]
13pub struct BumpEstimator {
14    // TODO: support binning
15    // TODO: support ptcl
16    // TODO: support tile
17
18    // NOTE: The segment count estimation could use further refinement, particularly to handle
19    // viewport clipping and rotation applied to fragments during append. We can produce a more
20    // optimal result under scale and rotation if we track more data for each shape during insertion
21    // and defer the final tally to resolve-time (in which we could evaluate the estimates using
22    // precisely transformed coordinates). For now we apply a fudge factor of sqrt(2) and inflate
23    // the number of tile crossing (a near~diagonal line orientation would result in worst case for
24    // the number of intersected tiles) to account for this.
25    //
26    // Accounting for viewport clipping (for the right and bottom edges of the viewport) is simply
27    // impossible at insertion time as the render target dimensions are unknown. We could
28    // potentially account for clipping (including clip shapes/layers) by tracking bounding boxes
29    // during insertion and resolving all clips at tally time (e.g. one could come up with a
30    // heuristic for scaling the counts based on the proportions of a clipped bbox area).
31    //
32    // Since we currently don't account for clipping, this will always overshoot when clips are
33    // present and when the bounding box of a shape is partially or wholly outside the viewport.
34    segments: u32,
35    lines: LineSoup,
36}
37
38impl BumpEstimator {
39    pub fn new() -> Self {
40        Self::default()
41    }
42
43    pub fn reset(&mut self) {
44        *self = Self::default();
45    }
46
47    /// Combine the counts of this estimator with `other` after applying an optional `transform`.
48    pub fn append(&mut self, other: &Self, transform: Option<&Transform>) {
49        let scale = transform_scale(transform);
50        self.segments += (other.segments as f64 * scale).ceil() as u32;
51        self.lines.add(&other.lines, scale);
52    }
53
54    pub fn count_path(
55        &mut self,
56        path: impl Iterator<Item = PathEl>,
57        t: &Transform,
58        stroke: Option<&Stroke>,
59    ) {
60        let mut caps = 1;
61        let mut joins: u32 = 0;
62        let mut lineto_lines = 0;
63        let mut fill_close_lines = 1;
64        let mut curve_lines = 0;
65        let mut curve_count = 0;
66        let mut segments = 0;
67
68        // Track the path state to correctly count empty paths and close joins.
69        let mut first_pt = None;
70        let mut last_pt = None;
71        let scale = transform_scale(Some(t));
72        let scaled_width = stroke.map(|s| s.width * scale).unwrap_or(0.);
73        let offset_fudge = scaled_width.sqrt().max(1.);
74        for el in path {
75            match el {
76                PathEl::MoveTo(p0) => {
77                    first_pt = Some(p0);
78                    let Some(point) = last_pt else {
79                        continue;
80                    };
81                    caps += 1;
82                    joins = joins.saturating_sub(1);
83                    fill_close_lines += 1;
84                    segments += count_segments_for_line(first_pt.unwrap(), point, t);
85                    last_pt = None;
86                }
87                PathEl::ClosePath => {
88                    if let Some(last_pt) = last_pt {
89                        joins += 1;
90                        lineto_lines += 1;
91                        segments += count_segments_for_line(first_pt.unwrap(), last_pt, t);
92                    }
93                    last_pt = first_pt;
94                }
95                PathEl::LineTo(p0) => {
96                    last_pt = Some(p0);
97                    joins += 1;
98                    lineto_lines += 1;
99                    segments += count_segments_for_line(first_pt.unwrap(), last_pt.unwrap(), t);
100                }
101                PathEl::QuadTo(p1, p2) => {
102                    let Some(p0) = last_pt.or(first_pt) else {
103                        continue;
104                    };
105                    last_pt = Some(p2);
106
107                    let p0 = p0.to_vec2();
108                    let p1 = p1.to_vec2();
109                    let p2 = p2.to_vec2();
110                    let lines = offset_fudge * wang::quadratic(RSQRT_OF_TOL, p0, p1, p2, t);
111
112                    curve_lines += lines.ceil() as u32;
113                    curve_count += 1;
114                    joins += 1;
115
116                    let segs = offset_fudge * count_segments_for_quadratic(p0, p1, p2, t);
117                    segments += segs.ceil().max(lines.ceil()) as u32;
118                }
119                PathEl::CurveTo(p1, p2, p3) => {
120                    let Some(p0) = last_pt.or(first_pt) else {
121                        continue;
122                    };
123                    last_pt = Some(p3);
124
125                    let p0 = p0.to_vec2();
126                    let p1 = p1.to_vec2();
127                    let p2 = p2.to_vec2();
128                    let p3 = p3.to_vec2();
129                    let lines = offset_fudge * wang::cubic(RSQRT_OF_TOL, p0, p1, p2, p3, t);
130
131                    curve_lines += lines.ceil() as u32;
132                    curve_count += 1;
133                    joins += 1;
134                    let segs = count_segments_for_cubic(p0, p1, p2, p3, t);
135                    segments += segs.ceil().max(lines.ceil()) as u32;
136                }
137            }
138        }
139
140        let Some(style) = stroke else {
141            self.lines.linetos += lineto_lines + fill_close_lines;
142            self.lines.curves += curve_lines;
143            self.lines.curve_count += curve_count;
144            self.segments += segments;
145
146            // Account for the implicit close
147            if let (Some(first_pt), Some(last_pt)) = (first_pt, last_pt) {
148                self.segments += count_segments_for_line(first_pt, last_pt, t);
149            }
150            return;
151        };
152
153        // For strokes, double-count the lines to estimate offset curves.
154        self.lines.linetos += 2 * lineto_lines;
155        self.lines.curves += 2 * curve_lines;
156        self.lines.curve_count += 2 * curve_count;
157        self.segments += 2 * segments;
158
159        self.count_stroke_caps(style.start_cap, scaled_width, caps);
160        self.count_stroke_caps(style.end_cap, scaled_width, caps);
161        self.count_stroke_joins(style.join, scaled_width, style.miter_limit, joins);
162    }
163
164    /// Produce the final total, applying an optional transform to all content.
165    pub fn tally(&self, transform: Option<&Transform>) -> BumpAllocatorMemory {
166        let scale = transform_scale(transform);
167
168        // The post-flatten line estimate.
169        let lines = self.lines.tally(scale);
170
171        // The estimate for tile crossings for lines. Here we ensure that there are at least as many
172        // segments as there are lines, in case `segments` was underestimated at small scales.
173        let n_segments = ((self.segments as f64 * scale).ceil() as u32).max(lines);
174
175        let bump = BumpAllocators {
176            failed: 0,
177            // TODO: we can provide a tighter bound here but for now we
178            // assume that binning must be bounded by the segment count.
179            binning: n_segments,
180            ptcl: 0,
181            tile: 0,
182            blend: 0,
183            seg_counts: n_segments,
184            segments: n_segments,
185            lines,
186        };
187        bump.memory()
188    }
189
190    fn count_stroke_caps(&mut self, style: Cap, scaled_width: f64, count: u32) {
191        match style {
192            Cap::Butt => {
193                self.lines.linetos += count;
194                self.segments += count_segments_for_line_length(scaled_width) * count;
195            }
196            Cap::Square => {
197                self.lines.linetos += 3 * count;
198                self.segments += count_segments_for_line_length(scaled_width) * count;
199                self.segments += 2 * count_segments_for_line_length(0.5 * scaled_width) * count;
200            }
201            Cap::Round => {
202                let (arc_lines, line_len) = estimate_arc_lines(scaled_width);
203                self.lines.curves += count * arc_lines;
204                self.lines.curve_count += 1;
205                self.segments += count * arc_lines * count_segments_for_line_length(line_len);
206            }
207        }
208    }
209
210    fn count_stroke_joins(&mut self, style: Join, scaled_width: f64, miter_limit: f64, count: u32) {
211        match style {
212            Join::Bevel => {
213                self.lines.linetos += count;
214                self.segments += count_segments_for_line_length(scaled_width) * count;
215            }
216            Join::Miter => {
217                let max_miter_len = scaled_width * miter_limit;
218                self.lines.linetos += 2 * count;
219                self.segments += 2 * count * count_segments_for_line_length(max_miter_len);
220            }
221            Join::Round => {
222                let (arc_lines, line_len) = estimate_arc_lines(scaled_width);
223                self.lines.curves += count * arc_lines;
224                self.lines.curve_count += 1;
225                self.segments += count * arc_lines * count_segments_for_line_length(line_len);
226            }
227        }
228
229        // Count inner join lines
230        self.lines.linetos += count;
231        self.segments += count_segments_for_line_length(scaled_width) * count;
232    }
233}
234
235fn estimate_arc_lines(scaled_stroke_width: f64) -> (u32, f64) {
236    // These constants need to be kept consistent with the definitions in `flatten_arc` in
237    // flatten.wgsl.
238    // TODO: It would be better if these definitions were shared/configurable. For example an
239    // option is for all tolerances to be parameters to the estimator as well as the GPU pipelines
240    // (the latter could be in the form of a config uniform) which would help to keep them in
241    // sync.
242    const MIN_THETA: f64 = 1e-6;
243    const TOL: f64 = 0.25;
244    let radius = TOL.max(scaled_stroke_width * 0.5);
245    let theta = (2. * (1. - TOL / radius).acos()).max(MIN_THETA);
246    let arc_lines = ((std::f64::consts::FRAC_PI_2 / theta).ceil() as u32).max(2);
247    (arc_lines, 2. * theta.sin() * radius)
248}
249
250#[derive(Clone, Default)]
251struct LineSoup {
252    // Explicit lines (such as linetos and non-round stroke caps/joins) and Bezier curves
253    // get tracked separately to ensure that explicit lines remain scale invariant.
254    linetos: u32,
255    curves: u32,
256
257    // Curve count is simply used to ensure a minimum number of lines get counted for each curve
258    // at very small scales to reduce the chances of an under-estimate.
259    curve_count: u32,
260}
261
262impl LineSoup {
263    fn tally(&self, scale: f64) -> u32 {
264        let curves = self
265            .scaled_curve_line_count(scale)
266            .max(5 * self.curve_count);
267
268        self.linetos + curves
269    }
270
271    fn scaled_curve_line_count(&self, scale: f64) -> u32 {
272        (self.curves as f64 * scale.sqrt()).ceil() as u32
273    }
274
275    fn add(&mut self, other: &Self, scale: f64) {
276        self.linetos += other.linetos;
277        self.curves += other.scaled_curve_line_count(scale);
278        self.curve_count += other.curve_count;
279    }
280}
281
282// TODO: The 32-bit Vec2 definition from cpu_shaders/util.rs could come in handy here.
283fn transform(t: &Transform, v: Vec2) -> Vec2 {
284    Vec2::new(
285        t.matrix[0] as f64 * v.x + t.matrix[2] as f64 * v.y,
286        t.matrix[1] as f64 * v.x + t.matrix[3] as f64 * v.y,
287    )
288}
289
290fn transform_scale(t: Option<&Transform>) -> f64 {
291    match t {
292        Some(t) => {
293            let m = t.matrix;
294            let v1x = m[0] as f64 + m[3] as f64;
295            let v2x = m[0] as f64 - m[3] as f64;
296            let v1y = m[1] as f64 - m[2] as f64;
297            let v2y = m[1] as f64 + m[2] as f64;
298            (v1x * v1x + v1y * v1y).sqrt() + (v2x * v2x + v2y * v2y).sqrt()
299        }
300        None => 1.,
301    }
302}
303
304fn approx_arc_length_cubic(p0: Vec2, p1: Vec2, p2: Vec2, p3: Vec2) -> f64 {
305    let chord_len = (p3 - p0).length();
306    // Length of the control polygon
307    let poly_len = (p1 - p0).length() + (p2 - p1).length() + (p3 - p2).length();
308    0.5 * (chord_len + poly_len)
309}
310
311fn count_segments_for_cubic(p0: Vec2, p1: Vec2, p2: Vec2, p3: Vec2, t: &Transform) -> f64 {
312    let p0 = transform(t, p0);
313    let p1 = transform(t, p1);
314    let p2 = transform(t, p2);
315    let p3 = transform(t, p3);
316    (approx_arc_length_cubic(p0, p1, p2, p3) * 0.0625 * std::f64::consts::SQRT_2).ceil()
317}
318
319fn count_segments_for_quadratic(p0: Vec2, p1: Vec2, p2: Vec2, t: &Transform) -> f64 {
320    count_segments_for_cubic(p0, p1.lerp(p0, 0.333333), p1.lerp(p2, 0.333333), p2, t)
321}
322
323// Estimate tile crossings for a line with known endpoints.
324fn count_segments_for_line(p0: Point, p1: Point, t: &Transform) -> u32 {
325    let dxdy = p0 - p1;
326    let dxdy = transform(t, dxdy);
327    let segments = (dxdy.x.abs().ceil() * 0.0625).ceil() + (dxdy.y.abs().ceil() * 0.0625).ceil();
328    (segments as u32).max(1)
329}
330
331// Estimate tile crossings for a line with a known length.
332fn count_segments_for_line_length(scaled_width: f64) -> u32 {
333    // scale the tile count by sqrt(2) to allow some slack for diagonal lines.
334    // TODO: Would "2" be a better factor?
335    ((scaled_width * 0.0625 * std::f64::consts::SQRT_2).ceil() as u32).max(1)
336}
337
338/// Wang's Formula (as described in Pyramid Algorithms by Ron Goldman, 2003, Chapter 5, Section
339/// 5.6.3 on Bezier Approximation) is a fast method for computing a lower bound on the number of
340/// recursive subdivisions required to approximate a Bezier curve within a certain tolerance. The
341/// formula for a Bezier curve of degree `n`, control points `p[0]...p[n]`, and number of levels of
342/// subdivision `l`, and flattening tolerance `tol` is defined as follows:
343///
344/// ```ignore
345///     m = max([length(p[k+2] - 2 * p[k+1] + p[k]) for (0 <= k <= n-2)])
346///     l >= log_4((n * (n - 1) * m) / (8 * tol))
347/// ```
348///
349/// For recursive subdivisions that split a curve into 2 segments at each level, the minimum number
350/// of segments is given by 2^l. From the formula above it follows that:
351///
352/// ```ignore
353///       segments >= 2^l >= 2^log_4(x)                      (1)
354///     segments^2 >= 2^(2*log_4(x)) >= 4^log_4(x)           (2)
355///     segments^2 >= x
356///       segments >= sqrt((n * (n - 1) * m) / (8 * tol))    (3)
357/// ```
358///
359/// Wang's formula computes an error bound on recursive subdivision based on the second derivative
360/// which tends to result in a suboptimal estimate when the curvature within the curve has a lot of
361/// variation. This is expected to frequently overshoot the flattening formula used in vello, which
362/// is closer to optimal (vello uses a method based on a numerical approximation of the integral
363/// over the continuous change in the number of flattened segments, with an error expressed in terms
364/// of curvature and infinitesimal arclength).
365mod wang {
366    use super::{Transform, Vec2, transform};
367
368    // The curve degree term sqrt(n * (n - 1) / 8) specialized for cubics:
369    //
370    //    sqrt(3 * (3 - 1) / 8)
371    //
372    const SQRT_OF_DEGREE_TERM_CUBIC: f64 = 0.86602540378;
373
374    // The curve degree term sqrt(n * (n - 1) / 8) specialized for quadratics:
375    //
376    //    sqrt(2 * (2 - 1) / 8)
377    //
378    const SQRT_OF_DEGREE_TERM_QUAD: f64 = 0.5;
379
380    pub(crate) fn quadratic(rsqrt_of_tol: f64, p0: Vec2, p1: Vec2, p2: Vec2, t: &Transform) -> f64 {
381        let v = -2. * p1 + p0 + p2;
382        let v = transform(t, v); // transform is distributive
383        let m = v.length();
384        (SQRT_OF_DEGREE_TERM_QUAD * m.sqrt() * rsqrt_of_tol).ceil()
385    }
386
387    pub(crate) fn cubic(
388        rsqrt_of_tol: f64,
389        p0: Vec2,
390        p1: Vec2,
391        p2: Vec2,
392        p3: Vec2,
393        t: &Transform,
394    ) -> f64 {
395        let v1 = -2. * p1 + p0 + p2;
396        let v2 = -2. * p2 + p1 + p3;
397        let v1 = transform(t, v1);
398        let v2 = transform(t, v2);
399        let m = v1.length().max(v2.length());
400        (SQRT_OF_DEGREE_TERM_CUBIC * m.sqrt() * rsqrt_of_tol).ceil()
401    }
402}