Skip to main content

basemapper_core/vector/
gl.rs

1//! A software model of the parts of MapLibre GL JS's WebGL pipeline used to
2//! draw fills, lines and circles, so CPU renders match it pixel-for-pixel.
3//!
4//! - Primitives are sampled at pixel centres with the top-left rule, like a
5//!   GPU rasteriser; there is no other antialiasing.
6//! - The framebuffer is 8-bit premultiplied RGBA; every fragment is blended
7//!   with `src + dst * (1 - src.a)` and rounded to 8 bits, like WebGL.
8//! - Line geometry is a port of `LineBucket.addLine` and the line / line-SDF
9//!   shaders; fill outlines model `gl.LINES` with the `fill_outline` shader;
10//!   dashes use a port of `LineAtlas`.
11//!
12//! References are to maplibre-gl-js `src/data/bucket/line_bucket.ts`,
13//! `src/render/line_atlas.ts`, `src/render/draw_fill.ts` and `src/shaders/*`.
14
15/// MapLibre loads all tile geometry into an 8192-unit extent.
16pub const EXTENT: f64 = 8192.0;
17
18// ── Framebuffer ──────────────────────────────────────────────────────────────
19
20pub struct Framebuffer {
21    pub w: usize,
22    pub h: usize,
23    /// Premultiplied RGBA8.
24    pub px: Vec<[u8; 4]>,
25}
26
27/// Float → unorm8 as GPUs do it: float32 multiply, round half to even
28/// (SIMD conversion). 0.3 * 255 is exactly 76.5 in float32 and stores as 76.
29#[inline]
30fn to_unorm8(v: f32) -> u8 {
31    (v.clamp(0.0, 1.0) * 255.0f32).round_ties_even() as u8
32}
33
34impl Framebuffer {
35    pub fn new(w: usize, h: usize) -> Self {
36        Framebuffer { w, h, px: vec![[0; 4]; w * h] }
37    }
38
39    /// Blend a premultiplied fragment (ONE, ONE_MINUS_SRC_ALPHA).
40    #[inline]
41    pub fn blend(&mut self, x: usize, y: usize, c: [f32; 4]) {
42        let d = &mut self.px[y * self.w + x];
43        let ia = 1.0 - c[3];
44        for i in 0..4 {
45            d[i] = to_unorm8(c[i] + d[i] as f32 / 255.0 * ia);
46        }
47    }
48
49    /// Straight-alpha RGBA8, as a canvas readback (`toDataURL`) returns it.
50    pub fn into_straight_rgba(self) -> Vec<u8> {
51        let mut out = Vec::with_capacity(self.w * self.h * 4);
52        for p in self.px {
53            let a = p[3] as u32;
54            if a == 0 {
55                out.extend_from_slice(&[0, 0, 0, 0]);
56            } else {
57                for c in &p[..3] {
58                    out.push(((*c as u32 * 255 + a / 2) / a).min(255) as u8);
59                }
60                out.push(p[3]);
61            }
62        }
63        out
64    }
65}
66
67/// Per-tile stencil clip: a pixel belongs to the tile if its centre is in
68/// `[x0, x1) × [y0, y1)` (top-left rule on the tile quad).
69#[derive(Clone, Copy, Debug)]
70pub struct Clip {
71    pub x0: f64,
72    pub y0: f64,
73    pub x1: f64,
74    pub y1: f64,
75}
76
77impl Clip {
78    /// Integer pixel range whose centres fall inside the clip and canvas.
79    fn px_range(&self, w: usize, h: usize) -> (i64, i64, i64, i64) {
80        let cx0 = ((self.x0 - 0.5).ceil() as i64).max(0);
81        let cy0 = ((self.y0 - 0.5).ceil() as i64).max(0);
82        let cx1 = ((self.x1 - 0.5).ceil() as i64).min(w as i64);
83        let cy1 = ((self.y1 - 0.5).ceil() as i64).min(h as i64);
84        (cx0, cy0, cx1, cy1)
85    }
86}
87
88// ── Triangle rasterisation ───────────────────────────────────────────────────
89
90#[derive(Clone, Copy)]
91pub struct Vert<const N: usize> {
92    pub x: f64,
93    pub y: f64,
94    pub v: [f64; N],
95}
96
97/// Sub-pixel precision of vertex positions: the rasterizer snaps them to a
98/// 1/16 px grid. The golden references come from MapLibre on SwiftShader
99/// (ANGLE, `SUBPIXEL_BITS` 4), which covers pixels from snapped positions
100/// while varyings keep the exact values.
101const SUBPIXEL: f64 = 16.0;
102
103#[inline]
104fn snap(v: f64) -> f64 {
105    (v * SUBPIXEL).round() / SUBPIXEL
106}
107
108#[inline]
109fn edge(ax: f64, ay: f64, bx: f64, by: f64, px: f64, py: f64) -> f64 {
110    (bx - ax) * (py - ay) - (by - ay) * (px - ax)
111}
112
113/// Top-left rule for an edge a→b of a triangle with positive `edge()` area
114/// (y down): top edges are horizontal going +x, left edges go up (-y).
115#[inline]
116fn is_top_left(ax: f64, ay: f64, bx: f64, by: f64) -> bool {
117    let (dx, dy) = (bx - ax, by - ay);
118    (dy == 0.0 && dx > 0.0) || dy < 0.0
119}
120
121/// Rasterise a triangle, calling `frag(x, y, varyings)` for each covered pixel
122/// centre inside `clip`. Varyings are interpolated linearly (no perspective).
123pub fn raster_triangle<const N: usize>(
124    w: usize,
125    h: usize,
126    tri: [Vert<N>; 3],
127    clip: &Clip,
128    mut frag: impl FnMut(usize, usize, &[f64; N]),
129) {
130    let [mut a, mut b, mut c] = tri;
131    for v in [&mut a, &mut b, &mut c] {
132        v.x = snap(v.x);
133        v.y = snap(v.y);
134    }
135    let mut area = edge(a.x, a.y, b.x, b.y, c.x, c.y);
136    if area == 0.0 || !area.is_finite() {
137        return;
138    }
139    if area < 0.0 {
140        std::mem::swap(&mut a, &mut b);
141        area = -area;
142    }
143    let (cx0, cy0, cx1, cy1) = clip.px_range(w, h);
144    let minx = (a.x.min(b.x).min(c.x) - 0.5).ceil().max(cx0 as f64) as i64;
145    let maxx = (a.x.max(b.x).max(c.x) - 0.5).floor().min(cx1 as f64 - 1.0) as i64;
146    let miny = (a.y.min(b.y).min(c.y) - 0.5).ceil().max(cy0 as f64) as i64;
147    let maxy = (a.y.max(b.y).max(c.y) - 0.5).floor().min(cy1 as f64 - 1.0) as i64;
148    if minx > maxx || miny > maxy {
149        return;
150    }
151    let tl = [
152        is_top_left(b.x, b.y, c.x, c.y),
153        is_top_left(c.x, c.y, a.x, a.y),
154        is_top_left(a.x, a.y, b.x, b.y),
155    ];
156    let inv = 1.0 / area;
157    let mut out = [0.0f64; N];
158    for py in miny..=maxy {
159        let yc = py as f64 + 0.5;
160        for px in minx..=maxx {
161            let xc = px as f64 + 0.5;
162            let w0 = edge(b.x, b.y, c.x, c.y, xc, yc);
163            let w1 = edge(c.x, c.y, a.x, a.y, xc, yc);
164            let w2 = edge(a.x, a.y, b.x, b.y, xc, yc);
165            let inside = (w0 > 0.0 || (w0 == 0.0 && tl[0]))
166                && (w1 > 0.0 || (w1 == 0.0 && tl[1]))
167                && (w2 > 0.0 || (w2 == 0.0 && tl[2]));
168            if !inside {
169                continue;
170            }
171            let (l0, l1, l2) = (w0 * inv, w1 * inv, w2 * inv);
172            for i in 0..N {
173                out[i] = a.v[i] * l0 + b.v[i] * l1 + c.v[i] * l2;
174            }
175            frag(px as usize, py as usize, &out);
176        }
177    }
178}
179
180// ── Fill interiors ───────────────────────────────────────────────────────────
181
182/// Pixel-centre coverage of one polygon (exterior + holes, even-odd), the
183/// same pixels earcut triangles cover under the top-left rule.
184pub fn raster_polygon(
185    w: usize,
186    h: usize,
187    rings: &[Vec<(f64, f64)>],
188    clip: &Clip,
189    mut frag: impl FnMut(usize, usize),
190) {
191    let mut edges: Vec<(f64, f64, f64, f64)> = Vec::new();
192    let (mut ymin, mut ymax) = (f64::INFINITY, f64::NEG_INFINITY);
193    for ring in rings {
194        let n = ring.len();
195        if n < 3 {
196            continue;
197        }
198        for i in 0..n {
199            let (p, q) = (ring[i], ring[(i + 1) % n]);
200            let (p, q) = ((snap(p.0), snap(p.1)), (snap(q.0), snap(q.1)));
201            if p.1 != q.1 {
202                edges.push((p.0, p.1, q.0, q.1));
203            }
204            ymin = ymin.min(p.1);
205            ymax = ymax.max(p.1);
206        }
207    }
208    if edges.is_empty() {
209        return;
210    }
211    let (cx0, cy0, cx1, cy1) = clip.px_range(w, h);
212    let row0 = ((ymin - 0.5).ceil() as i64).max(cy0);
213    let row1 = ((ymax - 0.5).ceil() as i64).min(cy1);
214    let mut xs: Vec<f64> = Vec::new();
215    for py in row0..row1 {
216        let yc = py as f64 + 0.5;
217        xs.clear();
218        for &(x0, y0, x1, y1) in &edges {
219            let (lo, hi) = if y0 < y1 { (y0, y1) } else { (y1, y0) };
220            if yc >= lo && yc < hi {
221                xs.push(x0 + (yc - y0) * (x1 - x0) / (y1 - y0));
222            }
223        }
224        xs.sort_by(|a, b| a.partial_cmp(b).unwrap());
225        for pair in xs.chunks_exact(2) {
226            let s = ((pair[0] - 0.5).ceil() as i64).max(cx0);
227            let e = ((pair[1] - 0.5).ceil() as i64).min(cx1);
228            for px in s..e {
229                frag(px as usize, py as usize);
230            }
231        }
232    }
233}
234
235// ── 1 px GL lines (fill outlines) ────────────────────────────────────────────
236
237/// Fragments of a 1 px aliased `gl.LINES` segment (diamond-exit style: start
238/// inclusive, end exclusive along the major axis), with the perpendicular
239/// distance from each pixel centre to the line, which is what the
240/// `fill_outline` shader's `length(v_pos - gl_FragCoord.xy)` evaluates to.
241pub fn raster_gl_line(
242    w: usize,
243    h: usize,
244    p0: (f64, f64),
245    p1: (f64, f64),
246    clip: &Clip,
247    mut frag: impl FnMut(usize, usize, f64),
248) {
249    let (dx, dy) = (p1.0 - p0.0, p1.1 - p0.1);
250    let len = (dx * dx + dy * dy).sqrt();
251    if len == 0.0 {
252        return;
253    }
254    let (cx0, cy0, cx1, cy1) = clip.px_range(w, h);
255    let mut emit = |px: i64, py: i64| {
256        if px < cx0 || px >= cx1 || py < cy0 || py >= cy1 {
257            return;
258        }
259        let (xc, yc) = (px as f64 + 0.5, py as f64 + 0.5);
260        let d = ((xc - p0.0) * dy - (yc - p0.1) * dx).abs() / len;
261        frag(px as usize, py as usize, d);
262    };
263    // Note: a strict diamond-exit start rule (emitting the start pixel when
264    // the segment begins past its centre) matched SwiftShader's output worse,
265    // so the column/row-centre walk below is kept as is; it was tuned on
266    // exact endpoints, and snapping them to the sub-pixel grid matches worse.
267    if dx.abs() >= dy.abs() {
268        // x-major: one fragment per column whose centre the segment spans.
269        let (k0, k1) = if dx > 0.0 {
270            ((p0.0 - 0.5).ceil() as i64, (p1.0 - 0.5).ceil() as i64)
271        } else {
272            ((p1.0 - 0.5).floor() as i64 + 1, (p0.0 - 0.5).floor() as i64 + 1)
273        };
274        for k in k0..k1 {
275            let xc = k as f64 + 0.5;
276            let y = p0.1 + (xc - p0.0) * dy / dx;
277            emit(k, y.floor() as i64);
278        }
279    } else {
280        let (k0, k1) = if dy > 0.0 {
281            ((p0.1 - 0.5).ceil() as i64, (p1.1 - 0.5).ceil() as i64)
282        } else {
283            ((p1.1 - 0.5).floor() as i64 + 1, (p0.1 - 0.5).floor() as i64 + 1)
284        };
285        for k in k0..k1 {
286            let yc = k as f64 + 0.5;
287            let x = p0.0 + (yc - p0.1) * dx / dy;
288            emit(x.floor() as i64, k);
289        }
290    }
291}
292
293#[inline]
294pub fn smoothstep(e0: f64, e1: f64, x: f64) -> f64 {
295    let t = ((x - e0) / (e1 - e0)).clamp(0.0, 1.0);
296    t * t * (3.0 - 2.0 * t)
297}
298
299// ── Line tessellation (port of LineBucket.addLine) ───────────────────────────
300
301const EXTRUDE_SCALE: f64 = 63.0;
302const SHARP_CORNER_OFFSET: f64 = 15.0;
303const DEG_PER_TRIANGLE: f64 = 20.0;
304const LINE_DISTANCE_SCALE: f64 = 0.5;
305const MAX_LINE_DISTANCE: f64 = 32768.0; // 2^(15-1) / LINE_DISTANCE_SCALE
306
307/// JavaScript `Math.round` (halves round toward +∞).
308#[inline]
309fn js_round(x: f64) -> f64 {
310    (x + 0.5).floor()
311}
312
313/// JavaScript ToUint8 (modulo 256 after truncation), as typed-array stores do.
314#[inline]
315fn to_uint8(x: f64) -> u8 {
316    (x.trunc() as i64).rem_euclid(256) as u8
317}
318
319#[derive(Clone, Copy, PartialEq, Debug)]
320struct P {
321    x: f64,
322    y: f64,
323}
324
325impl P {
326    fn sub(self, o: P) -> P {
327        P { x: self.x - o.x, y: self.y - o.y }
328    }
329    fn add(self, o: P) -> P {
330        P { x: self.x + o.x, y: self.y + o.y }
331    }
332    fn mult(self, k: f64) -> P {
333        P { x: self.x * k, y: self.y * k }
334    }
335    fn mag(self) -> f64 {
336        (self.x * self.x + self.y * self.y).sqrt()
337    }
338    fn unit(self) -> P {
339        let m = self.mag();
340        P { x: self.x / m, y: self.y / m }
341    }
342    fn perp(self) -> P {
343        P { x: -self.y, y: self.x }
344    }
345    fn round(self) -> P {
346        P { x: js_round(self.x), y: js_round(self.y) }
347    }
348    fn dist(self, o: P) -> f64 {
349        self.sub(o).mag()
350    }
351}
352
353/// One line vertex as the line shaders see it after attribute decoding.
354#[derive(Clone, Copy, Debug)]
355pub struct LineVertex {
356    /// Position in tile units (8192 extent).
357    pub x: f64,
358    pub y: f64,
359    /// Extrusion vector, quantised to 1/63 as stored in `a_data.xy`.
360    pub ex: f64,
361    pub ey: f64,
362    pub round: bool,
363    pub up: bool,
364    /// -1 / 0 / 1 (`a_direction`).
365    pub dir: f64,
366    /// `v_linesofar` in tile units, quantised as the shader decodes it.
367    pub linesofar: f64,
368}
369
370#[derive(Clone, Copy, PartialEq, Eq, Debug)]
371pub enum Join {
372    Miter,
373    Bevel,
374    Round,
375}
376
377#[derive(Clone, Copy, PartialEq, Eq, Debug)]
378pub enum Cap {
379    Butt,
380    Round,
381    Square,
382}
383
384#[derive(Clone, Copy, PartialEq, Eq, Debug)]
385enum CurJoin {
386    Miter,
387    Bevel,
388    FlipBevel,
389    FakeRound,
390    Round,
391    Butt,
392    Square,
393}
394
395pub struct LineBuilder {
396    pub verts: Vec<LineVertex>,
397    pub tris: Vec<[u32; 3]>,
398    distance: f64,
399    e1: i64,
400    e2: i64,
401    overscaling: f64,
402}
403
404impl LineBuilder {
405    pub fn new(overscaling: f64) -> Self {
406        LineBuilder { verts: Vec::new(), tris: Vec::new(), distance: 0.0, e1: -1, e2: -1, overscaling }
407    }
408
409    #[allow(clippy::too_many_arguments)]
410    pub fn add_line(
411        &mut self,
412        vertices: &[(f64, f64)],
413        is_polygon: bool,
414        join: Join,
415        cap: Cap,
416        miter_limit: f64,
417        round_limit: f64,
418    ) {
419        let v: Vec<P> = vertices.iter().map(|&(x, y)| P { x, y }).collect();
420        self.distance = 0.0;
421        let mut len = v.len();
422        while len >= 2 && v[len - 1] == v[len - 2] {
423            len -= 1;
424        }
425        let mut first = 0;
426        while first < len.saturating_sub(1) && v[first] == v[first + 1] {
427            first += 1;
428        }
429        if len < if is_polygon { 3 } else { 2 } {
430            return;
431        }
432        let miter_limit = if join == Join::Bevel { 1.05 } else { miter_limit };
433        let sharp_corner_offset = if self.overscaling <= 16.0 {
434            SHARP_CORNER_OFFSET * EXTENT / (512.0 * self.overscaling)
435        } else {
436            0.0
437        };
438        let cos_half_sharp_corner = (75.0f64 / 2.0).to_radians().cos();
439
440        let mut current: Option<P> = None;
441        let mut prev_vertex: Option<P>;
442        let mut prev_normal: Option<P> = None;
443        let mut next_normal: Option<P> = None;
444        self.e1 = -1;
445        self.e2 = -1;
446
447        if is_polygon {
448            current = Some(v[len - 2]);
449            next_normal = Some(v[first].sub(v[len - 2]).unit().perp());
450        }
451        prev_vertex = None;
452
453        let mut i = first;
454        while i < len {
455            let next_vertex = if i == len - 1 {
456                if is_polygon { Some(v[first + 1]) } else { None }
457            } else {
458                Some(v[i + 1])
459            };
460            if let Some(nv) = next_vertex {
461                if v[i] == nv {
462                    i += 1;
463                    continue;
464                }
465            }
466            if next_normal.is_some() {
467                prev_normal = next_normal;
468            }
469            if current.is_some() {
470                prev_vertex = current;
471            }
472            let mut cur = v[i];
473            current = Some(cur);
474
475            next_normal = match next_vertex {
476                Some(nv) => Some(nv.sub(cur).unit().perp()),
477                None => prev_normal,
478            };
479            let pn = prev_normal.or(next_normal).unwrap();
480            prev_normal = Some(pn);
481            let nn = next_normal.unwrap();
482
483            let mut join_normal = pn.add(nn);
484            if join_normal.x != 0.0 || join_normal.y != 0.0 {
485                join_normal = join_normal.unit();
486            }
487            let cos_angle = pn.x * nn.x + pn.y * nn.y;
488            let cos_half_angle = join_normal.x * nn.x + join_normal.y * nn.y;
489            let miter_length = if cos_half_angle != 0.0 { 1.0 / cos_half_angle } else { f64::INFINITY };
490            let approx_angle = 2.0 * (2.0 - 2.0 * cos_half_angle).sqrt();
491            let is_sharp_corner =
492                cos_half_angle < cos_half_sharp_corner && prev_vertex.is_some() && next_vertex.is_some();
493            let line_turns_left = pn.x * nn.y - pn.y * nn.x > 0.0;
494
495            if is_sharp_corner && i > first {
496                let pv = prev_vertex.unwrap();
497                let prev_seg_len = cur.dist(pv);
498                if prev_seg_len > 2.0 * sharp_corner_offset {
499                    let new_prev = cur.sub(cur.sub(pv).mult(sharp_corner_offset / prev_seg_len).round());
500                    self.distance += pv.dist(new_prev);
501                    self.add_current_vertex(new_prev, pn, 0.0, 0.0, false);
502                    prev_vertex = Some(new_prev);
503                }
504            }
505
506            let middle = prev_vertex.is_some() && next_vertex.is_some();
507            let mut cj = if middle {
508                match join {
509                    Join::Miter => CurJoin::Miter,
510                    Join::Bevel => CurJoin::Bevel,
511                    Join::Round => CurJoin::Round,
512                }
513            } else if is_polygon {
514                CurJoin::Butt
515            } else {
516                match cap {
517                    Cap::Butt => CurJoin::Butt,
518                    Cap::Round => CurJoin::Round,
519                    Cap::Square => CurJoin::Square,
520                }
521            };
522            if middle && cj == CurJoin::Round {
523                if miter_length < round_limit {
524                    cj = CurJoin::Miter;
525                } else if miter_length <= 2.0 {
526                    cj = CurJoin::FakeRound;
527                }
528            }
529            if cj == CurJoin::Miter && miter_length > miter_limit {
530                cj = CurJoin::Bevel;
531            }
532            if cj == CurJoin::Bevel {
533                if miter_length > 2.0 {
534                    cj = CurJoin::FlipBevel;
535                }
536                if miter_length < miter_limit {
537                    cj = CurJoin::Miter;
538                }
539            }
540
541            if let Some(pv) = prev_vertex {
542                self.distance += pv.dist(cur);
543            }
544
545            match cj {
546                CurJoin::Miter => {
547                    let jn = join_normal.mult(miter_length);
548                    self.add_current_vertex(cur, jn, 0.0, 0.0, false);
549                }
550                CurJoin::FlipBevel => {
551                    let jn = if miter_length > 100.0 {
552                        nn.mult(-1.0)
553                    } else {
554                        let bevel_length = miter_length * pn.add(nn).mag() / pn.sub(nn).mag();
555                        join_normal.perp().mult(bevel_length * if line_turns_left { -1.0 } else { 1.0 })
556                    };
557                    self.add_current_vertex(cur, jn, 0.0, 0.0, false);
558                    self.add_current_vertex(cur, jn.mult(-1.0), 0.0, 0.0, false);
559                }
560                CurJoin::Bevel | CurJoin::FakeRound => {
561                    let offset = -(miter_length * miter_length - 1.0).sqrt();
562                    let offset_a = if line_turns_left { offset } else { 0.0 };
563                    let offset_b = if line_turns_left { 0.0 } else { offset };
564                    if prev_vertex.is_some() {
565                        self.add_current_vertex(cur, pn, offset_a, offset_b, false);
566                    }
567                    if cj == CurJoin::FakeRound {
568                        let n = js_round(approx_angle * 180.0 / std::f64::consts::PI / DEG_PER_TRIANGLE) as i64;
569                        for m in 1..n {
570                            let mut t = m as f64 / n as f64;
571                            if t != 0.5 {
572                                let t2 = t - 0.5;
573                                let a = 1.0904 + cos_angle * (-3.2452 + cos_angle * (3.55645 - cos_angle * 1.43519));
574                                let b = 0.848013 + cos_angle * (-1.06021 + cos_angle * 0.215638);
575                                t = t + t * t2 * (t - 1.0) * (a * t2 * t2 + b);
576                            }
577                            let extrude = nn
578                                .sub(pn)
579                                .mult(t)
580                                .add(pn)
581                                .unit()
582                                .mult(if line_turns_left { -1.0 } else { 1.0 });
583                            self.add_half_vertex(cur, extrude.x, extrude.y, false, line_turns_left, 0.0);
584                        }
585                    }
586                    if next_vertex.is_some() {
587                        self.add_current_vertex(cur, nn, -offset_a, -offset_b, false);
588                    }
589                }
590                CurJoin::Butt => self.add_current_vertex(cur, join_normal, 0.0, 0.0, false),
591                CurJoin::Square => {
592                    let o = if prev_vertex.is_some() { 1.0 } else { -1.0 };
593                    self.add_current_vertex(cur, join_normal, o, o, false);
594                }
595                CurJoin::Round => {
596                    if prev_vertex.is_some() {
597                        self.add_current_vertex(cur, pn, 0.0, 0.0, false);
598                        self.add_current_vertex(cur, pn, 1.0, 1.0, true);
599                    }
600                    if next_vertex.is_some() {
601                        self.add_current_vertex(cur, nn, -1.0, -1.0, true);
602                        self.add_current_vertex(cur, nn, 0.0, 0.0, false);
603                    }
604                }
605            }
606
607            if is_sharp_corner && i < len - 1 {
608                let nv = next_vertex.unwrap();
609                let next_seg_len = cur.dist(nv);
610                if next_seg_len > 2.0 * sharp_corner_offset {
611                    let new_cur = cur.add(nv.sub(cur).mult(sharp_corner_offset / next_seg_len).round());
612                    self.distance += cur.dist(new_cur);
613                    self.add_current_vertex(new_cur, nn, 0.0, 0.0, false);
614                    cur = new_cur;
615                    current = Some(cur);
616                }
617            }
618            i += 1;
619        }
620    }
621
622    fn add_current_vertex(&mut self, p: P, normal: P, end_left: f64, end_right: f64, round: bool) {
623        let lx = normal.x + normal.y * end_left;
624        let ly = normal.y - normal.x * end_left;
625        let rx = -normal.x + normal.y * end_right;
626        let ry = -normal.y - normal.x * end_right;
627        self.add_half_vertex(p, lx, ly, round, false, end_left);
628        self.add_half_vertex(p, rx, ry, round, true, -end_right);
629        if self.distance > MAX_LINE_DISTANCE / 2.0 {
630            self.distance = 0.0;
631            self.add_current_vertex(p, normal, end_left, end_right, round);
632        }
633    }
634
635    fn add_half_vertex(&mut self, p: P, ex: f64, ey: f64, round: bool, up: bool, dir: f64) {
636        // Attribute encoding round trip (a_data is 4 x u8).
637        let qx = to_uint8(js_round(EXTRUDE_SCALE * ex) + 128.0) as f64 - 128.0;
638        let qy = to_uint8(js_round(EXTRUDE_SCALE * ey) + 128.0) as f64 - 128.0;
639        let scaled = (self.distance * LINE_DISTANCE_SCALE).trunc() as i64;
640        let z = to_uint8((((if dir == 0.0 { 0 } else if dir < 0.0 { -1 } else { 1 }) + 1) | ((scaled & 0x3F) << 2)) as f64);
641        let wv = to_uint8((scaled >> 6) as f64);
642        let linesofar = ((z as f64 / 4.0).floor() + wv as f64 * 64.0) * 2.0;
643        let a_dir = (z as f64 % 4.0) - 1.0;
644        self.verts.push(LineVertex {
645            x: p.x,
646            y: p.y,
647            ex: qx / EXTRUDE_SCALE,
648            ey: qy / EXTRUDE_SCALE,
649            round,
650            up,
651            dir: a_dir,
652            linesofar,
653        });
654        let e = (self.verts.len() - 1) as i64;
655        if self.e1 >= 0 && self.e2 >= 0 {
656            self.tris.push([self.e1 as u32, self.e2 as u32, e as u32]);
657        }
658        if up {
659            self.e2 = e;
660        } else {
661            self.e1 = e;
662        }
663    }
664}
665
666// ── Dash atlas (port of LineAtlas) ───────────────────────────────────────────
667
668pub const ATLAS_W: usize = 256;
669
670pub struct Dash {
671    /// Rows of signed-distance bytes, `2n + 1` rows of `ATLAS_W`.
672    pub rows: Vec<Vec<u8>>,
673    pub n: usize,
674    /// Sum of the dasharray (`dashEntry.width`).
675    pub width: f64,
676}
677
678struct Range {
679    left: f64,
680    right: f64,
681    is_dash: bool,
682    zero_length: bool,
683}
684
685fn dash_ranges(dasharray: &[f64], stretch: f64) -> Vec<Range> {
686    let odd = dasharray.len() % 2 == 1;
687    let mut ranges = Vec::new();
688    let left = if odd { -dasharray[dasharray.len() - 1] * stretch } else { 0.0 };
689    let right = dasharray[0] * stretch;
690    let mut is_dash = true;
691    ranges.push(Range { left, right, is_dash, zero_length: dasharray[0] == 0.0 });
692    let mut current = dasharray[0];
693    for &d in &dasharray[1..] {
694        is_dash = !is_dash;
695        let left = current * stretch;
696        current += d;
697        let right = current * stretch;
698        ranges.push(Range { left, right, is_dash, zero_length: d == 0.0 });
699    }
700    ranges
701}
702
703impl Dash {
704    pub fn new(dasharray: &[f64], round: bool) -> Dash {
705        let n = if round { 7 } else { 0 };
706        let width: f64 = dasharray.iter().sum();
707        let mut rows = vec![vec![0u8; ATLAS_W]; 2 * n + 1];
708        if width != 0.0 {
709            let stretch = ATLAS_W as f64 / width;
710            let mut ranges = dash_ranges(dasharray, stretch);
711            if round {
712                let half = stretch / 2.0;
713                for (ri, yy) in (-(n as i64)..=n as i64).enumerate() {
714                    let mut ci = 0;
715                    for x in 0..ATLAS_W {
716                        let xf = x as f64;
717                        if xf / ranges[ci].right > 1.0 && ci + 1 < ranges.len() {
718                            ci += 1;
719                        }
720                        let r = &ranges[ci];
721                        let min_dist = (xf - r.left).abs().min((xf - r.right).abs());
722                        let dist_middle = yy as f64 / n as f64 * (half + 1.0);
723                        let sd = if r.is_dash {
724                            let dist_edge = half - dist_middle.abs();
725                            (min_dist * min_dist + dist_edge * dist_edge).sqrt()
726                        } else {
727                            half - (min_dist * min_dist + dist_middle * dist_middle).sqrt()
728                        };
729                        rows[ri][x] = to_uint8((sd + 128.0).clamp(0.0, 255.0));
730                    }
731                }
732            } else {
733                // Collapse zero-length ranges and merge neighbours of the same type.
734                let mut i = ranges.len() as i64 - 1;
735                while i >= 0 {
736                    let iu = i as usize;
737                    if ranges[iu].zero_length {
738                        ranges.remove(iu);
739                    } else if iu + 1 < ranges.len() && ranges[iu + 1].is_dash == ranges[iu].is_dash {
740                        ranges[iu + 1].left = ranges[iu].left;
741                        ranges.remove(iu);
742                    }
743                    i -= 1;
744                }
745                if !ranges.is_empty() {
746                    let last = ranges.len() - 1;
747                    if ranges[0].is_dash == ranges[last].is_dash {
748                        let (fl, lr) = (ranges[last].left, ranges[0].right);
749                        ranges[0].left = fl - ATLAS_W as f64;
750                        ranges[last].right = lr + ATLAS_W as f64;
751                    }
752                    let mut ci = 0;
753                    for x in 0..ATLAS_W {
754                        let xf = x as f64;
755                        if xf / ranges[ci].right > 1.0 && ci + 1 < ranges.len() {
756                            ci += 1;
757                        }
758                        let r = &ranges[ci];
759                        let min_dist = (xf - r.left).abs().min((xf - r.right).abs());
760                        let sd = if r.is_dash { min_dist } else { -min_dist };
761                        rows[0][x] = to_uint8((sd + 128.0).clamp(0.0, 255.0));
762                    }
763                }
764            }
765        }
766        Dash { rows, n, width }
767    }
768
769    /// Bilinear sample (REPEAT in s) at texture s and local row coordinate
770    /// `r` in `[0, 2n]` (row centres at integers). Returns 0..=1.
771    pub fn sample(&self, s: f64, r: f64) -> f64 {
772        let x = s * ATLAS_W as f64 - 0.5;
773        let x0 = x.floor();
774        let fx = x - x0;
775        let i0 = (x0 as i64).rem_euclid(ATLAS_W as i64) as usize;
776        let i1 = (i0 + 1) % ATLAS_W;
777        let row = |ri: usize| {
778            let rr = &self.rows[ri];
779            rr[i0] as f64 * (1.0 - fx) + rr[i1] as f64 * fx
780        };
781        let v = if self.n == 0 {
782            row(0)
783        } else {
784            let r = r.clamp(0.0, (2 * self.n) as f64);
785            let r0 = r.floor() as usize;
786            let r1 = (r0 + 1).min(2 * self.n);
787            let fr = r - r0 as f64;
788            row(r0) * (1.0 - fr) + row(r1) * fr
789        };
790        v / 255.0
791    }
792}
793
794#[cfg(test)]
795mod tests {
796    use super::*;
797
798    #[test]
799    fn top_left_rule_shares_edges_exactly_once() {
800        // Two triangles forming a 4x4 square; every pixel centre hit once.
801        let clip = Clip { x0: -100.0, y0: -100.0, x1: 100.0, y1: 100.0 };
802        let mut hits = vec![0u8; 16];
803        let v = |x, y| Vert::<0> { x, y, v: [] };
804        for tri in [[v(0.0, 0.0), v(4.0, 0.0), v(4.0, 4.0)], [v(0.0, 0.0), v(4.0, 4.0), v(0.0, 4.0)]] {
805            raster_triangle(4, 4, tri, &clip, |x, y, _| hits[y * 4 + x] += 1);
806        }
807        assert!(hits.iter().all(|&h| h == 1), "{hits:?}");
808    }
809
810    #[test]
811    fn polygon_scanline_matches_square() {
812        let clip = Clip { x0: 0.0, y0: 0.0, x1: 8.0, y1: 8.0 };
813        let mut n = 0;
814        let ring = vec![(1.0, 1.0), (5.0, 1.0), (5.0, 5.0), (1.0, 5.0)];
815        raster_polygon(8, 8, &[ring], &clip, |_, _| n += 1);
816        assert_eq!(n, 16);
817    }
818
819    #[test]
820    fn straight_line_builds_quad() {
821        let mut b = LineBuilder::new(1.0);
822        b.add_line(&[(0.0, 0.0), (100.0, 0.0)], false, Join::Miter, Cap::Butt, 2.0, 1.05);
823        assert_eq!(b.verts.len(), 4);
824        assert_eq!(b.tris.len(), 2);
825        // Left extrude of an eastward line is +y (south) in tile space.
826        assert_eq!((b.verts[0].ex, b.verts[0].ey), (0.0, 1.0));
827        assert!(!b.verts[0].up && b.verts[1].up);
828        assert_eq!(b.verts[2].linesofar, 100.0);
829    }
830
831    #[test]
832    fn dash_atlas_regular_pattern() {
833        let d = Dash::new(&[2.0, 2.0], false);
834        assert_eq!(d.width, 4.0);
835        // Middle of the first dash is far inside (> 0.5), middle of gap is outside.
836        assert!(d.sample(0.125, 0.0) > 0.5);
837        assert!(d.sample(0.625, 0.0) < 0.5);
838    }
839}