hephaestus 0.1.0

Backend-agnostic 2D scene renderer for data visualization.
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
//! Polyline and polygon ribbons rendered via `SceneBuilder::draw_mesh`.
//!
//! Six renders:
//! - `ribbon_1_gradient_along.png` — single polyline with a 5-stop
//!   colour gradient along its length.
//! - `ribbon_2_variable_width.png` — single polyline with width
//!   varying from 2 pt at the start to 20 pt at the end.
//! - `ribbon_3_full.png` — gradient + variable-width combined.
//! - `ribbon_4_caps_joins.png` — 3×3 grid: rows = cap (butt / square
//!   / round), columns = join (miter / bevel / round).
//! - `ribbon_5_closed_rainbow.png` — regular dodecagon with a hue
//!   cycle around the loop; the wrap segment closes the gradient
//!   seamlessly (no visible discontinuity at the close).
//! - `ribbon_6_closed_full.png` — five-lobed polar curve drawn as a
//!   closed ribbon with both a hue-cycle gradient and a pulsing
//!   variable width.

use hephaestus::backend::vello::VelloRenderer;
use hephaestus::color::{rgb8, Color};
use hephaestus::geometry::Affine;
use hephaestus::mesh::Mesh;
use hephaestus::pick::PickId;
use hephaestus::primitives::{
    polygon_gradient, polygon_ribbon_full, polyline_gradient, polyline_ribbon,
    polyline_ribbon_full, RibbonOptions,
};
use hephaestus::scene::SceneBuilder;
use hephaestus::stroke::{Cap, Join};
use hephaestus::{Point, Renderer};

fn main() {
    let dpi = 96.0;
    let bg: Color = rgb8(248, 248, 252);
    let mut renderer = VelloRenderer::new().expect("vello renderer init");

    // ── Render 1: colour gradient along the line ───────────────────
    {
        let (w, h) = (1200u32, 300u32);
        let n = 80;
        let xs: Vec<f64> = (0..n)
            .map(|i| 80.0 + i as f64 / (n - 1) as f64 * 1040.0)
            .collect();
        let ys: Vec<f64> = xs
            .iter()
            .enumerate()
            .map(|(i, _)| 150.0 + 60.0 * (i as f64 * 0.18).sin())
            .collect();
        let points: Vec<Point> = xs
            .iter()
            .zip(ys.iter())
            .map(|(x, y)| Point::new(*x, *y))
            .collect();
        // 5-stop gradient: cool blues to warm reds.
        let stops = [
            rgb8(60, 80, 200),
            rgb8(80, 160, 200),
            rgb8(220, 220, 220),
            rgb8(220, 130, 80),
            rgb8(200, 50, 60),
        ];
        let colors: Vec<Color> = (0..n)
            .map(|i| interpolate_stops(&stops, i as f64 / (n - 1) as f64))
            .collect();
        let opts = RibbonOptions {
            half_width: pt_to_px(12.0, dpi) * 0.5,
            cap: Cap::Round,
            join: Join::Round,
            miter_limit: 4.0,
        };
        let mesh = polyline_gradient(&points, &colors, &opts);
        render_mesh(
            &mut renderer,
            &mesh,
            w,
            h,
            dpi,
            bg,
            "examples/ribbon_1_gradient_along.png",
        );
    }

    // ── Render 2: variable width along the line ────────────────────
    {
        let (w, h) = (1200u32, 300u32);
        let n = 80;
        let xs: Vec<f64> = (0..n)
            .map(|i| 80.0 + i as f64 / (n - 1) as f64 * 1040.0)
            .collect();
        let ys: Vec<f64> = (0..n)
            .map(|i| 150.0 + 60.0 * (i as f64 * 0.18).sin())
            .collect();
        let points: Vec<Point> = xs
            .iter()
            .zip(ys.iter())
            .map(|(x, y)| Point::new(*x, *y))
            .collect();
        // Width ramps from 2pt to 20pt linearly.
        let half_widths: Vec<f64> = (0..n)
            .map(|i| {
                let t = i as f64 / (n - 1) as f64;
                pt_to_px(2.0 + (20.0 - 2.0) * t, dpi) * 0.5
            })
            .collect();
        let opts = RibbonOptions {
            half_width: 1.0,
            cap: Cap::Round,
            join: Join::Round,
            miter_limit: 4.0,
        };
        // `polyline_ribbon_full` with no colours uses black; pass a
        // same-colour slice for the desired stroke colour.
        let stroke = rgb8(40, 90, 180);
        let colors = vec![stroke; n];
        let mesh = polyline_ribbon_full(&points, Some(&colors), Some(&half_widths), &opts);
        render_mesh(
            &mut renderer,
            &mesh,
            w,
            h,
            dpi,
            bg,
            "examples/ribbon_2_variable_width.png",
        );
    }

    // ── Render 3: gradient + variable width on a self-intersecting
    // figure-8 (Lissajous 1:2). The polyline crosses itself once at
    // the centre — each crossing arm renders at a different width
    // and colour, and SrcOver compositing layers them in source order
    // (later vertices draw on top of earlier ones).
    {
        let (w, h) = (1200u32, 400u32);
        let n = 240;
        let cx = 600.0;
        let cy = 200.0;
        let amp_x = 500.0;
        let amp_y = 120.0;
        let xs: Vec<f64> = (0..n)
            .map(|i| {
                let t = i as f64 / (n - 1) as f64 * std::f64::consts::TAU;
                cx + amp_x * t.sin()
            })
            .collect();
        let ys: Vec<f64> = (0..n)
            .map(|i| {
                let t = i as f64 / (n - 1) as f64 * std::f64::consts::TAU;
                cy + amp_y * (2.0 * t).sin()
            })
            .collect();
        let points: Vec<Point> = xs
            .iter()
            .zip(ys.iter())
            .map(|(x, y)| Point::new(*x, *y))
            .collect();
        let stops = [
            rgb8(60, 80, 200),
            rgb8(80, 160, 200),
            rgb8(220, 220, 220),
            rgb8(220, 130, 80),
            rgb8(200, 50, 60),
        ];
        let colors: Vec<Color> = (0..n)
            .map(|i| interpolate_stops(&stops, i as f64 / (n - 1) as f64))
            .collect();
        let half_widths: Vec<f64> = (0..n)
            .map(|i| {
                let t = i as f64 / (n - 1) as f64;
                pt_to_px(2.0 + (24.0 - 2.0) * t, dpi) * 0.5
            })
            .collect();
        let opts = RibbonOptions {
            half_width: 1.0,
            cap: Cap::Round,
            join: Join::Round,
            miter_limit: 4.0,
        };
        let mesh = polyline_ribbon_full(&points, Some(&colors), Some(&half_widths), &opts);
        render_mesh(
            &mut renderer,
            &mesh,
            w,
            h,
            dpi,
            bg,
            "examples/ribbon_3_full.png",
        );
    }

    // ── Render 4: 3×3 cap/join grid ────────────────────────────────
    {
        let (w, h) = (900u32, 700u32);
        let caps = [
            ("butt", Cap::Butt),
            ("square", Cap::Square),
            ("round", Cap::Round),
        ];
        let joins = [
            ("miter", Join::Miter),
            ("bevel", Join::Bevel),
            ("round", Join::Round),
        ];
        // Build 9 ribbons in one mesh (or one render): for each
        // (row, col), zigzag polyline showing the cap and join.
        let mut all_meshes: Vec<Mesh> = Vec::new();
        let cell_w = w as f64 / 3.0;
        let cell_h = h as f64 / 3.0;
        for (r_idx, (_cap_name, cap)) in caps.iter().enumerate() {
            for (c_idx, (_join_name, join)) in joins.iter().enumerate() {
                let cx = c_idx as f64 * cell_w;
                let cy = r_idx as f64 * cell_h;
                // Zigzag polyline filling the cell.
                let pad = 30.0;
                let pts = vec![
                    Point::new(cx + pad, cy + cell_h - pad),
                    Point::new(cx + cell_w * 0.5, cy + pad),
                    Point::new(cx + cell_w - pad, cy + cell_h - pad),
                ];
                let opts = RibbonOptions {
                    half_width: pt_to_px(18.0, dpi) * 0.5,
                    cap: *cap,
                    join: *join,
                    miter_limit: 4.0,
                };
                let stroke = rgb8(40, 90, 180);
                all_meshes.push(polyline_ribbon(&pts, stroke, &opts));
            }
        }
        render_meshes(
            &mut renderer,
            &all_meshes,
            w,
            h,
            dpi,
            bg,
            "examples/ribbon_4_caps_joins.png",
        );
    }

    // ── Render 5: closed-loop rainbow ──────────────────────────────
    // Regular dodecagon vertices, one full hue cycle around the
    // loop. The wrap segment interpolates colors[n-1] → colors[0]
    // (≈ magenta → red, a short hop on the colour wheel), which
    // should be visually indistinguishable from the other segment
    // transitions — i.e. no seam at the close.
    {
        let (w, h) = (700u32, 700u32);
        let cx = 350.0;
        let cy = 350.0;
        let radius = 260.0;
        let n = 12;
        let points: Vec<Point> = (0..n)
            .map(|i| {
                let theta = i as f64 / n as f64 * std::f64::consts::TAU;
                Point::new(cx + radius * theta.cos(), cy + radius * theta.sin())
            })
            .collect();
        let colors: Vec<Color> = (0..n)
            .map(|i| hsv_to_color(i as f64 / n as f64, 0.85, 0.95))
            .collect();
        let opts = RibbonOptions {
            half_width: pt_to_px(28.0, dpi) * 0.5,
            cap: Cap::Butt,
            join: Join::Round,
            miter_limit: 4.0,
        };
        let mesh = polygon_gradient(&points, &colors, &opts);
        render_mesh(
            &mut renderer,
            &mesh,
            w,
            h,
            dpi,
            bg,
            "examples/ribbon_5_closed_rainbow.png",
        );
    }

    // ── Render 6: closed loop with gradient + variable width ───────
    // Five-lobed polar curve r(θ) = R + a·sin(5θ) sampled at 240
    // points. Colours cycle the full hue wheel once; widths pulse
    // at twice the lobe frequency so the ribbon visibly fattens and
    // narrows around the loop. Both pieces close seamlessly because
    // `polygon_*` treats the n samples as one continuous ring.
    {
        let (w, h) = (900u32, 900u32);
        let cx = 450.0;
        let cy = 450.0;
        let base_r = 280.0;
        let amp_r = 70.0;
        let lobes = 5.0;
        let n = 240;
        let points: Vec<Point> = (0..n)
            .map(|i| {
                let theta = i as f64 / n as f64 * std::f64::consts::TAU;
                let r = base_r + amp_r * (lobes * theta).sin();
                Point::new(cx + r * theta.cos(), cy + r * theta.sin())
            })
            .collect();
        let colors: Vec<Color> = (0..n)
            .map(|i| hsv_to_color(i as f64 / n as f64, 0.85, 0.95))
            .collect();
        let half_widths: Vec<f64> = (0..n)
            .map(|i| {
                let theta = i as f64 / n as f64 * std::f64::consts::TAU;
                // Width pulses between ~4 pt and ~22 pt.
                let pt = 13.0 + 9.0 * (2.0 * lobes * theta).sin();
                pt_to_px(pt, dpi) * 0.5
            })
            .collect();
        let opts = RibbonOptions {
            half_width: 1.0,
            cap: Cap::Butt, // ignored by polygon_*
            join: Join::Round,
            miter_limit: 4.0,
        };
        let mesh = polygon_ribbon_full(&points, Some(&colors), Some(&half_widths), &opts);
        render_mesh(
            &mut renderer,
            &mesh,
            w,
            h,
            dpi,
            bg,
            "examples/ribbon_6_closed_full.png",
        );
    }
}

/// HSV → linear RGB Color. Hue is in [0, 1); saturation and value
/// are in [0, 1]. Hue wraps so callers can iterate `i / n` over a
/// closed loop without special-casing the seam.
fn hsv_to_color(h: f64, s: f64, v: f64) -> Color {
    let h6 = (h.rem_euclid(1.0)) * 6.0;
    let c = v * s;
    let x = c * (1.0 - ((h6 % 2.0) - 1.0).abs());
    let m = v - c;
    let (r, g, b) = match h6 as u32 {
        0 => (c, x, 0.0),
        1 => (x, c, 0.0),
        2 => (0.0, c, x),
        3 => (0.0, x, c),
        4 => (x, 0.0, c),
        _ => (c, 0.0, x),
    };
    Color::new([(r + m) as f32, (g + m) as f32, (b + m) as f32, 1.0])
}

fn pt_to_px(pt: f64, dpi: f64) -> f64 {
    pt * dpi / 72.0
}

fn interpolate_stops(stops: &[Color], t: f64) -> Color {
    if stops.is_empty() {
        return Color::new([0.0, 0.0, 0.0, 1.0]);
    }
    if stops.len() == 1 {
        return stops[0];
    }
    let scaled = t.clamp(0.0, 1.0) * (stops.len() - 1) as f64;
    let lo = scaled.floor() as usize;
    let hi = (lo + 1).min(stops.len() - 1);
    let frac = (scaled - lo as f64) as f32;
    let a = stops[lo].components;
    let b = stops[hi].components;
    Color::new([
        a[0] * (1.0 - frac) + b[0] * frac,
        a[1] * (1.0 - frac) + b[1] * frac,
        a[2] * (1.0 - frac) + b[2] * frac,
        a[3] * (1.0 - frac) + b[3] * frac,
    ])
}

fn render_mesh(
    renderer: &mut VelloRenderer,
    mesh: &Mesh,
    w: u32,
    h: u32,
    dpi: f64,
    bg: Color,
    out: &str,
) {
    let _ = dpi;
    {
        let scene = renderer.scene();
        scene.clear();
        scene.draw_mesh(mesh, Affine::IDENTITY, PickId::Skip);
    }
    let mut pixels = vec![0u8; (w * h * 4) as usize];
    renderer
        .render_to_buffer(w, h, bg, &mut pixels)
        .expect("render");
    let path = std::env::current_dir().unwrap().join(out);
    hephaestus::png::write_png(&path, w, h, &pixels).expect("write png");
    println!("wrote {}", path.display());
}

fn render_meshes(
    renderer: &mut VelloRenderer,
    meshes: &[Mesh],
    w: u32,
    h: u32,
    dpi: f64,
    bg: Color,
    out: &str,
) {
    let _ = dpi;
    {
        let scene = renderer.scene();
        scene.clear();
        for m in meshes {
            scene.draw_mesh(m, Affine::IDENTITY, PickId::Skip);
        }
    }
    let mut pixels = vec![0u8; (w * h * 4) as usize];
    renderer
        .render_to_buffer(w, h, bg, &mut pixels)
        .expect("render");
    let path = std::env::current_dir().unwrap().join(out);
    hephaestus::png::write_png(&path, w, h, &pixels).expect("write png");
    println!("wrote {}", path.display());
}