diff --git a/crates/effects/src/revolve.rs b/crates/effects/src/revolve.rs index acd6cf7c94..783bbcf953 100644 --- a/crates/effects/src/revolve.rs +++ b/crates/effects/src/revolve.rs @@ -797,11 +797,12 @@ pub(crate) fn revolve_meshes(n: &Node, total: &mut usize, limit: usize) -> Resul } let (path, rule) = object_profile(n, "Revolve")?; let ctx = GeomContext::of(n); - let mesh = |path: &PathData, fx: &Effect, item: &AppearanceItem| -> Result { + let mut keep = |out: &mut Vec, path: &PathData, fx: &Effect, item: &AppearanceItem| -> Result<(), String> { let b = path.bounds().ok_or("Revolve requires a shape with at least two anchors")?; let (paint, opacity, _) = paint_of(item); - let mesh = vectorcraft_three_d::revolve_mesh(path, rule, b, fx_options(fx))?; - Ok(crate::SolidMesh::plain(mesh, crate::solids::mesh_color(&paint, opacity))) + surface_meshes(path, rule, b, fx, fx_options(fx), (&paint, opacity, 1.0), true)? + .into_iter() + .try_for_each(|m| crate::solids::keep_mesh(out, total, m, limit)) }; if let Some(index) = n.appearance.effects.iter().position(|e| e.visible && is_revolve(&e.id)) { let before = n.appearance.effects.get(..index).unwrap_or_default(); @@ -810,7 +811,7 @@ pub(crate) fn revolve_meshes(n: &Node, total: &mut usize, limit: usize) -> Resul let paints = solid_paints(n); let item = surface_item(&paints).ok_or("the revolved object has no fill or stroke")?; let mut out = vec![]; - crate::solids::keep_mesh(&mut out, total, mesh(&path, fx, item)?, limit)?; + keep(&mut out, &path, fx, item)?; return Ok(out); } let path = geometry(&path, &n.appearance.effects, &ctx); @@ -820,12 +821,69 @@ pub(crate) fn revolve_meshes(n: &Node, total: &mut usize, limit: usize) -> Resul && let Some(fx) = item.effects().get(index) { let p = geometry(&path, item.effects().get(..index).unwrap_or_default(), &ctx.item(item)); - crate::solids::keep_mesh(&mut out, total, mesh(&p, fx, item)?, limit)?; + keep(&mut out, &p, fx, item)?; } } Ok(out) } +/// The surface Revolve `fx` sweeps from `path` (filled under `rule`) about the axis of `b` with +/// `options`, painted `paint` at `opacity` in a group member of opacity `member` (1 for an object +/// of its own), as meshes. When `graphics` and `fx` maps graphics onto the side, the side's +/// triangles are a mesh of their own with the point of the unrolled side surface each corner shows +/// ([`crate::MeshGraphics`]), the points the canvas places the graphics by +/// ([`crate::solids::graphics::surface_parts`]), after a mesh of the rest (the end caps and the cut +/// sides). As on the canvas, the graphics take `opacity`, and `member` applies to the side and its +/// graphics together. Otherwise the surface is one plain mesh. +fn surface_meshes( + path: &PathData, + rule: FillRule, + b: Rect, + fx: &Effect, + options: Revolve, + (paint, opacity, member): (&Paint, f32, f32), + graphics: bool, +) -> Result, String> { + let color = crate::solids::mesh_color(paint, opacity * member); + let list: Vec = if graphics && fx.id == REVOLVE && options.map_surface { + crate::solids::mapped_graphics(&merged_params(&fx.id, &fx.params)).into_iter().filter(|g| g.face == crate::PlanarFace::Front).collect() + } else { + vec![] + }; + if list.is_empty() { + return Ok(vec![crate::SolidMesh::plain(vectorcraft_three_d::revolve_mesh(path, rule, b, options)?, color)]); + } + let (mesh, on) = vectorcraft_three_d::revolve_mesh_surface(path, rule, b, options)?; + let (mut side, mut rest, mut art) = (vectorcraft_three_d::Mesh::default(), vectorcraft_three_d::Mesh::default(), vec![]); + for (t, points) in mesh.triangles.iter().zip(&on) { + let corner = |i: u32| mesh.positions.get(i as usize).copied().zip(mesh.normals.get(i as usize).copied()); + let Some(corners) = t.iter().map(|&i| corner(i)).collect::>>() else { continue }; + let into = match points { + Some(points) => { + art.extend(points); + &mut side + } + None => &mut rest, + }; + let base = into.positions.len() as u32; + for (p, n) in corners { + into.positions.push(p); + into.normals.push(n); + } + into.triangles.push([base, base + 1, base + 2]); + } + let mut out = vec![]; + if !rest.is_empty() { + out.push(crate::SolidMesh::plain(rest, color)); + } + if !side.is_empty() { + let graphics = + crate::MeshGraphics { face: crate::PlanarFace::Front, graphics: list, center: Point::ZERO, art, opacity, object: member.clamp(0.0, 1.0) }; + out.push(crate::SolidMesh { mesh: side, color, graphics: Some(graphics) }); + } + Ok(out) +} + /// The outline of every face [`revolve_art`] draws for `n`'s Revolve or Revolve (Classic) (its symbol /// instances, blends and clipping groups already resolved), in document coordinates: with the /// effect on the object, the surface in its top visible fill (else its stroke); with it on fills and strokes, one surface for each of @@ -919,12 +977,15 @@ fn group_meshes(n: &Node, total: &mut usize, limit: usize) -> Result Vec { let list = graphics::mapped_graphics(p); if list.is_empty() || !takes_graphics(id) || id == crate::REVOLVE { diff --git a/crates/engine/src/cmd/assets.rs b/crates/engine/src/cmd/assets.rs index 05c2fda1d7..d253c4803f 100644 --- a/crates/engine/src/cmd/assets.rs +++ b/crates/engine/src/cmd/assets.rs @@ -80,7 +80,7 @@ pub fn specs() -> Vec { "Export 3D Assets", [], None, - "{assets?: [asset id…] (default every 3D asset), folder?, zip?, textureSize?: 128…4096 (default 1024: the pixels along the longer side of each face's texture)} each 3D asset's object as a mesh file in its format (assets.set3DFormat), named after the asset: USDA or USDZ, glTF 2.0 (one .gltf, its buffer embedded) or OBJ with its .mtl (whitespace and # in an OBJ's name become _). Every solid of the object (the fill's, each stroke's, a group's members') is a mesh with a material in the color it is painted; faces turned away from the viewer are included, at the object's 3D rotation, y up, about the point it turns about, in points (glTF: meters). The graphics mapped onto a plane or onto Extrude & Bevel's front or back cap (threeD.mapGraphic) are a PNG texture of that face: its color with the graphics drawn over it, flat and unlit, on a mesh of the face's own with texture coordinates; glTF embeds it, USDZ stores it after the layer, and OBJ and USDA write it beside them as -texture-1.png… (whitespace, # and @ become _); a face that is not opaque keeps its opacity in the texture's alpha, and an OBJ also gets -texture-1-opacity.png…, the alpha as gray levels for its map_d. Graphics on Revolve's side are not exported. Files that would share a name get -2, -3…; an object with a hole that crosses its face's outline or another hole, or with more than 2,000,000 triangles, or textures of more than 67,108,864 pixels in one export, is refused → {files: [path…]} (no folder: {files: [{name, dataBase64}]}, or with zip one zip as {name, dataBase64, files})", + "{assets?: [asset id…] (default every 3D asset), folder?, zip?, textureSize?: 128…4096 (default 1024: the pixels along the longer side of each face's texture)} each 3D asset's object as a mesh file in its format (assets.set3DFormat), named after the asset: USDA or USDZ, glTF 2.0 (one .gltf, its buffer embedded) or OBJ with its .mtl (whitespace and # in an OBJ's name become _). Every solid of the object (the fill's, each stroke's, a group's members') is a mesh with a material in the color it is painted; faces turned away from the viewer are included, at the object's 3D rotation, y up, about the point it turns about, in points (glTF: meters). The graphics mapped onto a plane or onto Extrude & Bevel's front or back cap (threeD.mapGraphic) are a PNG texture of that face: its color with the graphics drawn over it, flat and unlit, on a mesh of the face's own with texture coordinates; glTF embeds it, USDZ stores it after the layer, and OBJ and USDA write it beside them as -texture-1.png… (whitespace, # and @ become _); a face that is not opaque keeps its opacity in the texture's alpha, and an OBJ also gets -texture-1-opacity.png…, the alpha as gray levels for its map_d. Graphics on Revolve's side (in a group, the side of the member with the longest profile) are a texture of the side unrolled as the canvas lays it out, on a mesh of the side's triangles; its end caps and cut sides stay plain. Files that would share a name get -2, -3…; an object with a hole that crosses its face's outline or another hole, or with more than 2,000,000 triangles, or textures of more than 67,108,864 pixels in one export, is refused → {files: [path…]} (no folder: {files: [{name, dataBase64}]}, or with zip one zip as {name, dataBase64, files})", has_doc, export_3d ), diff --git a/crates/engine/src/tests/assets_3d.rs b/crates/engine/src/tests/assets_3d.rs index d546eed793..1a647fb798 100644 --- a/crates/engine/src/tests/assets_3d.rs +++ b/crates/engine/src/tests/assets_3d.rs @@ -312,6 +312,112 @@ fn export_3d_paints_mapped_graphics_on_their_caps_in_every_format() { assert_eq!(image::load_from_memory(&png).unwrap().to_rgba8().dimensions(), (1024, 1024), "1024 pixels by default"); } +/// A blue 100 × 100 square revolved straight on about its left edge with `params`, with the red +/// 10 × 20 graphic "Mark" mapped onto its side `x` pt from the middle, collected as a 3D asset named +/// "Ball" in `format`. +fn revolved(format: &str, params: Value, x: f64) -> (Session, u64) { + let mut s = session(); + let mark = run(&mut s, "path.create", json!({"d": "M300 300L310 300L310 320L300 320Z"}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"color": "#ff0000"})); + run(&mut s, "threeD.addGraphic", json!({"name": "Mark", "ids": [mark]})); + let id = run(&mut s, "path.create", json!({"d": "M100 100L200 100L200 200L100 200Z"}))["id"].as_u64().unwrap(); + run(&mut s, "paint.setFill", json!({"color": "#0000ff"})); + let mut p = json!({"rotationX": 0.0, "rotationY": 0.0, "rotationZ": 0.0}); + p.as_object_mut().unwrap().extend(params.as_object().unwrap().clone()); + run(&mut s, "effect.apply", json!({"effect": "threeD.revolve", "params": p})); + run(&mut s, "threeD.mapGraphic", json!({"symbol": "Mark", "x": x, "ids": [id]})); + run(&mut s, "layer.setProps", json!({"id": id, "name": "Ball"})); + let asset = run(&mut s, "assets.add3D", json!({"ids": [id], "format": format}))["assets"][0].as_u64().unwrap(); + (s, asset) +} + +#[test] +fn export_3d_paints_graphics_mapped_onto_a_revolves_side_in_every_format() { + for (format, names) in [ + ("usda", vec!["Ball.usda", "Ball-texture-1.png"]), + ("usdz", vec!["Ball.usdz"]), + ("gltf", vec!["Ball.gltf"]), + ("obj", vec!["Ball.obj", "Ball.mtl", "Ball-texture-1.png"]), + ] { + let (mut s, _) = revolved(format, json!({}), 0.0); + let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128}))); + assert_eq!(out.iter().map(|(n, _)| n.as_str()).collect::>(), names, "{format}"); + } + // The side unrolled is 200π around the axis (the square's far edge is 100 from it) by 300 + // along the profile (its edge on the axis sweeps nothing): 512 × 245 pixels, blue with the red + // graphic at the middle. + let (mut s, _) = revolved("usda", json!({}), 0.0); + let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 512}))); + let picture = &out[1].1; + let scale = 512.0 / (200.0 * std::f64::consts::PI); + assert_eq!(image::load_from_memory(picture).unwrap().to_rgba8().dimensions(), (512, (300.0 * scale).ceil() as u32)); + let middle = (150.0 * scale) as u32; + assert!(is_red(pixel(picture, 256, middle)) && is_blue(pixel(picture, 10, 10)), "{:?}", pixel(picture, 256, middle)); + let usda = String::from_utf8(out[0].1.clone()).unwrap(); + assert_eq!((usda.matches("def Mesh").count(), usda.matches("primvars:st").count()), (1, 1), "the side is the only face"); + // Moved 50 pt around the axis, the graphic moves as far across the picture. + let (mut s, _) = revolved("usda", json!({}), 50.0); + let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 512}))); + let moved = (256.0 + 50.0 * scale).round() as u32; + assert!(is_red(pixel(&out[1].1, moved, middle)) && is_blue(pixel(&out[1].1, 256, middle))); + // An OBJ's texture coordinates stay inside the picture, as OBJ reads them (up from its bottom). + let (mut s, _) = revolved("obj", json!({}), 0.0); + let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128}))); + let obj = String::from_utf8(out[0].1.clone()).unwrap(); + let vt: Vec = obj.lines().filter_map(|l| l.strip_prefix("vt ")).flat_map(|l| l.split(' ').map(|v| v.parse::().unwrap())).collect(); + assert!(!vt.is_empty() && vt.iter().all(|v| (-1e-9..=1.0 + 1e-9).contains(v)), "{vt:?}"); + assert!(String::from_utf8(out[1].1.clone()).unwrap().contains("map_Kd -clamp on Ball-texture-1.png")); + // glTF embeds the picture, and the side's coordinates are its TEXCOORD_0. + let (mut s, _) = revolved("gltf", json!({}), 0.0); + let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128}))); + let g: Value = serde_json::from_slice(&out[0].1).unwrap(); + assert_eq!(g["images"].as_array().map(Vec::len), Some(1)); + assert!(g["meshes"].as_array().unwrap().iter().any(|m| !m["primitives"][0]["attributes"]["TEXCOORD_0"].is_null())); +} + +#[test] +fn a_partial_revolve_keeps_its_cut_sides_plain_beside_its_textured_side() { + let (mut s, asset) = revolved("usda", json!({"angle": 270.0}), 0.0); + let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128}))); + assert_eq!(out.iter().map(|(n, _)| n.as_str()).collect::>(), ["Ball.usda", "Ball-texture-1.png"]); + let usda = String::from_utf8(out[0].1.clone()).unwrap(); + assert_eq!((usda.matches("def Mesh").count(), usda.matches("primvars:st").count()), (2, 1), "the cut sides and the side"); + let d = &s.doc().unwrap().doc; + let id = d.asset(asset).unwrap().nodes[0].0; + // Without its graphics the surface is one plain mesh, as before. + run(&mut s, "select.set", json!({"ids": [id]})); + run(&mut s, "effect.setParams", json!({"index": 0, "params": {"graphics": []}})); + let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128}))); + assert_eq!(out.iter().map(|(n, _)| n.as_str()).collect::>(), ["Ball.usda"]); + assert_eq!(String::from_utf8(out[0].1.clone()).unwrap().matches("def Mesh").count(), 1); +} + +#[test] +fn a_revolved_groups_graphics_export_on_its_longest_members_side_only() { + let mut s = session(); + let mark = run(&mut s, "path.create", json!({"d": "M300 300L310 300L310 320L300 320Z"}))["id"].clone(); + run(&mut s, "threeD.addGraphic", json!({"name": "Mark", "ids": [mark]})); + let a = run(&mut s, "path.create", json!({"d": "M100 100L140 100L140 200L100 200Z"}))["id"].as_u64().unwrap(); + let b = run(&mut s, "path.create", json!({"d": "M100 120L160 120L160 130L100 130Z"}))["id"].as_u64().unwrap(); + let g = run(&mut s, "object.group", json!({"ids": [a, b]}))["id"].as_u64().unwrap(); + run(&mut s, "select.set", json!({"ids": [g]})); + run(&mut s, "effect.apply", json!({"effect": "threeD.revolve", "params": {"rotationX": 0.0, "rotationY": 0.0, "rotationZ": 0.0}})); + run(&mut s, "threeD.mapGraphic", json!({"symbol": "Mark", "ids": [g]})); + let d = &s.doc().unwrap().doc; + let parts = vectorcraft_render::effects::three_d_meshes_in(Some(d), d.node(vectorcraft_doc::NodeId(g)).unwrap()).unwrap(); + assert_eq!(parts.len(), 2); + let textured: Vec = parts.iter().enumerate().filter(|(_, p)| p.graphics.is_some()).map(|(k, _)| k).collect(); + assert_eq!(textured, [0], "the taller member's side"); + // A half-opaque member: as on the canvas, its opacity applies to its side and the graphics + // together, and the graphics keep the opacity of the fill. + run(&mut s, "transparency.set", json!({"ids": [a], "opacity": 50})); + let d = &s.doc().unwrap().doc; + let parts = vectorcraft_render::effects::three_d_meshes_in(Some(d), d.node(vectorcraft_doc::NodeId(g)).unwrap()).unwrap(); + let graphics = parts[0].graphics.as_ref().unwrap(); + assert_eq!((graphics.opacity, graphics.object), (1.0, 0.5)); + assert!((parts[0].color[3] - 0.5).abs() < 1e-6, "{:?}", parts[0].color); +} + #[test] fn a_texture_takes_the_opacity_of_the_fill_and_of_the_object_as_the_canvas_draws_them() { let half = |a: u8| (120..=135).contains(&a); diff --git a/crates/three-d/src/lib.rs b/crates/three-d/src/lib.rs index 18d371b420..f5537c9fea 100644 --- a/crates/three-d/src/lib.rs +++ b/crates/three-d/src/lib.rs @@ -22,7 +22,7 @@ mod lights; pub use lights::{Light, Lights, MAX_LIGHTS}; mod caps; mod mesh; -pub use mesh::{Mesh, MeshedSolid, extrude_mesh, extrude_meshed, inflate_meshed, inflate_meshes, plane_mesh, revolve_mesh}; +pub use mesh::{Mesh, MeshedSolid, extrude_mesh, extrude_meshed, inflate_meshed, inflate_meshes, plane_mesh, revolve_mesh, revolve_mesh_surface}; mod shadow; pub use shadow::{ MAX_SHADOW_FACES, Shadow, ShadowCaster, ShadowPlane, ShadowPosition, SolidFaces, TOO_COMPLEX_SHADOW, extrude_shadowed, inflate_shadowed, @@ -978,7 +978,22 @@ fn revolve_face_limit(o: Revolve) -> usize { /// each turned out of the region `rule` fills. fn revolve_faces(path: &PathData, rule: FillRule, bounds: Rect, options: Revolve, mesh: Option<&mut Vec>) -> Result, String> { let draw = mesh.is_none(); - revolve_sweep(path, rule, bounds, options, draw, mesh).map(|(faces, _)| faces) + revolve_sweep(path, rule, bounds, options, draw, mesh, None).map(|(faces, _)| faces) +} + +/// The faces of Revolve's surface before projection, kept in `faces` as [`revolve_faces`] keeps +/// them, and in `surface` where the corners of each face of the side lie on the side surface +/// ([`SurfaceCell`]), as the drawn faces place them. Only a sweep with [`Revolve::map_surface`] lays +/// out its side; only the longest contour of a compound profile has one. +pub(crate) fn revolve_surface_faces( + path: &PathData, + rule: FillRule, + bounds: Rect, + options: Revolve, + faces: &mut Vec, + surface: &mut SurfaceQuads, +) -> Result<(), String> { + revolve_sweep(path, rule, bounds, options, false, Some(faces), Some(surface)).map(|_| ()) } #[cfg(test)] @@ -1035,11 +1050,19 @@ fn cap_outward(profile: &[Point], index: usize, center_y: f64) -> Option<(Point, /// Keep for a mesh the faces of one contour's profile `s`, which runs round the region it sweeps as /// `turn` says (its holes' walls turned the other way): a quad for each edge at each step, then for /// each end in `caps` (0 the first, 1 the last) the disk, or for a sweep of less than a full turn -/// the sector with its center on the axis. `keep` keeps one face with its outward normal; its -/// error, or an edge with invalid coordinates, stops the faces. -fn keep_profile(at: &Sweeping, s: &Swept, turn: f64, caps: &[usize], mut keep: impl FnMut(Vec, V3) -> Result<(), String>) -> Result<(), String> { +/// the sector with its center on the axis. `keep` keeps one face with its outward normal and, for a +/// quad of the side when `surface` lays it out, where each of its corners lies on the side surface +/// ([`SurfaceCell`]); its error, or an edge with invalid coordinates, stops the faces. +fn keep_profile( + at: &Sweeping, + s: &Swept, + turn: f64, + caps: &[usize], + surface: Option>, + mut keep: impl FnMut(Vec, V3, Option<[Point; 4]>) -> Result<(), String>, +) -> Result<(), String> { let (o, steps) = (at.o, at.steps); - for (pair, hole) in s.points.windows(2).zip(&s.holes) { + for (i, (pair, hole)) in s.points.windows(2).zip(&s.holes).enumerate() { let [a, b] = pair else { continue }; let turn = if *hole { -turn } else { turn }; if ![a.x, a.y, b.x, b.y].iter().all(|v| v.is_finite() && v.abs() <= 1e8) { @@ -1051,7 +1074,14 @@ fn keep_profile(at: &Sweeping, s: &Swept, turn: f64, caps: &[usize], mut keep: i // swept to the middle of the step. let (dr, dy) = ((b.x - a.x) * turn, (b.y - a.y) * turn); let (sin, cos) = (at.sweep * (j as f64 + 0.5) / steps as f64).sin_cos(); - keep(vec![v0, v1, v2, v3], o.rotate(V3(dy * cos, -dr, dy * sin)))?; + // The corners on the side surface, as the drawn faces place them. + let uv = surface.map(|(along, angle)| { + let [va, vb] = along.get(i).copied().unwrap_or_default(); + let [t0, t1] = angle(j); + let (ra, rb) = ((a.x - at.axis).abs(), (b.x - at.axis).abs()); + [Point::new(t0 * ra, va), Point::new(t0 * rb, vb), Point::new(t1 * rb, vb), Point::new(t1 * ra, va)] + }); + keep(vec![v0, v1, v2, v3], o.rotate(V3(dy * cos, -dr, dy * sin)), uv)?; } } for &index in caps { @@ -1062,11 +1092,19 @@ fn keep_profile(at: &Sweeping, s: &Swept, turn: f64, caps: &[usize], mut keep: i } else { cap.insert(0, o.rotate(V3(0.0, end.y - at.center_y, 0.0))); } - keep(cap, o.rotate(V3(0.0, outward, 0.0)))?; + keep(cap, o.rotate(V3(0.0, outward, 0.0)), None)?; } Ok(()) } +/// How a contour's side lies on the side surface ([`SurfaceCell`]): the surface y of each end of +/// each piece of its profile ([`along_profile`]) and the surface angle at each end of a step. +type SurfaceLayout<'a> = (&'a [[f64; 2]], &'a dyn Fn(usize) -> [f64; 2]); + +/// Where the corners of the faces of Revolve's mesh lie on its side surface: the index of a face +/// among the faces kept, and the surface point of each of its four corners, in order. +pub(crate) type SurfaceQuads = Vec<(usize, [Point; 4])>; + /// Twice the signed area of the polygon `ring`. fn ring_area(ring: &[Point]) -> f64 { ring.iter().zip(ring.iter().cycle().skip(1)).take(ring.len()).map(|(p, q)| p.x * q.y - q.x * p.y).sum() @@ -1323,7 +1361,9 @@ fn lose_mesh(draw: bool, mesh: &mut Option<&mut Vec>, lost: &mut O /// [`revolve`]'s faces when `draw`, and with `mesh` the surface's faces before projection kept /// there from the same sweep, each turned out of the region `rule` fills. While faces are drawn, an /// error keeping faces for the mesh stops only the mesh: the error comes back beside the faces -/// drawn, and `mesh` keeps no more faces. Without `draw` that error is the result. +/// drawn, and `mesh` keeps no more faces. Without `draw` that error is the result. With `surface`, +/// the faces kept of the side of the contour that carries the graphics are listed there with their +/// corners on the side surface ([`revolve_surface_faces`]). fn revolve_sweep( path: &PathData, rule: FillRule, @@ -1331,6 +1371,7 @@ fn revolve_sweep( options: Revolve, draw: bool, mut mesh: Option<&mut Vec>, + mut surface: Option<&mut SurfaceQuads>, ) -> Result<(Vec, Option), String> { #[cfg(test)] REVOLVED.with(|n| n.set(n.get() + 1)); @@ -1534,7 +1575,15 @@ fn revolve_sweep( let turn = prepare(&mut kept); cuts.add(&kept, sp.closed, true); let caps: Vec = rings.iter().enumerate().filter_map(|(i, r)| r.as_ref().map(|_| i)).collect(); - let kept = keep_profile(&at, &kept, turn, &caps, |face, normal| keep(m, face, normal)); + let along = (surface.is_some() && surface_contour == Some(contour)).then(|| along_profile(&kept.points, axis, sp.closed)); + let layout = along.as_deref().map(|along| (along, &surface_angle as &dyn Fn(usize) -> [f64; 2])); + let kept = keep_profile(&at, &kept, turn, &caps, layout, |face, normal, uv| { + keep(m, face, normal)?; + if let (Some(uv), Some(s)) = (uv, surface.as_deref_mut()) { + s.push((m.len() - 1, uv)); + } + Ok(()) + }); if let Err(e) = kept { lose_mesh(draw, &mut mesh, &mut lost, e)?; } diff --git a/crates/three-d/src/mesh.rs b/crates/three-d/src/mesh.rs index 14284cb1bf..5262bb6131 100644 --- a/crates/three-d/src/mesh.rs +++ b/crates/three-d/src/mesh.rs @@ -8,7 +8,7 @@ //! turned plane) are cut into triangles: each hole is joined to its outline by a bridge, then the //! outline is cut by ear clipping. -use vectorcraft_geom::{FillRule, PathData, Rect}; +use vectorcraft_geom::{FillRule, PathData, Point, Rect}; use crate::solid::{Face3, Keep, extrude_faces, inflate_faces, plane_faces}; use crate::{Extrude, Facet, Inflate, Revolve, V3, View}; @@ -127,6 +127,21 @@ pub fn revolve_mesh(path: &PathData, rule: FillRule, bounds: Rect, options: Revo mesh(&faces) } +/// [`revolve_mesh`], with where each corner of each triangle of the side lies on the side surface +/// unrolled ([`crate::SurfaceCell`]), as the effect places a graphic mapped onto the side: one +/// entry for each triangle, in order, `None` for a triangle of an end cap, of a cut side or of a +/// contour other than the one that carries the graphics. Only a sweep with +/// [`Revolve::map_surface`] lays out its side; without it every entry is `None`. +pub fn revolve_mesh_surface(path: &PathData, rule: FillRule, bounds: Rect, options: Revolve) -> Result { + let (mut faces, mut surface) = (vec![], vec![]); + crate::revolve_surface_faces(path, rule, bounds, options, &mut faces, &mut surface)?; + mesh_on(&faces, Some(&surface)) +} + +/// A mesh with, for each of its triangles, the surface point of each corner, or `None` +/// ([`revolve_mesh_surface`]). +pub type SurfaceMesh = (Mesh, Vec>); + /// The area-weighted normal of `contours` (Newell's method). pub(crate) fn newell(contours: &[Vec]) -> V3 { let mut n = V3::default(); @@ -147,9 +162,28 @@ fn up(v: V3) -> [f64; 3] { /// `faces` (view space) as one mesh, each cut into triangles turned to its normal, which is written /// at unit length whatever length it is given (a face given no normal takes its corners' own). fn mesh(faces: &[Face3]) -> Result { + mesh_on(faces, None).map(|(mesh, _)| mesh) +} + +/// [`mesh`], with for each triangle where its corners lie on a surface: `surface` lists faces by +/// their index in `faces` (in increasing order) with a surface point for each corner of the face's +/// one contour, and a triangle of such a face takes its corners' points. `None` for a triangle of +/// any other face. Without `surface` the list is empty. +fn mesh_on(faces: &[Face3], surface: Option<&[(usize, [Point; 4])]>) -> Result { + let track = surface.is_some(); + let surface = surface.unwrap_or_default(); let mut out = Mesh::default(); + let mut on = vec![]; let mut work = 0usize; - for (contours, normal) in faces { + let mut cells = surface.iter().peekable(); + for (k, (contours, normal)) in faces.iter().enumerate() { + while cells.next_if(|(i, _)| *i < k).is_some() {} + let cell = cells.next_if(|(i, _)| *i == k).map(|(_, uv)| uv); + // The surface point of a corner of a triangle: the point of the face's corner it is. + let point = |v: V3| { + let corners = contours.first()?; + corners.iter().zip(cell?).find(|(c, _)| c.0 == v.0 && c.1 == v.1 && c.2 == v.2).map(|(_, p)| *p) + }; let geometric = newell(contours); let given = normal.unit(); let n = if given.dot(given) > 0.5 { given } else { geometric.unit() }; @@ -157,20 +191,36 @@ fn mesh(faces: &[Face3]) -> Result { continue; } let [nx, ny, nz] = up(n); - for [a, b, c] in triangulate(contours, geometric, &mut work)? { + // A face on the surface is cut along its diagonal from corner 0 to corner 2, as the canvas + // cuts it to place the graphics: the surface's layout of a quad whose ends lie at different + // distances from the axis is not one affine map, so the other diagonal would move them. + let quad = match contours.as_slice() { + [only] if cell.is_some() => <[V3; 4]>::try_from(only.as_slice()).ok(), + _ => None, + }; + let triangles = match quad { + Some([v0, v1, v2, v3]) => vec![[v0, v1, v2], [v0, v2, v3]], + None => triangulate(contours, geometric, &mut work)?, + }; + for [a, b, c] in triangles { let (pa, pb, pc) = (up(a), up(b), up(c)); let cross = V3(pb[0] - pa[0], pb[1] - pa[1], pb[2] - pa[2]).cross(V3(pc[0] - pa[0], pc[1] - pa[1], pc[2] - pa[2])); if cross.dot(cross) < 1e-24 { continue; } - let (pb, pc) = if cross.dot(V3(nx, ny, nz)) < 0.0 { (pc, pb) } else { (pb, pc) }; + let turned = cross.dot(V3(nx, ny, nz)) < 0.0; + let (pb, pc) = if turned { (pc, pb) } else { (pb, pc) }; + let (b, c) = if turned { (c, b) } else { (b, c) }; let base = u32::try_from(out.positions.len()).map_err(|_| "The 3D object is too complex to export".to_string())?; out.positions.extend([pa, pb, pc]); out.normals.extend([[nx, ny, nz]; 3]); out.triangles.push([base, base + 1, base + 2]); + if track { + on.push(point(a).zip(point(b)).zip(point(c)).map(|((a, b), c)| [a, b, c])); + } } } - Ok(out) + Ok((out, on)) } /// A corner of a face: its position on the plane the face is cut in, and in 3D. diff --git a/crates/three-d/src/mesh/tests.rs b/crates/three-d/src/mesh/tests.rs index 8b2ec0ae75..baf5266c76 100644 --- a/crates/three-d/src/mesh/tests.rs +++ b/crates/three-d/src/mesh/tests.rs @@ -255,6 +255,116 @@ fn a_partial_revolve_caps_its_ends_with_sectors_and_closes_its_cut_sides() { assert!(!closed(&hollow)); } +/// A vertical line 40 pt from the axis, from y 10 to 90: an open cylinder of radius 40 about the +/// axis at x 0, its middle height 50. +fn tube() -> (PathData, Rect) { + let mut b = BezPath::new(); + b.move_to((40.0, 10.0)); + b.line_to((40.0, 90.0)); + (PathData::from_bezpath(&b), Rect::new(0.0, 10.0, 40.0, 90.0)) +} + +#[test] +fn a_revolved_sides_corners_lie_where_the_canvas_places_the_unrolled_side() { + let (p, r) = tube(); + let o = Revolve { map_surface: true, ..Revolve::default() }; + let (m, on) = revolve_mesh_surface(&p, FillRule::NonZero, r, o).unwrap(); + assert_eq!(on.len(), m.triangles.len()); + assert_eq!(m.triangles.len(), revolve_mesh(&p, FillRule::NonZero, r, o).unwrap().triangles.len()); + let step = 40.0 * std::f64::consts::TAU / 64.0; + let (mut side, mut caps) = (0, 0); + for (t, points) in m.triangles.iter().zip(&on) { + let c = corners(&m, *t); + let Some(points) = points else { + // The end caps: flat at the top and bottom of the tube. + assert!(c.iter().all(|q| (q[1].abs() - 40.0).abs() < 1e-9), "{c:?}"); + caps += 1; + continue; + }; + side += 1; + for (q, uv) in c.iter().zip(points) { + // y runs down the profile from its middle (the mesh is y up), and x around the axis is + // the angle from the front (90°, toward the viewer), increasing to the viewer's right, + // times the radius. + assert!((uv.y + q[1]).abs() < 1e-9, "{q:?} {uv:?}"); + let turned = std::f64::consts::FRAC_PI_2 - q[2].atan2(q[0]); + let around = (turned + std::f64::consts::PI).rem_euclid(std::f64::consts::TAU) - std::f64::consts::PI; + let seam = (uv.x.abs() - 40.0 * std::f64::consts::PI).abs() < step + 1e-6; + assert!((uv.x - 40.0 * around).abs() < 1e-6 || seam, "{q:?} {uv:?}"); + } + // No triangle reaches across the cut at the back: each spans one step around the axis. + let (lo, hi) = points.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), p| (lo.min(p.x), hi.max(p.x))); + assert!(hi - lo < step + 1e-6, "{points:?}"); + } + assert_eq!((side, caps > 0), (2 * 64, true)); + // The cut is at the back: the side runs half a turn each way from the front. + let xs = on.iter().flatten().flatten().map(|p| p.x); + let (lo, hi) = xs.fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), x| (lo.min(x), hi.max(x))); + assert!((lo + 40.0 * std::f64::consts::PI).abs() < 1e-6 && (hi - 40.0 * std::f64::consts::PI).abs() < 1e-6, "{lo} {hi}"); +} + +#[test] +fn a_revolved_sides_layout_matches_its_drawn_faces_at_every_turn() { + let (p, r) = tube(); + for o in [ + Revolve { map_surface: true, angle: 90.0, ..Revolve::default() }, + Revolve { map_surface: true, angle: 250.0, offset: 15.0, edge: Edge::Right, rotation_x: -20.0, rotation_y: 35.0, ..Revolve::default() }, + ] { + let (m, on) = revolve_mesh_surface(&p, FillRule::NonZero, r, o).unwrap(); + // The drawn faces' surface points, which the canvas places the graphics by. + let drawn: Vec = crate::revolve(&p, r, o).unwrap().iter().filter_map(|f| f.surface.as_ref()).flat_map(|c| c.uv.clone()).collect(); + let near = |q: Point| drawn.iter().any(|d| d.distance(q) < 1e-6); + let points: Vec = on.iter().flatten().flatten().copied().collect(); + assert!(!points.is_empty() && points.iter().all(|q| near(*q)), "{o:?}"); + assert!(drawn.iter().all(|d| points.iter().any(|q| q.distance(*d) < 1e-6)), "{o:?}"); + // The end sectors and the two cut sides carry no surface points. + assert!(on.iter().any(Option::is_none) && on.len() == m.triangles.len()); + } + // Without the layout, no triangle carries one. + let (_, on) = revolve_mesh_surface(&p, FillRule::NonZero, r, Revolve::default()).unwrap(); + assert!(on.iter().all(Option::is_none)); +} + +#[test] +fn a_tapered_sides_triangles_are_the_drawn_faces_triangles() { + // A cone's side: each face's ends lie at different distances from the axis, so its layout on + // the surface is not one affine map, and each triangle must take the corners the canvas cuts + // the face into. + let mut b = BezPath::new(); + b.move_to((10.0, 10.0)); + b.line_to((40.0, 90.0)); + let p = PathData::from_bezpath(&b); + let r = Rect::new(0.0, 10.0, 40.0, 90.0); + let o = Revolve { map_surface: true, ..Revolve::default() }; + let key = |t: &[Point]| { + let mut k: Vec<(i64, i64)> = t.iter().map(|q| ((q.x * 1e6).round() as i64, (q.y * 1e6).round() as i64)).collect(); + k.sort_unstable(); + k + }; + let drawn: Vec<_> = crate::revolve(&p, r, o).unwrap().iter().filter_map(|f| f.surface.as_ref()).map(|c| key(&c.uv)).collect(); + assert!(drawn.iter().all(|k| k.len() == 3), "the canvas draws the smooth side in triangles"); + let (_, on) = revolve_mesh_surface(&p, FillRule::NonZero, r, o).unwrap(); + let side: Vec<_> = on.iter().flatten().collect(); + assert_eq!(side.len(), drawn.len()); + assert!(side.iter().all(|t| drawn.contains(&key(t.as_slice())))); +} + +#[test] +fn only_the_longest_contour_of_a_revolved_profile_lies_on_the_side_surface() { + let mut b = BezPath::new(); + b.move_to((40.0, 10.0)); + b.line_to((40.0, 90.0)); + b.move_to((20.0, 30.0)); + b.line_to((20.0, 50.0)); + let p = PathData::from_bezpath(&b); + let r = Rect::new(0.0, 10.0, 40.0, 90.0); + let (m, on) = revolve_mesh_surface(&p, FillRule::NonZero, r, Revolve { map_surface: true, cap_ends: false, ..Revolve::default() }).unwrap(); + for (t, points) in m.triangles.iter().zip(&on) { + let radius = corners(&m, *t).iter().map(|q| q[0].hypot(q[2])).fold(0.0f64, f64::max); + assert_eq!(points.is_some(), radius > 30.0, "{radius}"); + } +} + #[test] fn a_revolved_surface_has_unit_normals_facing_out_whatever_its_length_and_direction() { // A wall 100 pt tall and one 0.5 pt tall, each drawn up and down the page. diff --git a/crates/three-d/src/shadow.rs b/crates/three-d/src/shadow.rs index 00ae75d169..38d2be50c7 100644 --- a/crates/three-d/src/shadow.rs +++ b/crates/three-d/src/shadow.rs @@ -369,7 +369,7 @@ pub fn inflate_shadowed( /// [`crate::revolve`] gives one. pub fn revolve_shadowed(path: &PathData, bounds: Rect, options: Revolve) -> Result<(Vec, SolidFaces), String> { let mut kept = vec![]; - let (faces, lost) = crate::revolve_sweep(path, options.fill_rule, bounds, options, true, Some(&mut kept))?; + let (faces, lost) = crate::revolve_sweep(path, options.fill_rule, bounds, options, true, Some(&mut kept), None)?; let projection = Some(crate::revolve_projection(bounds, options.sanitized())); Ok((faces, SolidFaces { faces: lost.map_or(Ok(kept), Err), projection })) } diff --git a/docs/mcp.md b/docs/mcp.md index 4c1b661f42..a7c01834ff 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -9134,8 +9134,11 @@ and an MTL `map_Kd`; OBJ and USDA write the PNG beside them as `-texture-1 whose face is not opaque also gets `-texture-1-opacity.png`, the alpha as gray levels, for the MTL's `map_d`. Faces with the same color, graphics and bounds share one texture. `textureSize` (128 to 4096, default 1024, VectorCraft's own values) is the number of pixels along the longer side of each texture; one export -draws at most 67,108,864 texture pixels in all, and past that it is refused. Graphics on Revolve's side are not -exported yet. The layouts follow glTF 2.0, UsdPreviewSurface () +draws at most 67,108,864 texture pixels in all, and past that it is refused. Graphics on Revolve's side are a texture +of the side unrolled as the canvas lays it out (around the axis, the angle times the distance from the axis; along the +profile, its length), on a mesh of the side's triangles; its end caps and cut sides stay plain, and a full turn's +texture is cut at the back, where the canvas cuts the graphics. In a group, the graphics go on the side of the member +with the longest profile. The layouts follow glTF 2.0, UsdPreviewSurface () and OBJ/MTL (). With `zip`, the files go into one ZIP named after the document with `-3D` added (`Untitled-1-3D.zip`), or `3D Assets.zip` when the document's title gives no file name. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ef83de54ad..3b97b97517 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1469,7 +1469,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Extrude & Bevel (both kinds) and Rotate keep the art's curves in the faces they draw, export and expand: caps and the edges of walls and bevels where they meet a cap are cubics with smooth anchors where the art's are, fitted within 0.001 pt in perspective and within the sampling tolerance on a bevel's inset. An edge of a twisted wall that is cut into pieces, a piece of curve that does not fit after 8 halvings, and the curves past 1,048,576 for one solid stay straight (VectorCraft's own values; [three-d.md](three-d.md#what-differs-from-the-public-documentation)). Tests `solid::tests::a_cap_keeps_the_curves_of_the_art`, `a_cap_in_perspective_fits_the_projected_curves`, `a_beveled_cap_and_its_walls_share_their_curves`, `twisted_beveled_tiny_and_degenerate_caps_keep_their_curves`. - Export 3D Object (Asset Export's menu): an object with Extrude & Bevel, Revolve, Inflate or Rotate becomes a 3D asset whose Format is USDA (the default), USDZ, glTF or OBJ, and Export writes each of its solids as a mesh with a material in its paint's color (`assets.add3D`, `assets.set3DFormat`, `assets.export3D`; [export 3D vector artwork](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/export-3d-vector-artwork.html)). - Export 3D Object builds each Extrude & Bevel (both kinds) and Inflate solid once: the same build gives the faces that count toward the object's limit and the faces of its mesh, and the meshes match those of a separate build bit for bit. Tests `mesh::tests::a_meshed_solid_is_built_once`, `an_extruded_solid_and_its_mesh_match_the_two_built_apart`, `inflated_solids_and_their_meshes_match_the_two_built_apart`, `solids::tests_mesh::one_build_exports_the_meshes_built_apart`, `a_stroke_past_the_limits_is_left_out_of_the_export`. - - Export 3D Object writes the graphics mapped onto a plane or onto Extrude & Bevel's front and back caps as a PNG texture of each face, the face's color with its graphics drawn flat and unlit over it, on a mesh of that face with texture coordinates, in all four formats (glTF embeds it, USDZ packs it after the layer, OBJ and USDA write `-texture-1.png` beside them; `assets.export3D` `textureSize`, 128 to 4096 pixels, default 1024, VectorCraft's own values; [the help page](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/map-artwork-on-3d-objects.html)). Graphics on Revolve's side, materials and lighting are not exported. Tests `a_caps_mesh_corners_go_back_to_the_art_they_were_made_from`, `a_mesh_carries_its_caps_graphics_flat_in_the_arts_plane`, `each_format_carries_a_textured_part_with_its_coordinates_and_picture`, `export_3d_paints_mapped_graphics_on_their_caps_in_every_format`. + - Export 3D Object writes the graphics mapped onto a plane or onto Extrude & Bevel's front and back caps as a PNG texture of each face, the face's color with its graphics drawn flat and unlit over it, on a mesh of that face with texture coordinates, in all four formats (glTF embeds it, USDZ packs it after the layer, OBJ and USDA write `-texture-1.png` beside them; `assets.export3D` `textureSize`, 128 to 4096 pixels, default 1024, VectorCraft's own values; [the help page](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/map-artwork-on-3d-objects.html)). The graphics wrapped around Revolve's side export the same way, as a texture of the side unrolled as the canvas lays it out, on a mesh of the side's triangles, with its end caps and cut sides plain. Materials and lighting are not exported. Tests `a_caps_mesh_corners_go_back_to_the_art_they_were_made_from`, `a_mesh_carries_its_caps_graphics_flat_in_the_arts_plane`, `each_format_carries_a_textured_part_with_its_coordinates_and_picture`, `export_3d_paints_mapped_graphics_on_their_caps_in_every_format`, `a_revolved_sides_corners_lie_where_the_canvas_places_the_unrolled_side`, `a_revolved_sides_layout_matches_its_drawn_faces_at_every_turn`, `export_3d_paints_graphics_mapped_onto_a_revolves_side_in_every_format`, `a_partial_revolve_keeps_its_cut_sides_plain_beside_its_textured_side`. - Checking an Extrude & Bevel (both kinds) or Inflate effect builds each solid the effect draws once, about the bounds the effect draws it about; a shape with no fill still has its profile built on its own. Tests `solids::tests::the_check_builds_each_drawn_solid_once`, `the_check_builds_the_profile_of_a_shape_with_no_fill`. - Initial live Revolve (#605, #846): a portable geometry and shading crate (`three-d`), editable path and compound profiles, compact options with artboard rotation and light gizmos, SVG/PDF vector output and Expand Appearance that can trim covered faces. Open ends have continuous caps by default, shading is smooth with one to ten colored lights, and intersecting surfaces' visibility is approximate ([revolve.md](revolve.md)). - Revolve takes graphics on its swept side, shaded with the object's light ([the archived reference, page 185](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=185)). By VectorCraft's own rule a graphic wraps around the axis at its own size at every distance from it, narrows toward the silhouette, follows the profile along its length and is hidden where the side faces away (`threeD.mapGraphic`; `revolve::tests_graphics`, `tests::side_faces_lie_on_the_unrolled_surface_and_caps_do_not`, `map_graphic_puts_a_graphic_on_the_side_of_a_revolve`).