Skip to main content

ultrafast_render/
scene3d.rs

1//! 3D scenes: meshes (primitives, glTF), lights and cameras as graph
2//! nodes, rendered by a `render3d` node into an image like any other.
3//!
4//! Coordinates are right-handed with +y up; the default camera sits at
5//! (0, 0, 5) looking at the origin. Units are arbitrary.
6
7use crate::RenderError;
8use crate::ops::text;
9use std::path::Path;
10use ultrafast_graph::{Node, Param};
11
12/// Row-major 4x4 matrix; vectors are columns (`m * v`).
13#[derive(Debug, Clone, Copy, PartialEq)]
14pub struct Mat4(pub [f32; 16]);
15
16impl Mat4 {
17    pub const IDENTITY: Mat4 = Mat4([
18        1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0,
19    ]);
20
21    pub fn mul(&self, o: &Mat4) -> Mat4 {
22        let mut r = [0.0f32; 16];
23        for i in 0..4 {
24            for j in 0..4 {
25                r[i * 4 + j] = (0..4).map(|k| self.0[i * 4 + k] * o.0[k * 4 + j]).sum();
26            }
27        }
28        Mat4(r)
29    }
30
31    pub fn translate(x: f32, y: f32, z: f32) -> Mat4 {
32        let mut m = Self::IDENTITY;
33        m.0[3] = x;
34        m.0[7] = y;
35        m.0[11] = z;
36        m
37    }
38
39    pub fn scale(x: f32, y: f32, z: f32) -> Mat4 {
40        let mut m = Self::IDENTITY;
41        m.0[0] = x;
42        m.0[5] = y;
43        m.0[10] = z;
44        m
45    }
46
47    /// Rotation from Euler angles in degrees, applied X, then Y, then Z.
48    pub fn rotate_xyz(deg: [f32; 3]) -> Mat4 {
49        let [x, y, z] = deg.map(f32::to_radians);
50        let (sx, cx) = x.sin_cos();
51        let (sy, cy) = y.sin_cos();
52        let (sz, cz) = z.sin_cos();
53        let rx = Mat4([
54            1.0, 0.0, 0.0, 0.0, 0.0, cx, -sx, 0.0, 0.0, sx, cx, 0.0, 0.0, 0.0, 0.0, 1.0,
55        ]);
56        let ry = Mat4([
57            cy, 0.0, sy, 0.0, 0.0, 1.0, 0.0, 0.0, -sy, 0.0, cy, 0.0, 0.0, 0.0, 0.0, 1.0,
58        ]);
59        let rz = Mat4([
60            cz, -sz, 0.0, 0.0, sz, cz, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0,
61        ]);
62        rz.mul(&ry).mul(&rx)
63    }
64
65    /// Right-handed perspective projection with depth in [0, 1].
66    pub fn perspective(fov_y_deg: f32, aspect: f32, near: f32, far: f32) -> Mat4 {
67        let f = 1.0 / (fov_y_deg.to_radians() / 2.0).tan();
68        let a = far / (near - far);
69        Mat4([
70            f / aspect,
71            0.0,
72            0.0,
73            0.0,
74            0.0,
75            f,
76            0.0,
77            0.0,
78            0.0,
79            0.0,
80            a,
81            a * near,
82            0.0,
83            0.0,
84            -1.0,
85            0.0,
86        ])
87    }
88
89    pub fn look_at(eye: [f32; 3], target: [f32; 3], up: [f32; 3]) -> Mat4 {
90        let f = normalize(sub(target, eye));
91        let s = normalize(cross(f, up));
92        let u = cross(s, f);
93        Mat4([
94            s[0],
95            s[1],
96            s[2],
97            -dot(s, eye),
98            u[0],
99            u[1],
100            u[2],
101            -dot(u, eye),
102            -f[0],
103            -f[1],
104            -f[2],
105            dot(f, eye),
106            0.0,
107            0.0,
108            0.0,
109            1.0,
110        ])
111    }
112
113    pub fn transpose(&self) -> Mat4 {
114        let mut r = [0.0; 16];
115        for i in 0..4 {
116            for j in 0..4 {
117                r[j * 4 + i] = self.0[i * 4 + j];
118            }
119        }
120        Mat4(r)
121    }
122
123    /// Inverse of an affine matrix (rotation/scale/translation).
124    pub fn inverse_affine(&self) -> Mat4 {
125        let m = &self.0;
126        let (a, b, c, d, e, f, g, h, i) = (m[0], m[1], m[2], m[4], m[5], m[6], m[8], m[9], m[10]);
127        let det = a * (e * i - f * h) - b * (d * i - f * g) + c * (d * h - e * g);
128        if det.abs() < 1e-12 {
129            return Mat4::IDENTITY;
130        }
131        let inv = 1.0 / det;
132        let r = [
133            (e * i - f * h) * inv,
134            (c * h - b * i) * inv,
135            (b * f - c * e) * inv,
136            (f * g - d * i) * inv,
137            (a * i - c * g) * inv,
138            (c * d - a * f) * inv,
139            (d * h - e * g) * inv,
140            (b * g - a * h) * inv,
141            (a * e - b * d) * inv,
142        ];
143        let t = [m[3], m[7], m[11]];
144        let tt = [
145            -(r[0] * t[0] + r[1] * t[1] + r[2] * t[2]),
146            -(r[3] * t[0] + r[4] * t[1] + r[5] * t[2]),
147            -(r[6] * t[0] + r[7] * t[1] + r[8] * t[2]),
148        ];
149        Mat4([
150            r[0], r[1], r[2], tt[0], r[3], r[4], r[5], tt[1], r[6], r[7], r[8], tt[2], 0.0, 0.0, 0.0, 1.0,
151        ])
152    }
153}
154
155fn sub(a: [f32; 3], b: [f32; 3]) -> [f32; 3] {
156    [a[0] - b[0], a[1] - b[1], a[2] - b[2]]
157}
158fn dot(a: [f32; 3], b: [f32; 3]) -> f32 {
159    a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
160}
161fn cross(a: [f32; 3], b: [f32; 3]) -> [f32; 3] {
162    [
163        a[1] * b[2] - a[2] * b[1],
164        a[2] * b[0] - a[0] * b[2],
165        a[0] * b[1] - a[1] * b[0],
166    ]
167}
168fn normalize(a: [f32; 3]) -> [f32; 3] {
169    let l = dot(a, a).sqrt().max(1e-12);
170    [a[0] / l, a[1] / l, a[2] / l]
171}
172
173/// Interleaved vertices (position, normal, uv: 8 floats) and indices.
174#[derive(Debug, Clone, Default)]
175pub struct MeshData {
176    pub vertices: Vec<f32>,
177    pub indices: Vec<u32>,
178}
179
180impl MeshData {
181    fn vertex(&mut self, p: [f32; 3], n: [f32; 3], uv: [f32; 2]) -> u32 {
182        self.vertices.extend([p[0], p[1], p[2], n[0], n[1], n[2], uv[0], uv[1]]);
183        (self.vertices.len() / 8 - 1) as u32
184    }
185
186    /// A grid of vertices from `f(u, v) -> (position, normal)` over
187    /// [0,1]^2 with `nu` x `nv` cells.
188    fn grid(&mut self, nu: usize, nv: usize, f: impl Fn(f32, f32) -> ([f32; 3], [f32; 3])) {
189        let base = (self.vertices.len() / 8) as u32;
190        for j in 0..=nv {
191            for i in 0..=nu {
192                let (u, v) = (i as f32 / nu as f32, j as f32 / nv as f32);
193                let (p, n) = f(u, v);
194                self.vertex(p, n, [u, v]);
195            }
196        }
197        let row = nu as u32 + 1;
198        for j in 0..nv as u32 {
199            for i in 0..nu as u32 {
200                let a = base + j * row + i;
201                self.indices.extend([a, a + 1, a + row, a + 1, a + row + 1, a + row]);
202            }
203        }
204    }
205}
206
207/// Builds a primitive. All fit in a unit box centered at the origin.
208pub fn primitive(kind: &str, segments: usize) -> Option<MeshData> {
209    let mut m = MeshData::default();
210    let seg = segments.max(3);
211    let tau = std::f32::consts::TAU;
212    match kind {
213        "cube" => {
214            // (normal, u axis, v axis) per face.
215            let faces: [([f32; 3], [f32; 3], [f32; 3]); 6] = [
216                ([0.0, 0.0, 1.0], [1.0, 0.0, 0.0], [0.0, -1.0, 0.0]),
217                ([0.0, 0.0, -1.0], [-1.0, 0.0, 0.0], [0.0, -1.0, 0.0]),
218                ([1.0, 0.0, 0.0], [0.0, 0.0, -1.0], [0.0, -1.0, 0.0]),
219                ([-1.0, 0.0, 0.0], [0.0, 0.0, 1.0], [0.0, -1.0, 0.0]),
220                ([0.0, 1.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, 1.0]),
221                ([0.0, -1.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, -1.0]),
222            ];
223            for (n, u, v) in faces {
224                m.grid(1, 1, |a, b| {
225                    let (x, y) = (a - 0.5, b - 0.5);
226                    let p = [
227                        n[0] * 0.5 + u[0] * x + v[0] * y,
228                        n[1] * 0.5 + u[1] * x + v[1] * y,
229                        n[2] * 0.5 + u[2] * x + v[2] * y,
230                    ];
231                    (p, n)
232                });
233            }
234        }
235        "plane" => m.grid(1, 1, |u, v| ([u - 0.5, 0.5 - v, 0.0], [0.0, 0.0, 1.0])),
236        "sphere" => m.grid(seg * 2, seg, |u, v| {
237            let (theta, phi) = (u * tau, v * std::f32::consts::PI);
238            let n = [-phi.sin() * theta.sin(), phi.cos(), -phi.sin() * theta.cos()];
239            ([n[0] * 0.5, n[1] * 0.5, n[2] * 0.5], n)
240        }),
241        "cylinder" | "cone" => {
242            let top = if kind == "cone" { 0.0 } else { 0.5 };
243            let slope = (0.5 - top) / 1.0;
244            m.grid(seg * 2, 1, |u, v| {
245                let a = u * tau;
246                let r = top + (0.5 - top) * v;
247                let n = normalize([a.sin(), slope, a.cos()]);
248                ([r * a.sin(), 0.5 - v, r * a.cos()], n)
249            });
250            // Caps as fans.
251            for (y, r, ny) in [(0.5f32, top, 1.0f32), (-0.5, 0.5, -1.0)] {
252                if r <= 0.0 {
253                    continue;
254                }
255                let c = m.vertex([0.0, y, 0.0], [0.0, ny, 0.0], [0.5, 0.5]);
256                let first = (m.vertices.len() / 8) as u32;
257                for i in 0..=seg * 2 {
258                    let a = i as f32 / (seg * 2) as f32 * tau;
259                    m.vertex(
260                        [r * a.sin(), y, r * a.cos()],
261                        [0.0, ny, 0.0],
262                        [0.5 + 0.5 * a.sin(), 0.5 + 0.5 * a.cos()],
263                    );
264                }
265                for i in 0..(seg * 2) as u32 {
266                    m.indices.extend([c, first + i, first + i + 1]);
267                }
268            }
269        }
270        "torus" => m.grid(seg * 2, seg, |u, v| {
271            let (a, b) = (u * tau, v * tau);
272            let (big, small) = (0.35, 0.15);
273            let n = [b.cos() * a.sin(), b.sin(), b.cos() * a.cos()];
274            (
275                [
276                    (big + small * b.cos()) * a.sin(),
277                    small * b.sin(),
278                    (big + small * b.cos()) * a.cos(),
279                ],
280                n,
281            )
282        }),
283        _ => return None,
284    }
285    Some(m)
286}
287
288/// Loads every mesh of a glTF/GLB file, with node transforms applied.
289pub fn load_gltf(path: &Path) -> Result<MeshData, String> {
290    let (doc, buffers) = if crate::svg::external_files_allowed() {
291        let (doc, buffers, _) = gltf::import(path).map_err(|e| format!("{}: {e}", path.display()))?;
292        (doc, buffers)
293    } else {
294        // Embedded buffers only (a GLB's binary chunk, data URIs).
295        let bytes = std::fs::read(path).map_err(|e| format!("{}: {e}", path.display()))?;
296        let g = gltf::Gltf::from_slice(&bytes).map_err(|e| format!("{}: {e}", path.display()))?;
297        let buffers = gltf::import_buffers(&g.document, None, g.blob)
298            .map_err(|e| format!("{}: {e} (external files are off)", path.display()))?;
299        (g.document, buffers)
300    };
301    let mut m = MeshData::default();
302    fn visit(node: gltf::Node, parent: Mat4, buffers: &[gltf::buffer::Data], m: &mut MeshData) {
303        let local = Mat4(node.transform().matrix().map(|c| c).concat().try_into().unwrap()).transpose();
304        let world = parent.mul(&local);
305        if let Some(mesh) = node.mesh() {
306            let normal_m = world.inverse_affine().transpose();
307            for prim in mesh.primitives() {
308                let r = prim.reader(|b| Some(&buffers[b.index()]));
309                let Some(pos) = r.read_positions() else { continue };
310                let pos: Vec<[f32; 3]> = pos.collect();
311                let normals: Vec<[f32; 3]> = r
312                    .read_normals()
313                    .map(|n| n.collect())
314                    .unwrap_or_else(|| vec![[0.0, 1.0, 0.0]; pos.len()]);
315                let uvs: Vec<[f32; 2]> = r
316                    .read_tex_coords(0)
317                    .map(|t| t.into_f32().collect())
318                    .unwrap_or_else(|| vec![[0.0, 0.0]; pos.len()]);
319                let base = (m.vertices.len() / 8) as u32;
320                for i in 0..pos.len() {
321                    let p = apply(&world, pos[i], 1.0);
322                    let n = normalize(apply(&normal_m, normals[i], 0.0));
323                    m.vertex(p, n, uvs[i]);
324                }
325                match r.read_indices() {
326                    Some(ix) => m.indices.extend(ix.into_u32().map(|i| base + i)),
327                    None => m.indices.extend((0..pos.len() as u32).map(|i| base + i)),
328                }
329            }
330        }
331        for child in node.children() {
332            visit(child, world, buffers, m);
333        }
334    }
335    let scene = doc
336        .default_scene()
337        .or_else(|| doc.scenes().next())
338        .ok_or("no scene in file")?;
339    for node in scene.nodes() {
340        visit(node, Mat4::IDENTITY, &buffers, &mut m);
341    }
342    if m.indices.is_empty() {
343        return Err(format!("{}: no triangles", path.display()));
344    }
345    Ok(m)
346}
347
348fn apply(m: &Mat4, v: [f32; 3], w: f32) -> [f32; 3] {
349    let a = &m.0;
350    [
351        a[0] * v[0] + a[1] * v[1] + a[2] * v[2] + a[3] * w,
352        a[4] * v[0] + a[5] * v[1] + a[6] * v[2] + a[7] * w,
353        a[8] * v[0] + a[9] * v[1] + a[10] * v[2] + a[11] * w,
354    ]
355}
356
357/// Numeric param reader for 3D nodes.
358pub struct Params<'a> {
359    pub node: &'a Node,
360    pub t: f64,
361}
362
363impl Params<'_> {
364    pub fn vec<const N: usize>(&self, name: &str, default: [f32; N]) -> [f32; N] {
365        let mut out = default;
366        if let Some(v) = self.node.params.get(name).and_then(|p| p.eval(self.t)) {
367            if v.len() == 1 {
368                out = [v[0] as f32; N];
369            } else {
370                for (o, x) in out.iter_mut().zip(v) {
371                    *o = x as f32;
372                }
373            }
374        }
375        out
376    }
377
378    pub fn num(&self, name: &str, default: f32) -> f32 {
379        self.vec(name, [default])[0]
380    }
381
382    pub fn text(&self, name: &str) -> Option<&str> {
383        text(self.node, name)
384    }
385
386    /// Linear straight-alpha color from a document color param.
387    pub fn color(&self, name: &str, default: [f32; 4]) -> [f32; 4] {
388        let c = match self.node.params.get(name) {
389            None => return default,
390            Some(Param::Text(s)) => match crate::ops::parse_hex(s) {
391                Some(c) => c,
392                None => return default,
393            },
394            Some(p) => {
395                let v = p.eval(self.t).unwrap_or_default();
396                match v.len() {
397                    3 => [v[0], v[1], v[2], 1.0],
398                    4 => [v[0], v[1], v[2], v[3]],
399                    _ => return default,
400                }
401            }
402        };
403        let l = |x: f64| crate::ops::srgb_to_linear(x) as f32;
404        [l(c[0]), l(c[1]), l(c[2]), c[3] as f32]
405    }
406
407    /// Object transform: T(position) * R(rotation) * S(scale).
408    pub fn model(&self) -> Mat4 {
409        let p = self.vec("position", [0.0, 0.0, 0.0]);
410        let r = self.vec("rotation", [0.0, 0.0, 0.0]);
411        let s = self.vec("scale", [1.0, 1.0, 1.0]);
412        Mat4::translate(p[0], p[1], p[2])
413            .mul(&Mat4::rotate_xyz(r))
414            .mul(&Mat4::scale(s[0], s[1], s[2]))
415    }
416}
417
418/// Mesh cache key and loader for a `mesh` node.
419/// Params that only place or shade a mesh; everything else shapes it.
420const NON_GEOMETRY: &[&str] = &[
421    "position",
422    "rotation",
423    "scale",
424    "color",
425    "metallic",
426    "roughness",
427    "emissive",
428    "opacity",
429];
430
431pub fn mesh_key(node: &Node) -> String {
432    use std::hash::{Hash, Hasher};
433    match (text(node, "src"), text(node, "primitive")) {
434        (Some(src), _) => format!("file:{src}"),
435        (None, Some("text" | "path")) => {
436            let mut h = std::collections::hash_map::DefaultHasher::new();
437            for (k, v) in &node.params {
438                if !NON_GEOMETRY.contains(&k.as_str()) {
439                    k.hash(&mut h);
440                    serde_json::to_string(v).unwrap_or_default().hash(&mut h);
441                }
442            }
443            format!("extruded:{:x}", h.finish())
444        }
445        (None, kind) => {
446            format!(
447                "prim:{}:{}",
448                kind.unwrap_or("cube"),
449                Params { node, t: 0.0 }.num("segments", 32.0) as usize
450            )
451        }
452    }
453}
454
455pub fn build_mesh(id: &str, node: &Node, base: &Path, fonts: &mut crate::geom::Fonts) -> Result<MeshData, RenderError> {
456    let bad = |param: &str, reason: String| RenderError::BadParam {
457        node: id.to_string(),
458        param: param.to_string(),
459        reason,
460    };
461    let p = Params { node, t: 0.0 };
462    match (text(node, "src"), text(node, "primitive").unwrap_or("cube")) {
463        (Some(src), _) => {
464            let path = if Path::new(src).is_absolute() {
465                Path::new(src).to_path_buf()
466            } else {
467                base.join(src)
468            };
469            load_gltf(&path).map_err(|e| bad("src", e))
470        }
471        (None, "text") => {
472            // Lay the text out at 100 px per world unit, centered, then extrude.
473            let size = p.num("size", 1.0).max(1e-3) as f64;
474            let mut layout = ultrafast_graph::Node {
475                op: "text".into(),
476                ..Default::default()
477            };
478            for k in [
479                "text",
480                "font",
481                "weight",
482                "style",
483                "tracking",
484                "line_height",
485                "features",
486                "width",
487            ] {
488                if let Some(v) = node.params.get(k) {
489                    layout.params.insert(k.into(), v.clone());
490                }
491            }
492            layout.params.insert("size".into(), Param::Number(100.0));
493            layout.params.insert(
494                "align".into(),
495                node.params
496                    .get("align")
497                    .cloned()
498                    .unwrap_or(Param::Text("center".into())),
499            );
500            layout.params.insert("valign".into(), Param::Text("middle".into()));
501            let fmt = ultrafast_graph::Format {
502                width: 1,
503                height: 1,
504                fps: 1.0,
505                duration: 1.0,
506                motion_blur: None,
507            };
508            let paths: Vec<kurbo::BezPath> =
509                crate::geom::text_paths(id, &layout, &fmt, 0.0, crate::ops::Affine::IDENTITY, fonts, base)?
510                    .0
511                    .into_iter()
512                    .map(|(p, _, _)| p)
513                    .collect();
514            extrude(
515                &paths,
516                100.0 / size,
517                p.num("depth", (0.25 * size) as f32) as f64,
518                p.num("bevel", 0.0) as f64,
519            )
520            .map_err(|e| bad("text", e))
521        }
522        (None, "path") => {
523            let d = text(node, "d").ok_or_else(|| bad("d", "path mesh needs `d` (SVG path data)".into()))?;
524            let path = kurbo::BezPath::from_svg(d).map_err(|e| bad("d", format!("invalid SVG path data: {e}")))?;
525            extrude(
526                &[path],
527                p.num("units", 100.0) as f64,
528                p.num("depth", 0.25) as f64,
529                p.num("bevel", 0.0) as f64,
530            )
531            .map_err(|e| bad("d", e))
532        }
533        (None, kind) => {
534            let seg = p.num("segments", 32.0) as usize;
535            primitive(kind, seg).ok_or_else(|| {
536                bad(
537                    "primitive",
538                    format!("unknown primitive `{kind}` (cube, plane, sphere, cylinder, cone, torus, text, path)"),
539                )
540            })
541        }
542    }
543}
544
545#[cfg(test)]
546mod tests {
547    use super::*;
548
549    #[test]
550    fn primitives_are_well_formed() {
551        for k in ["cube", "plane", "sphere", "cylinder", "cone", "torus"] {
552            let m = primitive(k, 16).unwrap();
553            let n = (m.vertices.len() / 8) as u32;
554            assert!(m.indices.len().is_multiple_of(3) && !m.indices.is_empty(), "{k}");
555            assert!(m.indices.iter().all(|&i| i < n), "{k}");
556        }
557    }
558
559    #[test]
560    fn affine_inverse_roundtrips() {
561        let m = Mat4::translate(1.0, 2.0, 3.0)
562            .mul(&Mat4::rotate_xyz([10.0, 20.0, 30.0]))
563            .mul(&Mat4::scale(2.0, 3.0, 4.0));
564        let i = m.mul(&m.inverse_affine());
565        for (a, b) in i.0.iter().zip(Mat4::IDENTITY.0.iter()) {
566            assert!((a - b).abs() < 1e-5);
567        }
568    }
569
570    #[test]
571    fn look_at_puts_target_in_front() {
572        let v = Mat4::look_at([0.0, 0.0, 5.0], [0.0, 0.0, 0.0], [0.0, 1.0, 0.0]);
573        let p = apply(&v, [0.0, 0.0, 0.0], 1.0);
574        assert!((p[2] + 5.0).abs() < 1e-5, "{p:?}");
575    }
576}
577
578/// Extrudes 2D outlines (output-space px, y down) into a mesh: front and
579/// back caps tessellated with the nonzero rule, side walls from the
580/// flattened contours. `units` px make one world unit; the result is
581/// centered on the origin, +y up, extruded `depth` along z.
582/// Extrudes closed 2D paths (pixel units, y down) into a mesh centered on
583/// the origin: `units` pixels per world unit, `depth` world units deep.
584/// `bevel` (world units) chamfers both rims at 45 degrees. Sides are smooth
585/// along curves and sharp at corners.
586pub fn extrude(paths: &[kurbo::BezPath], units: f64, depth: f64, bevel: f64) -> Result<MeshData, String> {
587    use lyon_tessellation::geometry_builder::{BuffersBuilder, VertexBuffers};
588    use lyon_tessellation::path::Path as LPath;
589    use lyon_tessellation::{FillOptions, FillRule, FillTessellator, FillVertex};
590
591    // Bounds for centering.
592    let mut b = [f64::MAX, f64::MAX, f64::MIN, f64::MIN];
593    for p in paths {
594        let r = kurbo::Shape::bounding_box(p);
595        b = [b[0].min(r.x0), b[1].min(r.y0), b[2].max(r.x1), b[3].max(r.y1)];
596    }
597    if b[0] > b[2] {
598        return Err("nothing to extrude".into());
599    }
600    let (cx, cy) = ((b[0] + b[2]) / 2.0, (b[1] + b[3]) / 2.0);
601    let to_world = |x: f64, y: f64| -> [f32; 2] { [((x - cx) / units) as f32, (-(y - cy) / units) as f32] };
602
603    // Contours, flattened by kurbo (exactly as the 2D renderer does).
604    let mut contours: Vec<Vec<[f32; 2]>> = Vec::new();
605    for p in paths {
606        let mut cur: Vec<[f32; 2]> = Vec::new();
607        kurbo::flatten(p.iter(), 0.25, |el| match el {
608            kurbo::PathEl::MoveTo(q) => {
609                if cur.len() > 2 {
610                    contours.push(std::mem::take(&mut cur));
611                }
612                cur.clear();
613                cur.push(to_world(q.x, q.y));
614            }
615            kurbo::PathEl::LineTo(q) => {
616                let w = to_world(q.x, q.y);
617                // Drop near-zero segments: their normals are noise, and a
618                // noisy normal breaks the smooth shading of a curve.
619                if cur
620                    .last()
621                    .is_none_or(|l| (l[0] - w[0]).abs() + (l[1] - w[1]).abs() > 2e-3)
622                {
623                    cur.push(w);
624                }
625            }
626            kurbo::PathEl::ClosePath => {
627                if cur.len() > 2 {
628                    contours.push(std::mem::take(&mut cur));
629                }
630            }
631            _ => {}
632        });
633        if cur.len() > 2 {
634            contours.push(cur);
635        }
636    }
637    for c in &mut contours {
638        if c.len() > 1 && (c[0][0] - c[c.len() - 1][0]).abs() + (c[0][1] - c[c.len() - 1][1]).abs() < 2e-3 {
639            c.pop();
640        }
641    }
642    contours.retain(|c| c.len() > 2);
643
644    // Which way is out of the solid, per contour: contour direction depends
645    // on the font format and on holes, so probe the filled region (nonzero
646    // winding over every contour) just off the longest segment.
647    let winding = |p: [f32; 2]| -> i32 {
648        let mut w = 0;
649        for c in &contours {
650            for i in 0..c.len() {
651                let (a, q) = (c[i], c[(i + 1) % c.len()]);
652                let side = (q[0] - a[0]) * (p[1] - a[1]) - (p[0] - a[0]) * (q[1] - a[1]);
653                if a[1] <= p[1] {
654                    if q[1] > p[1] && side > 0.0 {
655                        w += 1;
656                    }
657                } else if q[1] <= p[1] && side < 0.0 {
658                    w -= 1;
659                }
660            }
661        }
662        w
663    };
664    let raw_normal = |c: &[[f32; 2]], i: usize| -> [f32; 2] {
665        let (a, q) = (c[i], c[(i + 1) % c.len()]);
666        let (dx, dy) = (q[0] - a[0], q[1] - a[1]);
667        let l = (dx * dx + dy * dy).sqrt().max(1e-9);
668        [dy / l, -dx / l]
669    };
670    let flips: Vec<f32> = contours
671        .iter()
672        .map(|c| {
673            let i = (0..c.len())
674                .max_by(|&x, &y| {
675                    let len = |i: usize| {
676                        let (a, q) = (c[i], c[(i + 1) % c.len()]);
677                        (q[0] - a[0]).hypot(q[1] - a[1])
678                    };
679                    len(x).partial_cmp(&len(y)).unwrap()
680                })
681                .unwrap();
682            let (a, q) = (c[i], c[(i + 1) % c.len()]);
683            let n = raw_normal(c, i);
684            let probe = [(a[0] + q[0]) / 2.0 + n[0] * 1e-3, (a[1] + q[1]) / 2.0 + n[1] * 1e-3];
685            if winding(probe) != 0 { -1.0 } else { 1.0 }
686        })
687        .collect();
688    // Outward normal of segment i (vertex i to i+1) of contour ci.
689    let seg_normal_of = |ci: usize, c: &[[f32; 2]], i: usize| -> [f32; 2] {
690        let n = raw_normal(c, i);
691        [n[0] * flips[ci], n[1] * flips[ci]]
692    };
693    const SMOOTH: f32 = 0.82; // cos 35 degrees
694    let bevel = bevel.clamp(0.0, depth * 0.49) as f32;
695    // The inset outline the caps sit on (miter offset, so it stays parallel).
696    let inset: Vec<Vec<[f32; 2]>> = contours
697        .iter()
698        .enumerate()
699        .map(|(ci, c)| {
700            (0..c.len())
701                .map(|i| {
702                    if bevel <= 0.0 {
703                        return c[i];
704                    }
705                    let (np, nn) = (
706                        seg_normal_of(ci, c, (i + c.len() - 1) % c.len()),
707                        seg_normal_of(ci, c, i),
708                    );
709                    let m = [np[0] + nn[0], np[1] + nn[1]];
710                    let ml = (m[0] * m[0] + m[1] * m[1]).sqrt().max(1e-6);
711                    let m = [m[0] / ml, m[1] / ml];
712                    let len = bevel / (m[0] * nn[0] + m[1] * nn[1]).max(0.5);
713                    [c[i][0] - m[0] * len, c[i][1] - m[1] * len]
714                })
715                .collect()
716        })
717        .collect();
718
719    let mut lp = LPath::builder();
720    for c in &inset {
721        lp.begin(lyon_tessellation::math::point(c[0][0], c[0][1]));
722        for v in &c[1..] {
723            lp.line_to(lyon_tessellation::math::point(v[0], v[1]));
724        }
725        lp.end(true);
726    }
727    let path = lp.build();
728    let mut buffers: VertexBuffers<[f32; 2], u32> = VertexBuffers::new();
729    FillTessellator::new()
730        .tessellate_path(
731            &path,
732            &FillOptions::tolerance(0.001).with_fill_rule(FillRule::NonZero),
733            &mut BuffersBuilder::new(&mut buffers, |v: FillVertex| v.position().to_array()),
734        )
735        .map_err(|e| format!("tessellation failed: {e:?}"))?;
736
737    let mut m = MeshData::default();
738    let hz = (depth / 2.0) as f32;
739    let uv = |p: [f32; 2]| {
740        [
741            ((p[0] as f64 * units + cx - b[0]) / (b[2] - b[0]).max(1e-9)) as f32,
742            ((cy - p[1] as f64 * units - b[1]) / (b[3] - b[1]).max(1e-9)) as f32,
743        ]
744    };
745    // Front (+z) and back (-z) caps.
746    for (z, nz, flip) in [(hz, 1.0f32, false), (-hz, -1.0f32, true)] {
747        let base = (m.vertices.len() / 8) as u32;
748        for p in &buffers.vertices {
749            m.vertex([p[0], p[1], z], [0.0, 0.0, nz], uv(*p));
750        }
751        for tri in buffers.indices.chunks_exact(3) {
752            if flip {
753                m.indices.extend([base + tri[0], base + tri[2], base + tri[1]]);
754            } else {
755                m.indices.extend([base + tri[0], base + tri[1], base + tri[2]]);
756            }
757        }
758    }
759    if depth <= 0.0 {
760        return Ok(m);
761    }
762    // Walls: for each segment, the bevel ring at the front, the side, and
763    // the bevel ring at the back. Vertex normals are averaged across a
764    // vertex where the outline is smooth, so curves shade round.
765    let side_z = hz - bevel;
766    for (ci, c) in contours.iter().enumerate() {
767        let n = c.len();
768        let normals: Vec<[f32; 2]> = (0..n).map(|i| seg_normal_of(ci, c, i)).collect();
769        let vertex_normal = |i: usize, seg: usize| -> [f32; 2] {
770            let (np, nn) = (normals[(i + n - 1) % n], normals[i % n]);
771            if np[0] * nn[0] + np[1] * nn[1] > SMOOTH {
772                let s = [np[0] + nn[0], np[1] + nn[1]];
773                let l = (s[0] * s[0] + s[1] * s[1]).sqrt().max(1e-9);
774                [s[0] / l, s[1] / l]
775            } else {
776                normals[seg]
777            }
778        };
779        for i in 0..n {
780            let j = (i + 1) % n;
781            let (na, nb) = (vertex_normal(i, i), vertex_normal(j, i));
782            // Side wall.
783            let v0 = m.vertex([c[i][0], c[i][1], side_z], [na[0], na[1], 0.0], [0.0, 0.0]);
784            let v1 = m.vertex([c[j][0], c[j][1], side_z], [nb[0], nb[1], 0.0], [1.0, 0.0]);
785            let v2 = m.vertex([c[j][0], c[j][1], -side_z], [nb[0], nb[1], 0.0], [1.0, 1.0]);
786            let v3 = m.vertex([c[i][0], c[i][1], -side_z], [na[0], na[1], 0.0], [0.0, 1.0]);
787            m.indices.extend([v0, v1, v2, v0, v2, v3]);
788            if bevel > 0.0 {
789                let q = &inset[ci];
790                let k = std::f32::consts::FRAC_1_SQRT_2;
791                for (zs, zo, sign) in [(side_z, hz, 1.0f32), (-side_z, -hz, -1.0f32)] {
792                    let (ba, bb) = ([na[0] * k, na[1] * k, sign * k], [nb[0] * k, nb[1] * k, sign * k]);
793                    let w0 = m.vertex([c[i][0], c[i][1], zs], ba, [0.0, 0.0]);
794                    let w1 = m.vertex([c[j][0], c[j][1], zs], bb, [1.0, 0.0]);
795                    let w2 = m.vertex([q[j][0], q[j][1], zo], bb, [1.0, 1.0]);
796                    let w3 = m.vertex([q[i][0], q[i][1], zo], ba, [0.0, 1.0]);
797                    if sign > 0.0 {
798                        m.indices.extend([w0, w2, w1, w0, w3, w2]);
799                    } else {
800                        m.indices.extend([w0, w1, w2, w0, w2, w3]);
801                    }
802                }
803            }
804        }
805    }
806    Ok(m)
807}
808
809#[cfg(test)]
810mod bevel_tests {
811    use super::*;
812
813    #[test]
814    fn bevel_adds_rings_and_insets_caps() {
815        let sq = kurbo::BezPath::from_svg("M0 0 H 100 V 100 H 0 Z").unwrap();
816        let flat = extrude(std::slice::from_ref(&sq), 100.0, 0.5, 0.0).unwrap();
817        let bev = extrude(&[sq], 100.0, 0.5, 0.1).unwrap();
818        assert!(
819            bev.vertices.len() > flat.vertices.len(),
820            "{} vs {}",
821            bev.vertices.len(),
822            flat.vertices.len()
823        );
824        // The front cap is inset by the bevel: its x extent shrinks by 0.1 each side.
825        let front: Vec<f32> = bev
826            .vertices
827            .chunks_exact(8)
828            .filter(|v| v[5] > 0.99)
829            .map(|v| v[0])
830            .collect();
831        let max = front.iter().cloned().fold(f32::MIN, f32::max);
832        assert!((max - 0.4).abs() < 1e-3, "front cap reaches {max}");
833    }
834}
835
836#[cfg(test)]
837mod smooth_tests {
838    use super::*;
839
840    #[test]
841    fn curved_sides_shade_smoothly() {
842        use kurbo::Shape;
843        let circle = kurbo::Circle::new((50.0, 50.0), 40.0).to_path(0.1);
844        let m = extrude(&[circle], 100.0, 0.5, 0.0).unwrap();
845        // Side vertices: normal z == 0. Group by position; normals at the same
846        // position must agree.
847        let mut by_pos: std::collections::HashMap<(i64, i64, i64), Vec<[f32; 3]>> = Default::default();
848        for v in m.vertices.chunks_exact(8) {
849            if v[5].abs() < 1e-3 {
850                let k = ((v[0] * 1e4) as i64, (v[1] * 1e4) as i64, (v[2] * 1e4) as i64);
851                by_pos.entry(k).or_default().push([v[3], v[4], v[5]]);
852            }
853        }
854        let mut worst = 1.0f32;
855        for ns in by_pos.values() {
856            for a in ns {
857                for b in ns {
858                    worst = worst.min(a[0] * b[0] + a[1] * b[1] + a[2] * b[2]);
859                }
860            }
861        }
862        assert!(worst > 0.999, "normals at a shared vertex disagree: cos {worst}");
863    }
864}