ezu-paint 0.8.2

Paint GIS features onto a hokusai surface for ezu
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
//! Paint MVT features onto a raster canvas.
//!
//! Three painting primitives are exposed:
//!
//! - [`paint_polygons`] — `tiny-skia` solid fill + optional outline +
//!   `libblur` gaussian blur. Fast path for large patches.
//! - [`paint_polygons_dabs`] — `hokusai` scatter-dab fill with
//!   world-deterministic jitter (seamless across tile boundaries).
//! - [`paint_lines`] — `hokusai::Brush::stroke_to` along polylines.
//!
//! These are the building blocks for the graph nodes in [`nodes`];
//! the host-side glue (PNG encoding, asset loading) lives in [`host`].
//!
//! All painting happens on a [`Canvas`] that optionally wraps a
//! **padded** buffer (`tile_size + 2 * pad`). Paint operations work in
//! the padded space; cropping happens at the host boundary.

// The node `schema()` methods build large `serde_json::json!` literals; the
// default macro recursion limit is not enough for the biggest of them.
#![recursion_limit = "256"]

pub mod brush;
/// Colour-space stop interpolation (re-exported from `ezu-core` so the
/// paint nodes and the MapLibre converter share one implementation).
pub use ezu_core::color as color_interp;
pub mod dabs;
pub mod render;
pub mod strokes;

pub use brush::BrushDefaults;
pub use dabs::{paint_polygons_dabs, DabFillStyle};
pub use hokusai::color::RgbaF32;
pub use hokusai::Brush;
#[cfg(feature = "parallel")]
pub use strokes::paint_lines_parallel;
pub use strokes::{paint_lines, LineStrokeStyle};

use ezu_features::Polygon;
use tiny_skia::{
    Color, FillRule, LineCap, LineJoin, Paint, PathBuilder, Pixmap, PixmapPaint,
    PremultipliedColorU8, Stroke, StrokeDash, Transform,
};

/// A raster canvas backed by a premultiplied RGBA `Pixmap`.
///
/// The canvas optionally has a padding ring around the tile area; all paint
/// operations work in the padded coordinate space, and [`encode_png`] crops
/// back down to the actual tile.
pub mod host;
pub mod legend;
pub mod nodes;

pub struct Canvas {
    pixmap: Pixmap,
    tile_w: u32,
    tile_h: u32,
    pad: u32,
}

impl Canvas {
    /// Convenience: padded canvas with `pad = 0`.
    /// Returns `None` if `tile_w == 0` or `tile_h == 0`, or if the
    /// pixel buffer would overflow allocation.
    pub fn new(tile_w: u32, tile_h: u32) -> Option<Self> {
        Self::new_padded(tile_w, tile_h, 0)
    }

    /// Create a canvas whose internal buffer is `tile_w + 2*pad` × `tile_h + 2*pad`.
    ///
    /// Returns `None` if the resulting padded dimensions are zero or
    /// would overflow allocation.
    pub fn new_padded(tile_w: u32, tile_h: u32, pad: u32) -> Option<Self> {
        let pw = tile_w.checked_add(2u32.checked_mul(pad)?)?;
        let ph = tile_h.checked_add(2u32.checked_mul(pad)?)?;
        let pixmap = Pixmap::new(pw, ph)?;
        Some(Self {
            pixmap,
            tile_w,
            tile_h,
            pad,
        })
    }

    /// Fill the entire (padded) canvas with a solid color, e.g. paper background.
    pub fn fill(&mut self, color: Color) {
        self.pixmap.fill(color);
    }

    pub fn pixmap(&self) -> &Pixmap {
        &self.pixmap
    }

    pub fn pixmap_mut(&mut self) -> &mut Pixmap {
        &mut self.pixmap
    }

    /// Width of the internal (padded) buffer. Use this when sizing layer
    /// pixmaps, masks, or scatter grids.
    pub fn width(&self) -> u32 {
        self.tile_w + 2 * self.pad
    }

    /// Height of the internal (padded) buffer.
    pub fn height(&self) -> u32 {
        self.tile_h + 2 * self.pad
    }

    pub fn tile_width(&self) -> u32 {
        self.tile_w
    }

    pub fn tile_height(&self) -> u32 {
        self.tile_h
    }

    pub fn pad(&self) -> u32 {
        self.pad
    }

    /// Consume the canvas and return its underlying `Pixmap`. Callers
    /// can then call `Pixmap::take` to recover the raw `Vec<u8>` without
    /// copying — paint nodes use this to hand a freshly-painted buffer
    /// to the graph layer without an intermediate `to_vec`.
    pub fn into_pixmap(self) -> Pixmap {
        self.pixmap
    }
}

/// Style for a watercolor polygon layer.
#[derive(Debug, Clone)]
pub struct WatercolorStyle {
    pub fill: Color,
    /// Optional darker outline color giving the "wet edge" feel.
    pub edge: Option<Color>,
    pub edge_width: f32,
    /// Gaussian blur sigma applied to the layer before compositing.
    pub blur_sigma: f32,
}

impl Default for WatercolorStyle {
    fn default() -> Self {
        Self {
            fill: Color::from_rgba8(150, 180, 210, 180),
            edge: Some(Color::from_rgba8(80, 110, 150, 220)),
            edge_width: 1.5,
            blur_sigma: 1.2,
        }
    }
}

/// Paint a collection of MVT polygons onto a fresh transparent layer, blur it,
/// and composite it over `canvas` (source-over).
///
/// Coordinates are MVT tile-local (`[0, extent]`, y-down). The polygons are
/// scaled to tile size and offset by the canvas's padding.
pub fn paint_polygons(
    canvas: &mut Canvas,
    polygons: &[Polygon],
    extent: u32,
    style: &WatercolorStyle,
) {
    let w = canvas.width();
    let h = canvas.height();

    let sx = canvas.tile_w as f32 / extent as f32;
    let sy = canvas.tile_h as f32 / extent as f32;
    let ox = canvas.pad as f32;
    let oy = canvas.pad as f32;

    let mut fill_paint = Paint::default();
    fill_paint.set_color(style.fill);
    fill_paint.anti_alias = true;

    let mut edge_paint = Paint::default();
    if let Some(edge) = style.edge {
        edge_paint.set_color(edge);
        edge_paint.anti_alias = true;
    }

    let draw = |target: &mut Pixmap| {
        for poly in polygons {
            let Some(path) = build_polygon_path(poly, sx, sy, ox, oy) else {
                continue;
            };
            target.fill_path(
                &path,
                &fill_paint,
                FillRule::EvenOdd,
                Transform::identity(),
                None,
            );
            if style.edge.is_some() {
                let stroke = Stroke {
                    width: style.edge_width,
                    ..Stroke::default()
                };
                target.stroke_path(&path, &edge_paint, &stroke, Transform::identity(), None);
            }
        }
    };

    if style.blur_sigma > 0.0 {
        // Blur needs an isolated layer so it only softens this call's
        // polygons, not what's already on the canvas.
        let mut layer = Pixmap::new(w, h).expect("non-zero layer");
        draw(&mut layer);
        blur_pixmap(&mut layer, style.blur_sigma);
        canvas.pixmap.draw_pixmap(
            0,
            0,
            layer.as_ref(),
            &PixmapPaint::default(),
            Transform::identity(),
            None,
        );
    } else {
        draw(&mut canvas.pixmap);
    }
}

/// Style for a crisp vector stroke (contrast with `paint_lines`, which is a
/// painterly hokusai brush).
#[derive(Debug, Clone)]
pub struct StrokeStyle {
    pub color: Color,
    pub width: f32,
    pub cap: LineCap,
    pub join: LineJoin,
    /// On/off dash lengths in pixels (empty / `None` = solid).
    pub dash: Option<Vec<f32>>,
    /// MapLibre `line-gap-width` in pixels. `0` (the plain case) strokes the
    /// centreline at `width`. A positive gap turns the stroke into a casing:
    /// two parallel strokes of `width` each, their inner edges `gap` apart,
    /// i.e. an annulus of outer width `gap + 2 * width` around a `gap`-wide
    /// hole.
    pub gap: f32,
}

/// Stroke MVT polylines with a crisp, constant-width `tiny-skia` line onto a
/// fresh layer, then composite over `canvas`. Coordinates are MVT tile-local
/// (`[0, extent]`, y-down), scaled to tile size and offset by the pad.
pub fn paint_strokes(
    canvas: &mut Canvas,
    lines: &[Vec<(i32, i32)>],
    extent: u32,
    style: &StrokeStyle,
) {
    if lines.is_empty() || style.width <= 0.0 {
        return;
    }
    let sx = canvas.tile_w as f32 / extent as f32;
    let sy = canvas.tile_h as f32 / extent as f32;
    let ox = canvas.pad as f32;
    let oy = canvas.pad as f32;

    let paths: Vec<tiny_skia::Path> = lines
        .iter()
        .filter(|line| line.len() >= 2)
        .filter_map(|line| {
            let mut pb = PathBuilder::new();
            pb.move_to(line[0].0 as f32 * sx + ox, line[0].1 as f32 * sy + oy);
            for &(x, y) in &line[1..] {
                pb.line_to(x as f32 * sx + ox, y as f32 * sy + oy);
            }
            pb.finish()
        })
        .collect();
    if paths.is_empty() {
        return;
    }

    let mut paint = Paint::default();
    paint.set_color(style.color);
    paint.anti_alias = true;

    let gap = style.gap.max(0.0);
    let mut stroke = Stroke {
        // With a gap the drawn band spans `gap/2 ..= gap/2 + width` from the
        // centreline, so the outer footprint is `gap + 2 * width`.
        width: if gap > 0.0 {
            gap + 2.0 * style.width
        } else {
            style.width
        },
        line_cap: style.cap,
        line_join: style.join,
        ..Stroke::default()
    };
    if let Some(pattern) = &style.dash {
        // tiny-skia needs an even, non-empty pattern with positive total.
        if pattern.len() >= 2 && pattern.iter().sum::<f32>() > 0.0 {
            let mut p = pattern.clone();
            if p.len() % 2 == 1 {
                p.extend_from_within(..); // repeat to make it even
            }
            stroke.dash = StrokeDash::new(p, 0.0);
        }
    }

    if gap <= 0.0 {
        for path in &paths {
            canvas
                .pixmap
                .stroke_path(path, &paint, &stroke, Transform::identity(), None);
        }
        return;
    }

    // Casing: paint the full footprint onto an isolated layer, then knock the
    // `gap`-wide corridor back out of it, so the two flanks share the outer
    // stroke's joins, caps and dash phase exactly as MapLibre's line shader
    // does (it renders one extruded ribbon and discards fragments closer to
    // the centreline than `gap/2`). The knockout is solid even when the
    // casing is dashed: the corridor is empty between dashes anyway.
    //
    // The layer spans only what these paths can ink. A data-driven stroke
    // calls this once per feature group, and a full-canvas layer would
    // charge every one of them for an allocation, a clear and a composite
    // over the whole tile however short the road is.
    let Some((ox_i, oy_i, w, h)) = ink_bounds(
        &paths,
        &stroke,
        canvas.pixmap.width(),
        canvas.pixmap.height(),
    ) else {
        return;
    };
    let Some(mut layer) = Pixmap::new(w, h) else {
        return;
    };
    let to_layer = Transform::from_translate(-(ox_i as f32), -(oy_i as f32));
    for path in &paths {
        layer.stroke_path(path, &paint, &stroke, to_layer, None);
    }
    let mut erase = Paint {
        blend_mode: tiny_skia::BlendMode::DestinationOut,
        anti_alias: true,
        ..Paint::default()
    };
    erase.set_color(Color::BLACK);
    let hole = Stroke {
        width: gap,
        line_cap: style.cap,
        line_join: style.join,
        ..Stroke::default()
    };
    for path in &paths {
        layer.stroke_path(path, &erase, &hole, to_layer, None);
    }
    canvas.pixmap.draw_pixmap(
        ox_i,
        oy_i,
        layer.as_ref(),
        &PixmapPaint::default(),
        Transform::identity(),
        None,
    );
}

/// Pixel rect `(x, y, width, height)` that `paths` stroked with `stroke`
/// can touch, clipped to the canvas. `None` when the stroke falls entirely
/// outside the canvas.
///
/// The outset is deliberately generous: a miter join reaches out to
/// `miter_limit` half-widths from the centreline, and anti-aliasing
/// spills a pixel past that. Overshooting costs a few rows of a scratch
/// buffer, while undershooting would clip ink off a join.
fn ink_bounds(
    paths: &[tiny_skia::Path],
    stroke: &Stroke,
    canvas_w: u32,
    canvas_h: u32,
) -> Option<(i32, i32, u32, u32)> {
    let mut bounds = paths.first()?.bounds();
    for path in &paths[1..] {
        let b = path.bounds();
        bounds = tiny_skia::Rect::from_ltrb(
            bounds.left().min(b.left()),
            bounds.top().min(b.top()),
            bounds.right().max(b.right()),
            bounds.bottom().max(b.bottom()),
        )?;
    }
    let outset = stroke.width * 0.5 * stroke.miter_limit.max(1.0) + 2.0;
    let left = (bounds.left() - outset).floor().max(0.0) as u32;
    let top = (bounds.top() - outset).floor().max(0.0) as u32;
    let right = ((bounds.right() + outset).ceil().max(0.0) as u32).min(canvas_w);
    let bottom = ((bounds.bottom() + outset).ceil().max(0.0) as u32).min(canvas_h);
    if right <= left || bottom <= top {
        return None;
    }
    Some((left as i32, top as i32, right - left, bottom - top))
}

pub(crate) fn build_polygon_path(
    poly: &Polygon,
    sx: f32,
    sy: f32,
    ox: f32,
    oy: f32,
) -> Option<tiny_skia::Path> {
    let mut pb = PathBuilder::new();
    push_ring(&mut pb, &poly.exterior, sx, sy, ox, oy)?;
    for hole in &poly.holes {
        push_ring(&mut pb, hole, sx, sy, ox, oy)?;
    }
    pb.finish()
}

fn push_ring(
    pb: &mut PathBuilder,
    ring: &[(i32, i32)],
    sx: f32,
    sy: f32,
    ox: f32,
    oy: f32,
) -> Option<()> {
    if ring.len() < 3 {
        return None;
    }
    let (x0, y0) = ring[0];
    pb.move_to(x0 as f32 * sx + ox, y0 as f32 * sy + oy);
    for &(x, y) in &ring[1..] {
        pb.line_to(x as f32 * sx + ox, y as f32 * sy + oy);
    }
    pb.close();
    Some(())
}

/// In-place gaussian blur on a tiny-skia `Pixmap` using `libblur`.
fn blur_pixmap(pixmap: &mut Pixmap, sigma: f32) {
    let w = pixmap.width() as usize;
    let h = pixmap.height() as usize;
    let mut rgba: Vec<u8> = Vec::with_capacity(w * h * 4);
    for px in pixmap.pixels() {
        let p = px.demultiply();
        rgba.extend_from_slice(&[p.red(), p.green(), p.blue(), p.alpha()]);
    }

    let src_buf = rgba.clone();
    let src = libblur::BlurImage::borrow(
        &src_buf,
        w as u32,
        h as u32,
        libblur::FastBlurChannels::Channels4,
    );
    let mut dst = libblur::BlurImageMut::borrow(
        &mut rgba,
        w as u32,
        h as u32,
        libblur::FastBlurChannels::Channels4,
    );
    if libblur::gaussian_blur(
        &src,
        &mut dst,
        libblur::GaussianBlurParams::new_from_sigma(sigma as f64),
        libblur::EdgeMode2D::new(libblur::EdgeMode::Clamp),
        libblur::ThreadingPolicy::Single,
        libblur::ConvolutionMode::Exact,
    )
    .is_err()
    {
        return;
    }

    let out = pixmap.pixels_mut();
    for (i, dst) in out.iter_mut().enumerate() {
        let r = rgba[i * 4];
        let g = rgba[i * 4 + 1];
        let b = rgba[i * 4 + 2];
        let a = rgba[i * 4 + 3];
        *dst = PremultipliedColorU8::from_rgba(mul(r, a), mul(g, a), mul(b, a), a).unwrap_or_else(
            || {
                // Fully-transparent black is always a valid premul color;
                // this fallback only fires if `from_rgba` ever rejects
                // its input (it doesn't today).
                PremultipliedColorU8::from_rgba(0, 0, 0, 0)
                    .expect("transparent black is a valid premul color")
            },
        );
    }
}

#[inline]
fn mul(c: u8, a: u8) -> u8 {
    ((c as u16 * a as u16 + 127) / 255) as u8
}

#[derive(Debug, thiserror::Error)]
pub enum PaintError {
    #[error("png encode failed")]
    PngEncode,
    #[error("webp encode failed: {0}")]
    WebpEncode(String),
}