diff --git a/crates/effects/src/catalog.rs b/crates/effects/src/catalog.rs index 568aa583b1..8e45364857 100644 --- a/crates/effects/src/catalog.rs +++ b/crates/effects/src/catalog.rs @@ -210,15 +210,15 @@ pub fn effect_catalog() -> Vec { CLASSIC_EXTRUDE, "Extrude & Bevel (Classic)…", &["Effect", "3D and Materials", "3D (Classic)"], - "{depth: pt (0..2000, 50), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelHeight: pt (1..100, 4; the bevel is as wide as it is tall), bevelInside: bool (false: added around the shape; true: carved into it), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face, hidden ones included, and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none|blackOverprint (black; the color the faces darken toward; none keeps the paint and adds only the highlight; blackOverprint keeps the paint and draws the shading over it as overprinting black, on the black plate, with no highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, lighter where the highlight is, with black multiplied and overprinting where the faces darken, so a spot color keeps its plate; it does nothing while shadingColor is custom, and with blackOverprint every face keeps its paint and swatch link whether it is on or off), drawHiddenFaces: bool (false; also draws the faces turned away, behind the others)}. The front face is the art, extruded backwards about the center of its bounds; a solid is built for the top fill and for each stroke, each in its own paint. The defaults are VectorCraft's own.", - json!({"depth":50.0,"cap":true,"bevel":"none","bevelHeight":4.0,"bevelInside":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"surface":"plastic","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":100.0,"ambient":50.0,"highlightIntensity":60.0,"highlightSize":90.0,"blendSteps":25,"shadingColor":"black","shadingCustom":"#000000","preserveSpotColors":false,"drawHiddenFaces":false}), + "{depth: pt (0..2000, 50), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelHeight: pt (1..100, 4; the bevel is as wide as it is tall), bevelInside: bool (false: added around the shape; true: carved into it), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face, hidden ones included, and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none|blackOverprint (black; the color the faces darken toward; none keeps the paint and adds only the highlight; blackOverprint keeps the paint and draws the shading over it as overprinting black, on the black plate, with no highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, lighter where the highlight is, with black multiplied and overprinting where the faces darken, so a spot color keeps its plate; it does nothing while shadingColor is custom, and with blackOverprint every face keeps its paint and swatch link whether it is on or off), drawHiddenFaces: bool (false; also draws the faces turned away, behind the others), mapArt: array of 0..64 objects ([]; Map Art, see threeD.mapArt: surface: integer (1..100000; the numbered surface, one map for a surface), symbol: name of a document symbol, x: pt (-1000000..1000000, 0; the offset of the art's center from the center of the surface laid out flat), y: pt (-1000000..1000000, 0), scaleX: % (1..10000, 100; of the symbol's own width), scaleY: % (1..10000, 100), rotation: degrees (-360..360, 0; counterclockwise); the surfaces are numbered through the object's solids in the order they are built: each solid's front cap and back cap (none on a hollow solid, cap false), then each side wall from corner to corner of the outline, then the bevel above each wall; a map past the object's surfaces draws nothing; wireframe draws no mapped art), mapShade: bool (false; Shade Artwork: the mapped art takes the tone and highlight of its face), mapInvisible: bool (false; Invisible Geometry: with at least one map, only the mapped art is drawn)}. The front face is the art, extruded backwards about the center of its bounds; a solid is built for the top fill and for each stroke, each in its own paint. The defaults, the surface numbering and the limits are VectorCraft's own.", + json!({"depth":50.0,"cap":true,"bevel":"none","bevelHeight":4.0,"bevelInside":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"surface":"plastic","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":100.0,"ambient":50.0,"highlightIntensity":60.0,"highlightSize":90.0,"blendSteps":25,"shadingColor":"black","shadingCustom":"#000000","preserveSpotColors":false,"drawHiddenFaces":false,"mapArt":[],"mapShade":false,"mapInvisible":false}), ), g( CLASSIC_REVOLVE, "Revolve (Classic)…", &["Effect", "3D and Materials", "3D (Classic)"], - "{angle: degrees (0..360, 360; how far the profile sweeps round the axis), cap: bool (true: solid, the open ends and a partial sweep's cut sides closed; false: hollow), offset: pt (0..1000, 0; the axis's distance from the profile, a ring past 0), edge: left|right (left; the axis is at the left or the right edge of the profile's bounds), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none|blackOverprint (black; the color the faces darken toward; none keeps the paint and adds only the highlight; blackOverprint keeps the paint and draws the shading over it as overprinting black, on the black plate, with no highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, lighter where the highlight is, with black multiplied and overprinting where the faces darken, so a spot color keeps its plate; it does nothing while shadingColor is custom, and with blackOverprint every face keeps its paint and swatch link whether it is on or off)}. The profile sweeps round a vertical axis, as Revolve's does, painted with the top fill (else the top stroke); every face is drawn, back to front. The defaults are VectorCraft's own.", - json!({"angle":360.0,"cap":true,"offset":0.0,"edge":"left","rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"surface":"plastic","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":100.0,"ambient":50.0,"highlightIntensity":60.0,"highlightSize":90.0,"blendSteps":25,"shadingColor":"black","shadingCustom":"#000000","preserveSpotColors":false}), + "{angle: degrees (0..360, 360; how far the profile sweeps round the axis), cap: bool (true: solid, the open ends and a partial sweep's cut sides closed; false: hollow), offset: pt (0..1000, 0; the axis's distance from the profile, a ring past 0), edge: left|right (left; the axis is at the left or the right edge of the profile's bounds), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none|blackOverprint (black; the color the faces darken toward; none keeps the paint and adds only the highlight; blackOverprint keeps the paint and draws the shading over it as overprinting black, on the black plate, with no highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, lighter where the highlight is, with black multiplied and overprinting where the faces darken, so a spot color keeps its plate; it does nothing while shadingColor is custom, and with blackOverprint every face keeps its paint and swatch link whether it is on or off), mapArt: array of 0..64 objects ([]; Map Art, see threeD.mapArt: surface: integer (the swept side is surface 1, the only one; in a group, the side of the member with the longest profile; a map of another surface draws nothing), symbol: name of a document symbol, x: pt (-1000000..1000000, 0; the offset of the art's center from the middle of the side unrolled flat, around the axis), y: pt (-1000000..1000000, 0; along the profile), scaleX: % (1..10000, 100; of the symbol's own width), scaleY: % (1..10000, 100), rotation: degrees (-360..360, 0; counterclockwise); the art wraps around the side and is drawn where its outside faces the viewer; wireframe draws no mapped art), mapShade: bool (false; Shade Artwork: the mapped art takes the tone and highlight of its face), mapInvisible: bool (false; Invisible Geometry: with at least one map, only the mapped art is drawn)}. The profile sweeps round a vertical axis, as Revolve's does, painted with the top fill (else the top stroke); every face is drawn, back to front. The defaults, the surface numbering and the limits are VectorCraft's own.", + json!({"angle":360.0,"cap":true,"offset":0.0,"edge":"left","rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"surface":"plastic","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":100.0,"ambient":50.0,"highlightIntensity":60.0,"highlightSize":90.0,"blendSteps":25,"shadingColor":"black","shadingCustom":"#000000","preserveSpotColors":false,"mapArt":[],"mapShade":false,"mapInvisible":false}), ), g( CLASSIC_ROTATE, diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index 7eec83c7f5..4f2a32aa10 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -106,6 +106,10 @@ pub use solids::{ GRAPHIC_MAX_OFFSET, GRAPHIC_SCALE_RANGE, GRAPHICS_NOT_TAKEN, appearance_graphic_symbols, exports_three_d, graphic_fitting_scale, graphic_frame_at, graphic_side_size, graphics_reshaped_after, rename_appearance_graphic_symbol, }; +pub use solids::{ + MAP_ART, MAP_ART_NOT_TAKEN, MAP_INVISIBLE, MAP_SHADE, MAX_MAP_SURFACE, MAX_MAPS, MapSurface, SurfaceKind, SurfaceMap, map_surfaces_at, + map_surfaces_with, surface_maps, takes_map_art, with_surface_map, +}; pub use stylize::{ScribbleSetting, scribble_setting_id, scribble_settings}; pub use svg_filter::SVG_FILTER; pub use trap::TRAP; diff --git a/crates/effects/src/revolve.rs b/crates/effects/src/revolve.rs index 43e60a0022..75f60c894e 100644 --- a/crates/effects/src/revolve.rs +++ b/crates/effects/src/revolve.rs @@ -113,7 +113,7 @@ pub fn revolve_options(p: &Value) -> Revolve { /// The options Revolve (`id` [`REVOLVE`]) or Revolve (Classic) ([`CLASSIC_REVOLVE`]) with /// parameters `p` sweeps its surface with. A Revolve with graphics lays out its side for them. -fn options_of(id: &str, p: &Value) -> Revolve { +pub(crate) fn options_of(id: &str, p: &Value) -> Revolve { if id == CLASSIC_REVOLVE { classic::options(p) } else { @@ -141,6 +141,7 @@ pub fn validate_revolve_in(doc: Option<&Document>, n: &Node, p: &Value) -> Resul /// [`validate_revolve_in`] for Revolve or Revolve (Classic), `id`. pub(crate) fn validate_in(doc: Option<&Document>, n: &Node, id: &str, p: &Value) -> Result<(), String> { validate_params_of(id, p)?; + validate_map_symbols(doc, id, p)?; let n = &*resolve_for(doc, n, "Revolve", false)?; let effects = &n.appearance.effects; // The profile is measured before the object's one Revolve, hidden or shown. @@ -215,7 +216,7 @@ fn check_graphics(doc: Option<&Document>, id: &str, path: &PathData, b: Rect, op /// The member of a group whose side takes the group's graphics: the first with the longest /// profile among those with a fill or stroke. -fn graphics_member(shapes: &[Profile], b: Rect, options: Revolve) -> Option { +pub(crate) fn graphics_member(shapes: &[Profile], b: Rect, options: Revolve) -> Option { shapes .iter() .enumerate() @@ -237,6 +238,15 @@ fn check_shadow<'a>(p: &Value, paths: impl IntoIterator, b: /// [`validate_revolve`] for a Revolve with parameters `p` at index `index` of the effects of /// appearance item `target` of `n` ([`validate_item_of`]). +/// An error when the symbols that Revolve (Classic)'s Map Art in `p` places, with the symbols of +/// `doc`, are past the limits of a graphic's art, as on Extrude & Bevel (Classic). +fn validate_map_symbols(doc: Option<&Document>, id: &str, p: &Value) -> Result<(), String> { + match doc.filter(|_| id == CLASSIC_REVOLVE) { + Some(doc) => crate::solids::graphics::validate_symbols(doc, p), + None => Ok(()), + } +} + #[cfg(test)] pub(crate) fn validate_item_revolve(n: &Node, p: &Value, target: usize, index: usize) -> Result<(), String> { validate_item_of(None, n, REVOLVE, p, target, index) @@ -252,6 +262,7 @@ pub(crate) fn validate_item_of(doc: Option<&Document>, n: &Node, id: &str, p: &V return validate_in(doc, n, id, p); } validate_params_of(id, p)?; + validate_map_symbols(doc, id, p)?; const EMPTY: &str = "Revolve requires a shape with at least two anchors"; let (path, _) = object_profile(n, "Revolve")?; if !has_two_anchors(&path) { @@ -463,10 +474,12 @@ fn group_shadow( /// with its classic surface, as Extrude & Bevel (Classic) does. Revolve's graphics, with the /// symbols of `doc`, are drawn on the faces of the side ([`crate::solids::graphics::surface_parts`]): /// a face with a part of a graphic is a group of the face and that part. With `cast`, the sweep -/// that draws the surface also keeps the faces its shadow is cast from ([`SolidFaces`]). The last -/// value is whether the faces go over an underlay of themselves ([`seals`]): the caller seals them -/// ([`sealed_surface`], [`sealed_runs`]) in the order it draws them. -#[allow(clippy::too_many_arguments)] +/// that draws the surface also keeps the faces its shadow is cast from ([`SolidFaces`]). With +/// `hide`, a Revolve (Classic) surface without mapped art leaves its faces out, as Invisible +/// Geometry does ([`crate::solids::classic::surface`]). The last two values are whether the faces +/// go over an underlay of themselves ([`seals`]): the caller seals them ([`sealed_surface`], +/// [`sealed_runs`]) in the order it draws them; and whether the faces were left out. +#[allow(clippy::too_many_arguments, clippy::type_complexity)] fn surface( doc: Option<&Document>, n: &Node, @@ -480,7 +493,8 @@ fn surface( expand: bool, copies: &mut Copies, cast: bool, -) -> Option<(Vec, Node, Option, bool)> { + hide: bool, +) -> Option<(Vec, Node, Option, bool, bool)> { #[cfg(test)] crate::solids::SOLIDS_BUILT.with(|n| n.set(n.get() + 1)); // A loaded file or a profile edited past the limits keeps drawing its source path instead @@ -500,7 +514,23 @@ fn surface( let drawn = facets.iter().map(|f| Drawn { depth: f.depth, points: f.contours.first().cloned().unwrap_or_default(), plane: f.plane }).collect(); let p = merged_params(&fx.id, &fx.params); - return Some((drawn, crate::solids::classic::surface(n, facets, &paint, opacity, blend, &p), kept, false)); + // Mapped art goes on the side, the surface's one numbered surface. Its paints' copies + // count with the graphics', and art past the limits is left out. + let map_art = crate::solids::graphics::map_art::MapArt::of(doc, &fx.id, &p); + let layout = map_art.as_ref().and_then(|_| { + let (width, height) = vectorcraft_three_d::revolve_surface_size(path, b, options)?; + let side = vectorcraft_three_d::SolidSurface { kind: vectorcraft_three_d::SurfaceKind::Side, width, height, center: None }; + Some(crate::solids::graphics::map_art::SolidLayout { first: 0, surfaces: vec![side], ends: None }) + }); + let mut budget = crate::solids::graphics::map_art::MapBudget::default(); + let mapped = map_art.as_ref().zip(layout.as_ref()).map(|(art, layout)| crate::solids::classic::Mapped { + art, + layout, + budget: &mut budget, + copies: &mut copies.graphics, + }); + let (art, hidden) = crate::solids::classic::surface(n, facets, &paint, (opacity, blend), &p, mapped, hide); + return Some((drawn, art, kept, false, hidden)); } let colored = colored(&options); let (faces, kept) = if cast { @@ -632,7 +662,7 @@ fn surface( let mut group = Node::group(n.id, children); group.opacity = opacity; group.blend = blend; - Some((keys, group, kept, seal)) + Some((keys, group, kept, seal, false)) } /// Plain `surface` ([`surface`]: a group of its faces) over an underlay of its faces when `seal` @@ -722,8 +752,8 @@ fn object_surface( let b = path.bounds()?; let (paint, opacity, blend) = paint_of(item); let cast = casts(fx, opacity); - surface(doc, n, path, b, rule_options(fx, rule), fx, paint, opacity, blend, expand, copies, cast) - .map(|(_, art, kept, seal)| (sealed_surface(n.id, art, seal), kept)) + surface(doc, n, path, b, rule_options(fx, rule), fx, paint, opacity, blend, expand, copies, cast, false) + .map(|(_, art, kept, seal, _)| (sealed_surface(n.id, art, seal), kept)) } /// The options effect `fx` sweeps the surface of a profile filled with `rule` with: its cut sides @@ -1155,22 +1185,42 @@ fn group_art(doc: Option<&Document>, n: &Node, expand: bool) -> Option { let mut opaque = true; // The graphics go once, on the side of the member with the longest profile. Without graphics // no member is measured for them. - let mapped = fx.id == REVOLVE && !crate::solids::mapped_graphics(&merged_params(&fx.id, &fx.params)).is_empty(); + // Revolve (Classic)'s mapped art goes on that member's side too. + let p = merged_params(&fx.id, &fx.params); + let mapped = (fx.id == REVOLVE && !crate::solids::mapped_graphics(&p).is_empty()) + || (fx.id == CLASSIC_REVOLVE && !crate::solids::surface_maps(&p).is_empty()); let longest = if mapped { graphics_member(&shapes, b, options) } else { None }; - for (k, s) in shapes.iter().enumerate() { - let Some(item) = surface_item(&s.items) else { - kept.push(None); - continue; - }; + // Member `k`'s surface, its faces left out with `hide`, with its opacity and blending mode; + // `None` for a member with no fill or stroke. + let member = |k: usize, s: &Profile, hide: bool, copies: &mut Copies| { + let item = surface_item(&s.items)?; // The opacity and blending of the member and the groups it is in apply through its scopes. let (paint, opacity, blend) = paint_of(item); - opaque &= opacity >= 1.0 && blend == Default::default() && s.scopes.is_empty(); // A member with transparency of its own keeps every face, as a transparent object does. let expand = expand && s.scopes.is_empty(); let doc = doc.filter(|_| longest == Some(k)); let cast = casts(fx, opacity * s.opacity); let options = Revolve { fill_rule: s.rule, ..options }; - let (depths, art, faces, seal) = surface(doc, n, &s.path, b, options, fx, paint, opacity, blend, expand, &mut copies, cast)?; + Some((opacity, blend, surface(doc, n, &s.path, b, options, fx, paint, opacity, blend, expand, copies, cast, hide))) + }; + // With Invisible Geometry the other members leave their faces out too, once the mapped art on + // the longest member's side has left that member's faces out, so it is built first. + let invisible = fx.id == CLASSIC_REVOLVE && doc.is_some() && p.get(crate::solids::MAP_INVISIBLE).and_then(Value::as_bool).unwrap_or(false); + let mut first = None; + if let Some(l) = longest.filter(|_| invisible) + && let Some(s) = shapes.get(l) + { + first = member(l, s, false, &mut copies); + } + let hide = matches!(first, Some((_, _, Some((_, _, _, _, true))))); + for (k, s) in shapes.iter().enumerate() { + let built = if longest == Some(k) && first.is_some() { first.take() } else { member(k, s, hide, &mut copies) }; + let Some((opacity, blend, built)) = built else { + kept.push(None); + continue; + }; + opaque &= opacity >= 1.0 && blend == Default::default() && s.scopes.is_empty(); + let (depths, art, faces, seal, _) = built?; surfaces.push((depths, art, s.scopes.as_slice())); kept.push(faces); seals.push(seal); @@ -1870,8 +1920,9 @@ mod tests { let path = n.path_data().unwrap(); let fx = n.appearance.effects.first().unwrap(); let (paint, opacity, blend) = paint_of(n.appearance.items.first().unwrap()); - let (_, art, _, seal) = - surface(None, n, path, path.bounds().unwrap(), fx_options(fx), fx, paint, opacity, blend, false, &mut Copies::default(), false).unwrap(); + let (_, art, _, seal, _) = + surface(None, n, path, path.bounds().unwrap(), fx_options(fx), fx, paint, opacity, blend, false, &mut Copies::default(), false, false) + .unwrap(); (art, seal) } @@ -2129,7 +2180,7 @@ mod tests { .map(|s| { let (paint, opacity, blend) = paint_of(surface_item(&s.items).unwrap()); let cast = casts(&fx, opacity * s.opacity); - surface(None, &g, &s.path, b, options, &fx, paint, opacity, blend, false, &mut Copies::default(), cast).unwrap().2 + surface(None, &g, &s.path, b, options, &fx, paint, opacity, blend, false, &mut Copies::default(), cast, false).unwrap().2 }) .collect(); assert!(kept.iter().all(Option::is_some), "{id} {params}"); @@ -2165,7 +2216,7 @@ mod tests { .map(|s| { let (paint, opacity, blend) = paint_of(surface_item(&s.items).unwrap()); let cast = casts(&fx, opacity * s.opacity); - surface(None, g, &s.path, b, options, &fx, paint, opacity, blend, false, &mut Copies::default(), cast).unwrap().2 + surface(None, g, &s.path, b, options, &fx, paint, opacity, blend, false, &mut Copies::default(), cast, false).unwrap().2 }) .collect(); [group_shadow(g.id, &fx, &shapes, b, options, kept).unwrap(), group_shadow(g.id, &fx, &shapes, b, options, vec![]).unwrap()] diff --git a/crates/effects/src/revolve/classic.rs b/crates/effects/src/revolve/classic.rs index 4aefb13eef..97bfa67add 100644 --- a/crates/effects/src/revolve/classic.rs +++ b/crates/effects/src/revolve/classic.rs @@ -4,6 +4,8 @@ use serde_json::Value; use vectorcraft_three_d::Revolve; +use crate::solids::graphics::map_art; + pub const CLASSIC_REVOLVE: &str = "threeD.classicRevolve"; /// The numeric parameters: (key, lowest, highest, whole numbers only). @@ -23,19 +25,28 @@ const RANGES: [(&str, f64, f64, bool); 13] = [ ("blendSteps", 1.0, 256.0, true), ]; -const FLAGS: [&str; 3] = ["cap", "lightBehind", "preserveSpotColors"]; +const FLAGS: [&str; 5] = ["cap", "lightBehind", "preserveSpotColors", map_art::MAP_SHADE, map_art::MAP_INVISIBLE]; /// The surface Revolve (Classic)'s parameters `p` sweep: Revolve's angle, cap, offset, edge, -/// rotation and perspective, built unshaded, since the classic surfaces light its faces. +/// rotation and perspective, built unshaded, since the classic surfaces light its faces. With +/// mapped art its side is laid out for it. pub(crate) fn options(p: &Value) -> Revolve { - Revolve { shade: false, smooth_shading: false, lights: None, light_color: [1.0; 3], ..super::revolve_options(p) } + Revolve { + shade: false, + smooth_shading: false, + lights: None, + light_color: [1.0; 3], + map_surface: !map_art::surface_maps(p).is_empty(), + ..super::revolve_options(p) + } } /// Check Revolve (Classic)'s parameters `p` (its defaults filled in) beyond the checks it shares /// with Revolve: every key is one of its parameters, numbers are in range, flags are true or false, -/// and the surface and shading color are named. +/// the surface and shading color are named, and `mapArt` holds valid maps. pub(crate) fn validate(p: &Value) -> Result<(), String> { - crate::solids::classic::validate_classic(CLASSIC_REVOLVE, p, &RANGES, &FLAGS) + crate::solids::classic::validate_classic(CLASSIC_REVOLVE, p, &RANGES, &FLAGS)?; + map_art::validate(CLASSIC_REVOLVE, p) } #[cfg(test)] diff --git a/crates/effects/src/solids.rs b/crates/effects/src/solids.rs index 2bda4dc126..8c66f95573 100644 --- a/crates/effects/src/solids.rs +++ b/crates/effects/src/solids.rs @@ -24,6 +24,10 @@ mod source; pub(crate) use source::{resolve, resolve_for}; pub(crate) mod graphics; +pub use graphics::map_art::{ + MAP_ART, MAP_ART_NOT_TAKEN, MAP_INVISIBLE, MAP_SHADE, MAX_MAP_SURFACE, MAX_MAPS, SurfaceMap, surface_maps, takes_map_art, with_surface_map, +}; +use graphics::map_art::{MapArt, MapBudget, SolidLayout}; pub use graphics::{ GRAPHICS, GraphicFrame, MAX_GRAPHICS, MappedGraphic, MeshGraphics, graphic_symbols, mapped_graphics, mesh_graphics_art, missing_symbol, names_graphic_symbol, rename_graphic_symbol, rename_graphic_symbol_in, takes_graphics, with_graphic, @@ -32,6 +36,7 @@ pub use graphics::{ MAX_OFFSET as GRAPHIC_MAX_OFFSET, NOT_TAKEN as GRAPHICS_NOT_TAKEN, SCALE_RANGE as GRAPHIC_SCALE_RANGE, appearance_graphic_symbols, fitting as graphic_fitting_scale, rename_appearance_graphic_symbol, }; +pub use vectorcraft_three_d::SurfaceKind; pub(crate) mod shadow; @@ -180,6 +185,7 @@ pub fn extrude_options(p: &Value) -> Extrude { both_sides: flag(p, "bevelBothSides", false), }), hidden: false, + map_surfaces: false, map_surface: false, } } @@ -1924,8 +1930,11 @@ fn surfaces_with(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profil filled.push(Filled { at: out.len(), member, caps, opacity, blend, masked: masks_surface(&paint, colored) }); } } - let art = - if classic { classic::surface(n, f, &paint, opacity, blend, &p) } else { surface(n, f, &paint, opacity, blend, colored, false) }; + let art = if classic { + classic::surface(n, f, &paint, (opacity, blend), &p, None, false).0 + } else { + surface(n, f, &paint, opacity, blend, colored, false) + }; out.push((s.scopes.as_slice(), Arc::new(art))); } } @@ -1939,15 +1948,28 @@ fn surfaces_with(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profil let carrier = if graphics_on { side_carrier(&fx.id, &p, &parts, bounds) } else { None }; let mut solids = vec![]; let mut built = vec![]; + // With mapped art, each solid's place among the object's numbered surfaces: the surfaces are + // counted through the parts in order, those of a part whose solid is left out too. + let map_art = MapArt::of(doc, &fx.id, &p).filter(|_| fx.id == CLASSIC_EXTRUDE); + let mut layouts: Vec = vec![]; + let mut surfaces_before = 0usize; let made = built_solids_cast(&fx.id, &p, &parts, bounds, MAX_OBJECT_FACES, cast, carrier); - for (k, ((item, opacity, _, _, scopes, member), f)) in parts.iter().zip(made).enumerate() { + for (k, ((item, opacity, area, rule, scopes, member), f)) in parts.iter().zip(made).enumerate() { let item: &AppearanceItem = item; + let layout = map_art.as_ref().map(|_| { + let options = classic_extrude_options(&p); + let surfaces = vectorcraft_three_d::extrude_surfaces(area, *rule, bounds, options).unwrap_or_default(); + let first = surfaces_before; + surfaces_before += surfaces.len(); + SolidLayout { first, surfaces, ends: Some((bounds, options, view_options(&p))) } + }); match f { Ok(Some((f, _))) if !crate::revolve::paint_copies_add(&mut paint_bytes, facet_copies(&f, paint_ref(item), colored), paint_ref(item)) => { return None; } Ok(Some((f, faces))) => { solids.push((item, *opacity, *scopes, f, *member)); + layouts.extend(layout); built.push(faces); } // A stroke's outline past the limits is left out; the fill's solid still draws, and @@ -2035,6 +2057,7 @@ fn surfaces_with(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profil let split = split && solids.iter().filter(|(item, _, _, f, _)| composite(item, f)).map(|(.., f, _)| f.len()).sum::() <= MAX_FACE_COMPOSITES; let members: Vec = solids.iter().map(|s| s.4).collect(); + let mut map_budget = MapBudget::default(); // Which surfaces lie over an underlay of their facets, in one order or whole // ([`in_one_order`], [`underlaid_surface`]). let seals: Vec = solids.iter().map(|(.., f, _)| underlaid(f, colored)).collect(); @@ -2044,7 +2067,8 @@ fn surfaces_with(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profil let mut graphic_copies = 0usize; let surfaces: Vec = solids .into_iter() - .map(|(item, member, scopes, f, shape)| { + .enumerate() + .map(|(k, (item, member, scopes, f, shape))| { let paints = Paints::of(item, closed(shape)); let depths: Vec = f.iter().map(|f| Placed::of(f, shape, paints)).collect(); let ends = f.iter().map(|f| f.end.filter(|_| !f.away)).collect(); @@ -2061,7 +2085,13 @@ fn surfaces_with(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profil }; let drawn = parts.iter().any(|p| !p.is_empty()); let art = if classic { - classic::surface(n, f, &paint, opacity, blend, &p) + let mapped = map_art.as_ref().zip(layouts.get(k)).map(|(art, layout)| classic::Mapped { + art, + layout, + budget: &mut map_budget, + copies: &mut paint_bytes, + }); + classic::surface(n, f, &paint, (opacity, blend), &p, mapped, false).0 } else { let faces = drawn || (split && shared.get(shape).copied().unwrap_or(false)); with_side_parts(n.id, surface(n, f, &paint, opacity, blend, colored, faces), parts) @@ -2391,28 +2421,7 @@ pub fn graphic_side_size(doc: Option<&Document>, n: &Node, item: Option, /// The 3D effect `pick` finds in the effects of `n` or its `item`, and the shapes it builds from. fn frame_shapes(doc: Option<&Document>, n: &Node, item: Option, pick: &Pick<'_>) -> Option<(Effect, Vec)> { let n = &*resolve(doc, n, "").ok()?; - let (fx, shapes) = if is_container(n) { - let (index, fx) = pick(&n.appearance.effects).filter(|_| item.is_none())?; - let mut shapes = members(n, "").ok()?; - reshape_members(n, n.appearance.effects.get(..index)?, &mut shapes); - (fx, shapes) - } else { - let (path, rule) = profile(n)?; - let ctx = GeomContext::of(n); - match item { - None => { - let (index, fx) = pick(&n.appearance.effects)?; - let path = geometry(&path, n.appearance.effects.get(..index)?, &ctx); - (fx, vec![Profile { path, rule, items: solid_paints(n), opacity: 1.0, scopes: vec![] }]) - } - Some(k) => { - let it = n.appearance.items.get(k)?; - let (index, fx) = pick(it.effects())?; - let path = geometry(&geometry(&path, &n.appearance.effects, &ctx), it.effects().get(..index)?, &ctx.item(it)); - (fx, vec![Profile { path, rule, items: vec![it.clone()], opacity: 1.0, scopes: vec![] }]) - } - } - }; + let (fx, shapes) = picked(n, item, pick)?; Some((fx.clone(), shapes)) } @@ -2459,6 +2468,165 @@ fn frame_of(doc: Option<&Document>, n: &Node, item: Option, pick: &Pick<' }) } +/// One numbered surface of a 3D object that takes Map Art: what it is, its size laid out flat in +/// points, whether the viewer sees any of it, and the edges of its outline on the page. +#[derive(Clone, Debug, PartialEq)] +pub struct MapSurface { + pub kind: SurfaceKind, + pub width: f64, + pub height: f64, + pub visible: bool, + pub outline: Vec<[Point; 2]>, +} + +/// The numbered surfaces of the 3D effect at `index` of the effects of `n` (on the object itself +/// with `item` `None`, else on its fill or stroke `item`), which must be an Extrude & Bevel +/// (Classic) or Revolve (Classic), shown or hidden, in the order Map Art numbers them from 1. +/// `None` for any other effect, and when the object's art can't be built. +pub fn map_surfaces_at(doc: Option<&Document>, n: &Node, item: Option, index: usize) -> Option> { + let n = &*resolve(doc, n, "").ok()?; + let (fx, shapes) = picked(n, item, &|fx: &[Effect]| fx.get(index).filter(|e| takes_map_art(&e.id)).map(|e| (index, e)))?; + let p = crate::merged_params(&fx.id, &fx.params); + let b = union_bounds(&shapes)?; + // The edges of `facets` on each local surface of `surfaces`, in one pass over the facets: every + // edge of an end, and the edges of the cells that lie along the sides of the flat surface. + let seen = |surfaces: &[vectorcraft_three_d::SolidSurface], facets: &[Facet]| -> Vec> { + let mut edges: Vec> = vec![vec![]; surfaces.len()]; + // Each surface laid out flat, and how near a point must be to its side to lie along it. + let frames: Vec<(Rect, f64)> = surfaces + .iter() + .map(|s| { + let flat = match s.kind { + SurfaceKind::Side => Rect::new(-s.width / 2.0, -s.height / 2.0, s.width / 2.0, s.height / 2.0), + _ => Rect::new(0.0, 0.0, s.width, s.height), + }; + (flat, (s.width.max(s.height) * 1e-6).max(1e-9)) + }) + .collect(); + let ends: Vec<(usize, PlanarFace)> = surfaces + .iter() + .enumerate() + .filter_map(|(k, s)| match s.kind { + SurfaceKind::End(end) => Some((k, end)), + _ => None, + }) + .collect(); + for f in facets.iter().filter(|f| !f.away) { + if let Some(at) = f.end { + for &(k, end) in &ends { + if end == at + && let Some(out) = edges.get_mut(k) + { + for c in &f.contours { + out.extend(c.iter().zip(c.iter().cycle().skip(1)).take(c.len()).map(|(a, b)| [*a, *b])); + } + } + } + } + let Some(cell) = f.cell.as_deref().filter(|c| c.uv.len() == c.page.len()) else { continue }; + let k = cell.surface; + // A facet of an end adds to an end's surface only its own edges, above. + if f.end.is_some() && surfaces.get(k).is_some_and(|s| matches!(s.kind, SurfaceKind::End(_))) { + continue; + } + let (Some(&(flat, near)), Some(out)) = (frames.get(k), edges.get_mut(k)) else { continue }; + let count = cell.uv.len(); + for i in 0..count { + let j = (i + 1) % count; + let (Some(a), Some(c)) = (cell.uv.get(i), cell.uv.get(j)) else { continue }; + let along = |at: f64, of: fn(&Point) -> f64| (of(a) - at).abs() <= near && (of(c) - at).abs() <= near; + let on_side = along(flat.x0, |p| p.x) || along(flat.x1, |p| p.x) || along(flat.y0, |p| p.y) || along(flat.y1, |p| p.y); + if let (true, Some(from), Some(to)) = (on_side, cell.page.get(i), cell.page.get(j)) { + out.push([*from, *to]); + } + } + } + edges + }; + let listed = |surfaces: &[vectorcraft_three_d::SolidSurface], facets: &[Facet], out: &mut Vec| { + for (s, outline) in surfaces.iter().zip(seen(surfaces, facets)) { + out.push(MapSurface { kind: s.kind, width: s.width, height: s.height, visible: !outline.is_empty(), outline }); + } + }; + let mut out = vec![]; + if fx.id == crate::CLASSIC_REVOLVE { + // Revolve (Classic) has one surface: its side, in a group that of the member with the + // longest profile. + let options = vectorcraft_three_d::Revolve { map_surface: true, ..crate::revolve::options_of(&fx.id, &p) }; + let shape = shapes.get(crate::revolve::graphics_member(&shapes, b, options)?)?; + let (width, height) = vectorcraft_three_d::revolve_surface_size(&shape.path, b, options)?; + let surfaces = [vectorcraft_three_d::SolidSurface { kind: SurfaceKind::Side, width, height, center: None }]; + let facets = vectorcraft_three_d::revolve_facets(&shape.path, b, options).unwrap_or_default(); + listed(&surfaces, &facets, &mut out); + return Some(out); + } + let (parts, bounds) = solid_parts(&shapes, b); + let options = vectorcraft_three_d::Extrude { map_surfaces: true, ..classic_extrude_options(&p) }; + let view = view_options(&p); + for (_, _, area, rule, _, _) in &parts { + let surfaces = vectorcraft_three_d::extrude_surfaces(area, *rule, bounds, options).unwrap_or_default(); + let facets = vectorcraft_three_d::extrude(area, *rule, bounds, options, view).unwrap_or_default(); + listed(&surfaces, &facets, &mut out); + } + Some(out) +} + +/// [`map_surfaces_at`] for `n` as it is with 3D effect `id` and parameters `p` among the effects of +/// the object itself (`item` `None`) or of its fill or stroke `item`: in place of the effect at +/// `index` when that is an effect `id`, else of the last effect `id` there, or after those effects +/// when there is none. A dialog lists the surfaces of the effect it edits with this, whether or not +/// its preview has changed the object. +pub fn map_surfaces_with( + doc: Option<&Document>, + n: &Node, + (item, index): (Option, Option), + id: &str, + p: &Value, +) -> Option> { + let mut n = n.clone(); + let effects = n.appearance.effects_mut(item)?; + let at = index.filter(|&k| effects.get(k).is_some_and(|e| e.id == id)).or_else(|| effects.iter().rposition(|e| e.id == id)); + let index = match at { + Some(index) => { + effects.get_mut(index)?.params = p.clone(); + index + } + None => { + effects.push(crate::new_effect(id, p)?); + effects.len() - 1 + } + }; + map_surfaces_at(doc, &n, item, index) +} + +/// The 3D effect `pick` finds in the effects of `n` (resolved) or of its `item`, with the shapes +/// it builds from: the members of a group or layer, or the object's own profile after the geometry +/// effects before the 3D effect. +fn picked<'n>(n: &'n Node, item: Option, pick: &Pick<'_>) -> Option<(&'n Effect, Vec)> { + Some(if is_container(n) { + let (index, fx) = pick(&n.appearance.effects).filter(|_| item.is_none())?; + let mut shapes = members(n, "").ok()?; + reshape_members(n, n.appearance.effects.get(..index)?, &mut shapes); + (fx, shapes) + } else { + let (path, rule) = profile(n)?; + let ctx = GeomContext::of(n); + match item { + None => { + let (index, fx) = pick(&n.appearance.effects)?; + let path = geometry(&path, n.appearance.effects.get(..index)?, &ctx); + (fx, vec![Profile { path, rule, items: solid_paints(n), opacity: 1.0, scopes: vec![] }]) + } + Some(k) => { + let it = n.appearance.items.get(k)?; + let (index, fx) = pick(it.effects())?; + let path = geometry(&geometry(&path, &n.appearance.effects, &ctx), it.effects().get(..index)?, &ctx.item(it)); + (fx, vec![Profile { path, rule, items: vec![it.clone()], opacity: 1.0, scopes: vec![] }]) + } + } + }) +} + /// The bounds of the art symbol `name` of `doc` draws as a graphic, in the symbol's coordinates. pub fn graphic_bounds(doc: &Document, name: &str) -> Option { graphics::art_bounds(doc, name) diff --git a/crates/effects/src/solids/classic.rs b/crates/effects/src/solids/classic.rs index 79d87fdb25..54401fd189 100644 --- a/crates/effects/src/solids/classic.rs +++ b/crates/effects/src/solids/classic.rs @@ -9,6 +9,7 @@ use vectorcraft_doc::{Appearance, AppearanceItem, FillLayer, Node}; use vectorcraft_geom::Rect; use vectorcraft_three_d::{Bevel, BevelShape, ClassicShading, ClassicSurface, Extrude, Facet, Light}; +use super::graphics::map_art::{self, MapArt, MapBudget, SolidLayout}; use crate::util::{flag, num, text}; pub const CLASSIC_EXTRUDE: &str = "threeD.classicExtrude"; @@ -51,10 +52,21 @@ pub fn classic_extrude_options(p: &Value) -> Extrude { ..Bevel::default() }), hidden: flag(p, "drawHiddenFaces", false) || classic_shading(p).surface == ClassicSurface::Wireframe, + // The numbered surfaces are laid out only for an effect that maps art onto them. + map_surfaces: !map_art::surface_maps(p).is_empty(), ..Extrude::default() } } +/// The mapped art of one solid for [`surface`]: the effect's maps, the solid's place among the +/// object's numbered surfaces, and the limits the object's mapped art shares. +pub(crate) struct Mapped<'a, 'd> { + pub(crate) art: &'a MapArt<'d>, + pub(crate) layout: &'a SolidLayout, + pub(crate) budget: &'a mut MapBudget, + pub(crate) copies: &'a mut usize, +} + /// The color faces darken toward: black (for Black Overprint too), the custom color, or none (faces /// keep their paint and only the highlight lightens them). fn shading_color(p: &Value) -> Option { @@ -102,13 +114,15 @@ const RANGES: [(&str, f64, f64, bool); 13] = [ ("blendSteps", 1.0, 256.0, true), ]; -const FLAGS: [&str; 5] = ["cap", "bevelInside", "lightBehind", "drawHiddenFaces", "preserveSpotColors"]; +const FLAGS: [&str; 7] = ["cap", "bevelInside", "lightBehind", "drawHiddenFaces", "preserveSpotColors", map_art::MAP_SHADE, map_art::MAP_INVISIBLE]; /// Check Extrude & Bevel (Classic)'s parameters `p` (its defaults filled in): every key is one of -/// its parameters, numbers are in range, flags are true or false, and `surface`, `shadingColor` and -/// `shadingCustom` name a surface, a shading color and a #rrggbb color. +/// its parameters, numbers are in range, flags are true or false, `surface`, `shadingColor` and +/// `shadingCustom` name a surface, a shading color and a #rrggbb color, and `mapArt` holds valid +/// maps. pub fn validate(p: &Value) -> Result<(), String> { - validate_classic(CLASSIC_EXTRUDE, p, &RANGES, &FLAGS) + validate_classic(CLASSIC_EXTRUDE, p, &RANGES, &FLAGS)?; + map_art::validate(CLASSIC_EXTRUDE, p) } /// Rotate (Classic)'s numeric parameters: (key, lowest, highest, whole numbers only). @@ -261,7 +275,23 @@ pub(crate) fn stroke_width(face: &Facet, p: &Value) -> f64 { /// is shaded opaque and then masked by its own transparency, so the shading follows the gradient's /// coverage; without a placement of its own, it is placed once on all the faces /// ([`crate::lighting::opaque_surface_paint`]). -pub(crate) fn surface(n: &Node, facets: Vec, source: &Paint, opacity: f32, blend: BlendMode, p: &Value) -> Node { +/// +/// With `mapped`, a face that carries mapped art is a group of the face and that art, which the +/// surface's opacity mask covers too. Shade Artwork gives the art its face's tone and highlight, +/// and Invisible Geometry leaves the faces out: a face is then a group of its art alone. Wireframe +/// draws no mapped art. Without `mapped`, `hide` leaves the faces out the same way, for a solid +/// that shares Invisible Geometry with another solid's mapped art; Wireframe still draws. +/// +/// Returns the group and whether its faces were left out. +pub(crate) fn surface( + n: &Node, + facets: Vec, + source: &Paint, + (opacity, blend): (f32, BlendMode), + p: &Value, + mapped: Option>, + hide: bool, +) -> (Node, bool) { let shading = classic_shading(p); let lights = lights(p); let shade = shading_color(p); @@ -270,57 +300,41 @@ pub(crate) fn surface(n: &Node, facets: Vec, source: &Paint, opacity: f32 let wire = shading.surface == ClassicSurface::Wireframe; let (paint, mask) = if wire { (source.clone(), None) } else { crate::lighting::opaque_surface_paint(source, || super::facets_bounds(&facets)) }; let paint = &paint; + // The mapped art of each facet, and whether the faces themselves are left out. Art past the + // limits is left out, and the faces draw; the copies and the points of art left out do not + // count against the art of later solids. + let (mut parts, invisible) = match mapped.filter(|_| !wire) { + Some(m) => { + let shaded_as = |f: &Facet, c: Color| { + let (tone, spec) = shading.tone(f.normal, &lights); + shaded(c, tone, spec, shade) + }; + let (mut used, mut budget) = (*m.copies, m.budget.clone()); + match m.art.parts(n.id, &facets, m.layout, &shaded_as, &mut budget, &mut used) { + Some(parts) => { + (*m.copies, *m.budget) = (used, budget); + (parts, m.art.invisible) + } + None => (vec![], false), + } + } + None => (vec![], hide && !wire), + }; let children = facets .into_iter() - .map(|face| { + .enumerate() + .map(|(k, face)| { + let art = parts.get_mut(k).map(std::mem::take).unwrap_or_default(); + if !art.is_empty() || invisible { + let drawn = (!invisible).then(|| Arc::new(shaded_face(n, &face, paint, &shading, &lights, shade, preserve, overprint))); + return Arc::new(Node::group(n.id, drawn.into_iter().chain(art).collect())); + } if wire { // A wire edge is drawn as a seam is: a round-joined stroke of the paint. let edge = crate::lighting::seam_stroke(paint.clone(), WIRE); return Arc::new(Node::path(n.id, face.path(), Appearance { items: vec![AppearanceItem::Stroke(edge)], ..Default::default() })); } - let (tone, spec) = shading.tone(face.normal, &lights); - // A narrow stroke of the face's own paint closes the hairline seams between faces. - let seam = super::seam_width(&face); - if overprint { - let items = overprinted_face(paint, tone, seam); - return Arc::new(Node::path(n.id, face.path(), Appearance { items, ..Default::default() })); - } - let items = match paint.color() { - // Unshaded (No Shading, no shading color, or a face in full light) with no - // highlight: the paint itself, its color space and swatch kept. - Some(_) if (tone >= 1.0 || shade.is_none()) && spec <= 0.0 => { - vec![ - AppearanceItem::Fill(FillLayer::new(paint.clone())), - AppearanceItem::Stroke(crate::lighting::seam_stroke(paint.clone(), seam)), - ] - } - // Preserve Spot Colors: a color linked to a swatch stays a tint of that swatch. - Some(_) if preserve && matches!(paint, Paint::Solid { swatch: Some(_), .. }) && !paint.is_registration() => { - linked_face(paint, tone, spec, shade, seam) - } - Some(c) => { - let fill = Paint::solid(shaded(c, tone, spec, shade)); - vec![AppearanceItem::Fill(FillLayer::new(fill.clone())), AppearanceItem::Stroke(crate::lighting::seam_stroke(fill, seam))] - } - // Gradients and patterns keep their paint, darkened by a layer of the shading color - // and lightened by one of white. As with the other 3D effects' pattern shadow, the - // layers cover the whole face, transparent pattern cells included. - None => { - let mut items = vec![ - AppearanceItem::Fill(FillLayer::new(paint.clone())), - AppearanceItem::Stroke(crate::lighting::seam_stroke(paint.clone(), seam)), - ]; - for (color, share) in [(shade, 1.0 - tone), (Some(Color::WHITE), spec)] { - if let Some(color) = color.filter(|_| share > 0.0) { - let mut layer = FillLayer::new(Paint::solid(color)); - layer.opacity = share as f32; - items.push(AppearanceItem::Fill(layer)); - } - } - items - } - }; - Arc::new(Node::path(n.id, face.path(), Appearance { items, ..Default::default() })) + Arc::new(shaded_face(n, &face, paint, &shading, &lights, shade, preserve, overprint)) }) .collect(); let mut group = Node::group(n.id, children); @@ -331,5 +345,61 @@ pub(crate) fn surface(n: &Node, facets: Vec, source: &Paint, opacity: f32 let coverage = Node::path(n.id, vectorcraft_geom::shapes::rectangle(bounds), Appearance::basic(mask, Paint::None, 0.0)); group.extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(coverage, true))); } - group + (group, invisible) +} + +/// One face of a solid in paint `paint` (opaque: [`surface`] masks a gradient's transparency), +/// filled in the paint shaded by the face's tone and highlight under `lights`, toward shading +/// color `shade`. With `preserve` (Preserve Spot Colors), a color linked to a swatch is drawn as +/// [`linked_face`] draws it. With `overprint` (Black Overprint), the face is drawn as +/// [`overprinted_face`] draws it. +#[allow(clippy::too_many_arguments)] +fn shaded_face( + n: &Node, + face: &Facet, + paint: &Paint, + shading: &ClassicShading, + lights: &[([f64; 3], f64)], + shade: Option, + preserve: bool, + overprint: bool, +) -> Node { + let (tone, spec) = shading.tone(face.normal, lights); + // A narrow stroke of the face's own paint closes the hairline seams between faces. + let seam = super::seam_width(face); + if overprint { + let items = overprinted_face(paint, tone, seam); + return Node::path(n.id, face.path(), Appearance { items, ..Default::default() }); + } + let items = match paint.color() { + // Unshaded (No Shading, no shading color, or a face in full light) with no + // highlight: the paint itself, its color space and swatch kept. + Some(_) if (tone >= 1.0 || shade.is_none()) && spec <= 0.0 => { + vec![AppearanceItem::Fill(FillLayer::new(paint.clone())), AppearanceItem::Stroke(crate::lighting::seam_stroke(paint.clone(), seam))] + } + // Preserve Spot Colors: a color linked to a swatch stays a tint of that swatch. + Some(_) if preserve && matches!(paint, Paint::Solid { swatch: Some(_), .. }) && !paint.is_registration() => { + linked_face(paint, tone, spec, shade, seam) + } + Some(c) => { + let fill = Paint::solid(shaded(c, tone, spec, shade)); + vec![AppearanceItem::Fill(FillLayer::new(fill.clone())), AppearanceItem::Stroke(crate::lighting::seam_stroke(fill, seam))] + } + // Gradients and patterns keep their paint, darkened by a layer of the shading color + // and lightened by one of white. As with the other 3D effects' pattern shadow, the + // layers cover the whole face, transparent pattern cells included. + None => { + let mut items = + vec![AppearanceItem::Fill(FillLayer::new(paint.clone())), AppearanceItem::Stroke(crate::lighting::seam_stroke(paint.clone(), seam))]; + for (color, share) in [(shade, 1.0 - tone), (Some(Color::WHITE), spec)] { + if let Some(color) = color.filter(|_| share > 0.0) { + let mut layer = FillLayer::new(Paint::solid(color)); + layer.opacity = share as f32; + items.push(AppearanceItem::Fill(layer)); + } + } + items + } + }; + Node::path(n.id, face.path(), Appearance { items, ..Default::default() }) } diff --git a/crates/effects/src/solids/graphics.rs b/crates/effects/src/solids/graphics.rs index bf4a71ace7..2859f2edf1 100644 --- a/crates/effects/src/solids/graphics.rs +++ b/crates/effects/src/solids/graphics.rs @@ -170,6 +170,8 @@ pub fn mapped_graphics(p: &Value) -> Vec { /// Revolve take graphics; a plane has only a front, and Revolve's graphics go on its side, named /// the front. Only Extrude & Bevel takes graphics on its side. pub fn validate(id: &str, p: &Value) -> Result<(), String> { + // Map Art's maps are checked with the graphics: an effect that takes none refuses them. + map_art::validate(id, p)?; let list = match p.get(GRAPHICS) { None => return Ok(()), Some(Value::Array(list)) => list, @@ -200,11 +202,11 @@ pub fn validate(id: &str, p: &Value) -> Result<(), String> { /// graphics in `old` (the effect's parameters before an edit) already name: a graphic whose symbol /// was deleted may stay. pub fn missing_symbol(doc: &Document, p: &Value, old: Option<&Value>) -> Option { - let kept = old.map(mapped_graphics).unwrap_or_default(); - mapped_graphics(p) - .into_iter() - .map(|g| g.symbol) - .find(|name| !doc.symbols.iter().any(|s| s.name == *name) && !kept.iter().any(|g| g.symbol == *name)) + let names = |p: &Value| -> Vec { + mapped_graphics(p).into_iter().map(|g| g.symbol).chain(map_art::surface_maps(p).into_iter().map(|m| m.symbol)).collect() + }; + let kept = old.map(names).unwrap_or_default(); + names(p).into_iter().find(|name| !doc.symbols.iter().any(|s| s.name == *name) && !kept.contains(name)) } /// Does the art of the symbols the graphics in `p` name fit the limits? A graphic whose symbol @@ -213,8 +215,10 @@ pub fn missing_symbol(doc: &Document, p: &Value, old: Option<&Value>) -> Option< pub fn validate_symbols(doc: &Document, p: &Value) -> Result<(), String> { let curve = if super::view_options(p).perspective > 0.0 { PERSPECTIVE_PIECES } else { 1 }; let mut elements = 0usize; - for g in mapped_graphics(p) { - let Some(symbol) = doc.symbols.iter().find(|s| s.name == g.symbol) else { continue }; + // The symbols Map Art places count with the graphics. + let names = mapped_graphics(p).into_iter().map(|g| g.symbol).chain(map_art::surface_maps(p).into_iter().map(|m| m.symbol)); + for name in names { + let Some(symbol) = doc.symbols.iter().find(|s| s.name == name) else { continue }; let pieces = pieces_of(doc, symbol)?; elements = elements.saturating_add(pieces.iter().map(|p| drawn_elements(&p.path, curve)).sum()); if elements > MAX_ELEMENTS { @@ -1225,9 +1229,11 @@ pub fn appearance_graphic_symbols(appearance: &Appearance) -> Vec { std::iter::once(&appearance.effects) .chain(appearance.items.iter().map(AppearanceItem::effects)) .flatten() - .filter(|e| takes_graphics(&e.id)) - .flat_map(|e| mapped_graphics(&e.params)) - .map(|g| g.symbol) + .filter(|e| takes_graphics(&e.id) || map_art::takes_map_art(&e.id)) + .flat_map(|e| { + let graphics = mapped_graphics(&e.params).into_iter().map(|g| g.symbol).filter(|_| takes_graphics(&e.id)); + graphics.chain(map_art::surface_maps(&e.params).into_iter().map(|m| m.symbol).filter(|_| map_art::takes_map_art(&e.id))) + }) .collect() } @@ -1247,8 +1253,15 @@ pub fn rename_appearance_graphic_symbol(appearance: &mut Appearance, from: &str, let (effects, items) = (&mut appearance.effects, &mut appearance.items); lists.push(effects); lists.extend(items.iter_mut().map(AppearanceItem::effects_mut)); - for e in lists.into_iter().flatten().filter(|e| takes_graphics(&e.id)) { - if let Some(Value::Array(list)) = e.params.get_mut(GRAPHICS) { + for e in lists.into_iter().flatten() { + let key = if takes_graphics(&e.id) { + GRAPHICS + } else if map_art::takes_map_art(&e.id) { + map_art::MAP_ART + } else { + continue; + }; + if let Some(Value::Array(list)) = e.params.get_mut(key) { for g in list.iter_mut() { if g.get("symbol").and_then(Value::as_str) == Some(from) { g["symbol"] = json!(to); @@ -1294,6 +1307,9 @@ pub fn with_graphic(p: &Value, g: &MappedGraphic) -> Value { Value::Object(out) } +#[path = "map_art.rs"] +pub(crate) mod map_art; + #[cfg(test)] #[path = "tests_graphics.rs"] mod tests; diff --git a/crates/effects/src/solids/map_art.rs b/crates/effects/src/solids/map_art.rs new file mode 100644 index 0000000000..51b86118bc --- /dev/null +++ b/crates/effects/src/solids/map_art.rs @@ -0,0 +1,655 @@ +//! Map Art: the art of a document symbol mapped onto the numbered surfaces of Extrude & Bevel +//! (Classic) and Revolve (Classic). +//! +//! The effect keeps its maps in its `mapArt` parameter, each `{surface, symbol, x, y, scaleX, +//! scaleY, rotation}`: the surface's number (from 1), the symbol's name, the offset of the art's +//! center from the center of the surface laid out flat (points, x to the right and y down as the +//! surface is seen from outside the solid), its size as a share of the symbol's own, and its turn +//! (degrees, counterclockwise). `mapShade` shades the mapped art with its surface, and +//! `mapInvisible` draws the mapped art without the solid's faces. +//! +//! The surfaces of Extrude & Bevel (Classic) are numbered through its solids in the order they are +//! built, each solid's as [`vectorcraft_three_d::extrude_surfaces`] lists them. Revolve (Classic) +//! has one surface, its swept side (in a group, the side of the member with the longest profile). +//! A map whose number is past the object's surfaces draws nothing. + +use std::collections::{HashMap, HashSet}; +use std::sync::Arc; + +use serde_json::{Map, Value, json}; +use vectorcraft_doc::color::{Color, Paint}; +use vectorcraft_doc::{Appearance, AppearanceItem, Document, FillLayer, Node, NodeId, NodeKind}; +use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Point, Rect}; +use vectorcraft_three_d::{Extrude, FaceMap, Facet, MapCell, PlanarFace, SolidSurface, SurfaceKind, View}; + +use super::{ + MAX_ELEMENTS, MAX_SURFACE_CUTS, MAX_SURFACE_POINTS, NotMapped, SURFACE_SEAM, Unrolled, counterclockwise, map_path, pieces_of, straight_pieces, + takes_seam, triangle_map, +}; + +/// The effect parameter that holds the maps. +pub const MAP_ART: &str = "mapArt"; + +/// The effect parameter of Shade Artwork. +pub const MAP_SHADE: &str = "mapShade"; + +/// The effect parameter of Invisible Geometry. +pub const MAP_INVISIBLE: &str = "mapInvisible"; + +/// The most surfaces of one 3D effect that carry a map. +pub const MAX_MAPS: usize = 64; + +/// The highest surface number a map may name. +pub const MAX_MAP_SURFACE: usize = 100_000; + +/// The error for maps on a 3D effect that takes none. +pub const MAP_ART_NOT_TAKEN: &str = "Map Art maps symbols onto Extrude & Bevel (Classic) and Revolve (Classic)"; + +/// The symbol mapped onto one numbered surface of a 3D object. +#[derive(Clone, Debug, PartialEq)] +pub struct SurfaceMap { + /// The surface's number, from 1. + pub surface: usize, + pub symbol: String, + pub x: f64, + pub y: f64, + /// Percent of the symbol's own width. + pub scale_x: f64, + /// Percent of the symbol's own height. + pub scale_y: f64, + /// Degrees, counterclockwise. + pub rotation: f64, +} + +impl SurfaceMap { + pub fn to_value(&self) -> Value { + json!({ + "surface": self.surface, + "symbol": self.symbol, + "x": self.x, + "y": self.y, + "scaleX": self.scale_x, + "scaleY": self.scale_y, + "rotation": self.rotation, + }) + } + + /// The map `v` describes. `surface` and `symbol` are required: the offsets and the rotation + /// default to 0 and the scales to 100. + pub fn from_value(v: &Value) -> Result { + let Value::Object(m) = v else { return Err(format!("each of `{MAP_ART}` must be an object")) }; + if let Some(k) = m.keys().find(|k| !matches!(k.as_str(), "surface" | "symbol" | "x" | "y" | "scaleX" | "scaleY" | "rotation")) { + return Err(format!("`{MAP_ART}` entries take surface, symbol, x, y, scaleX, scaleY and rotation, not `{k}`")); + } + let surface = m + .get("surface") + .and_then(Value::as_u64) + .and_then(|n| usize::try_from(n).ok()) + .filter(|n| (1..=MAX_MAP_SURFACE).contains(n)) + .ok_or_else(|| format!("each of `{MAP_ART}` needs `surface`, a whole number from 1 to {MAX_MAP_SURFACE}"))?; + let symbol = match m.get("symbol") { + Some(Value::String(s)) if !s.trim().is_empty() => s.clone(), + _ => return Err(format!("each of `{MAP_ART}` needs `symbol`, the name of a symbol")), + }; + let number = |key: &str, default: f64, (lo, hi): (f64, f64)| -> Result { + match m.get(key) { + None => Ok(default), + Some(v) => v + .as_f64() + .filter(|n| n.is_finite() && (lo..=hi).contains(n)) + .ok_or_else(|| format!("`{MAP_ART}` {key} must be a number from {lo} to {hi}")), + } + }; + Ok(Self { + surface, + symbol, + x: number("x", 0.0, (-super::MAX_OFFSET, super::MAX_OFFSET))?, + y: number("y", 0.0, (-super::MAX_OFFSET, super::MAX_OFFSET))?, + scale_x: number("scaleX", 100.0, super::SCALE_RANGE)?, + scale_y: number("scaleY", 100.0, super::SCALE_RANGE)?, + rotation: number("rotation", 0.0, (-360.0, 360.0))?, + }) + } + + /// Where the symbol's art goes on the flat surface, for art whose bounds are `art` on a + /// surface with center `center`. With `mirrored` (the back cap) x runs to the right as the + /// surface is seen from behind the solid. + pub fn placement(&self, art: Rect, center: Point, mirrored: bool) -> Affine { + let place = Affine::translate((center.x + self.x, center.y + self.y)) + * Affine::rotate(-self.rotation.to_radians()) + * Affine::scale_non_uniform(self.scale_x / 100.0, self.scale_y / 100.0) + * Affine::translate(-art.center().to_vec2()); + if mirrored { + Affine::translate(center.to_vec2()) * Affine::scale_non_uniform(-1.0, 1.0) * Affine::translate(-center.to_vec2()) * place + } else { + place + } + } + + /// The scales (percent) at which art with bounds `art`, turned by the map's rotation, fills a + /// surface `width` by `height` points: Scale to Fit. `None` for art or a surface with no area. + pub fn fitting_scales(&self, art: Rect, (width, height): (f64, f64)) -> Option<(f64, f64)> { + let (w, h) = (art.width(), art.height()); + if w <= 0.0 || h <= 0.0 || width <= 0.0 || height <= 0.0 { + return None; + } + // The box of the art turned by the rotation, at its own size. + let (sin, cos) = self.rotation.to_radians().sin_cos(); + let (bw, bh) = (w * cos.abs() + h * sin.abs(), w * sin.abs() + h * cos.abs()); + let clamp = |v: f64| v.clamp(super::SCALE_RANGE.0, super::SCALE_RANGE.1); + if sin.abs() < 1e-9 || cos.abs() < 1e-9 { + // Square to the surface, each side takes its own scale. + let (sx, sy) = if cos.abs() >= 0.5 { (width / w, height / h) } else { (height / w, width / h) }; + return Some((clamp(sx * 100.0), clamp(sy * 100.0))); + } + let fit = (width / bw).min(height / bh); + Some((clamp(fit * 100.0), clamp(fit * 100.0))) + } +} + +/// The 3D effects that take Map Art: Extrude & Bevel (Classic) and Revolve (Classic). +pub fn takes_map_art(id: &str) -> bool { + id == super::super::CLASSIC_EXTRUDE || id == crate::CLASSIC_REVOLVE +} + +/// The maps in parameters `p`, leaving out entries that are not valid and, of two maps of one +/// surface, the later one (a file may hold anything; commands check every entry with +/// [`validate`]). +pub fn surface_maps(p: &Value) -> Vec { + let Some(Value::Array(list)) = p.get(MAP_ART) else { return vec![] }; + let mut seen = HashSet::new(); + list.iter().filter_map(|v| SurfaceMap::from_value(v).ok()).filter(|m| seen.insert(m.surface)).take(MAX_MAPS).collect() +} + +/// Are the maps in parameters `p` of 3D effect `id` valid? Only Extrude & Bevel (Classic) and +/// Revolve (Classic) take maps, at most [`MAX_MAPS`] of them, one for a surface. +pub fn validate(id: &str, p: &Value) -> Result<(), String> { + let list = match p.get(MAP_ART) { + None => return Ok(()), + Some(Value::Array(list)) => list, + Some(_) => return Err(format!("`{MAP_ART}` must be an array")), + }; + if list.is_empty() { + return Ok(()); + } + if !takes_map_art(id) { + return Err(MAP_ART_NOT_TAKEN.into()); + } + if list.len() > MAX_MAPS { + return Err(format!("`{MAP_ART}` takes at most {MAX_MAPS} maps")); + } + let mut seen = HashSet::new(); + for v in list { + let m = SurfaceMap::from_value(v)?; + if !seen.insert(m.surface) { + return Err(format!("`{MAP_ART}` maps surface {} more than once", m.surface)); + } + } + Ok(()) +} + +/// `p` with the map of surface `surface` replaced by `map`, or removed with `None`. The maps stay +/// in the order of their surfaces. +pub fn with_surface_map(p: &Value, surface: usize, map: Option<&SurfaceMap>) -> Value { + let mut maps: Vec = surface_maps(p).into_iter().filter(|m| m.surface != surface).collect(); + maps.extend(map.cloned()); + maps.sort_by_key(|m| m.surface); + let mut out = p.as_object().cloned().unwrap_or_else(Map::new); + out.insert(MAP_ART.into(), Value::Array(maps.iter().map(SurfaceMap::to_value).collect())); + Value::Object(out) +} + +/// One solid's place among its object's numbered surfaces: the index of its first surface, its +/// surfaces, and for a solid with planar ends the bounds, options and view it was built with. +pub(crate) struct SolidLayout { + pub(crate) first: usize, + pub(crate) surfaces: Vec, + pub(crate) ends: Option<(Rect, Extrude, View)>, +} + +/// What the mapped art of one object has drawn so far, against the limits its maps share. +#[derive(Clone, Debug, Default, PartialEq)] +pub(crate) struct MapBudget { + elements: usize, + /// The points of the maps' symbols cut into straight pieces, against [`MAX_ELEMENTS`]. + input: usize, + /// The points the maps' art draws on the faces, against [`MAX_SURFACE_POINTS`]. + points: usize, + cuts: usize, +} + +/// The maps of one 3D effect, with the document whose symbols they place. +pub(crate) struct MapArt<'a> { + doc: &'a Document, + maps: Vec, + /// Shade Artwork: the mapped art takes the shading of its surface. + pub(crate) shade: bool, + /// Invisible Geometry: only the mapped art is drawn. + pub(crate) invisible: bool, +} + +impl<'a> MapArt<'a> { + /// The maps of 3D effect `id` with parameters `p`. `None` without a document, for an effect + /// that takes no maps and for one that has none. + pub(crate) fn of(doc: Option<&'a Document>, id: &str, p: &Value) -> Option { + let maps = surface_maps(p); + let flag = |key: &str| p.get(key).and_then(Value::as_bool).unwrap_or(false); + (takes_map_art(id) && !maps.is_empty()).then_some(Self { doc: doc?, maps, shade: flag(MAP_SHADE), invisible: flag(MAP_INVISIBLE) }) + } + + fn map_of(&self, index: usize) -> Option<&SurfaceMap> { + self.maps.iter().find(|m| m.surface == index + 1) + } + + /// The mapped art that falls on each of `facets`, one solid's facets in drawing order, for an + /// object with id `id`: for each facet, the nodes to draw right after it. Only facets turned + /// toward the viewer carry art. `shade` gives a color as its facet shades it, for Shade + /// Artwork. A map whose symbol the document does not have, or whose art is past the limits of + /// a graphic's art, draws nothing. `None` when the art is past the limits the maps of one + /// object share, or the copies of its paints take `copies` past the object's allowance: the + /// solid then draws without mapped art. + pub(crate) fn parts( + &self, + id: NodeId, + facets: &[Facet], + layout: &SolidLayout, + shade: &dyn Fn(&Facet, Color) -> Color, + budget: &mut MapBudget, + copies: &mut usize, + ) -> Option>>> { + let mut out: Vec>> = vec![vec![]; facets.len()]; + let mut flat: HashMap> = HashMap::new(); + for (f, parts) in facets.iter().zip(out.iter_mut()) { + if f.away { + continue; + } + let recolor = |c: Color| if self.shade { shade(f, c) } else { c }; + if let Some(end) = f.end { + let Some(local) = layout.surfaces.iter().position(|s| s.kind == SurfaceKind::End(end)) else { continue }; + let (Some(m), Some(center)) = (self.map_of(layout.first + local), layout.surfaces.get(local).and_then(|s| s.center)) else { + continue; + }; + let Some((bounds, options, view)) = layout.ends else { continue }; + let Some(map) = vectorcraft_three_d::extrude_face_map(bounds, options, view, end) else { continue }; + parts.extend(self.end_art(id, m, (end, &map), center, f, &recolor, budget, copies)?); + } else if let Some(cell) = f.cell.as_deref() { + let (Some(m), Some(surface)) = (self.map_of(layout.first + cell.surface), layout.surfaces.get(cell.surface)) else { continue }; + if let std::collections::hash_map::Entry::Vacant(e) = flat.entry(cell.surface) { + e.insert(self.unrolled(m, surface, budget)?); + } + let Some(pieces) = flat.get(&cell.surface) else { continue }; + parts.extend(cell_art(id, pieces, cell, f, &recolor, budget, copies)?); + } + } + Some(out) + } + + /// The art of map `m` on planar end `end` of a solid, drawn on its facet `f` through `map`, + /// for an end whose bounds have center `center`: one clipping group, as a graphic on a cap is + /// drawn. `None` past the limits. + #[allow(clippy::too_many_arguments)] + fn end_art( + &self, + id: NodeId, + m: &SurfaceMap, + (end, map): (PlanarFace, &FaceMap), + center: Point, + f: &Facet, + recolor: &dyn Fn(Color) -> Color, + budget: &mut MapBudget, + copies: &mut usize, + ) -> Option>> { + let Some(symbol) = self.doc.symbols.iter().find(|s| s.name == m.symbol) else { return Some(vec![]) }; + let Ok(pieces) = pieces_of(self.doc, symbol) else { return Some(vec![]) }; + let Some(bounds) = pieces.iter().filter_map(|p| p.path.bounds()).reduce(|a, b| a.union(b)) else { return Some(vec![]) }; + let place = m.placement(bounds, center, end == PlanarFace::Back); + let affine = map.local_affine(center).filter(|_| map.is_affine()); + // Gradients follow the end's map as it is near the art's center, or near the middle of the + // part in front of the eye when the center is not. + let local = map.local_affine(place * bounds.center()).or_else(|| { + let part = map.mapped_part(place.transform_rect_bbox(bounds))?; + let sum = part.iter().fold(Point::ZERO, |s, p| s + p.to_vec2()); + map.local_affine(Point::new(sum.x / part.len() as f64, sum.y / part.len() as f64)) + }); + let Some(local) = local else { return Some(vec![]) }; + let gradient_map = local * place; + let mut children = vec![]; + for piece in pieces { + let placed = piece.path.transformed(place); + let least: usize = placed.subpaths.iter().map(|s| s.anchors.len()).sum(); + let before = budget.elements; + if before.saturating_add(least) > MAX_ELEMENTS { + return None; + } + let room = MAX_ELEMENTS - before; + let mut rule = piece.rule; + let mapped = match map_path(&placed, map, affine, room) { + Err(NotMapped::Behind) => { + // Part of it is at or behind the eye: the part in front is drawn. + let Some(part) = placed.bounds().and_then(|b| map.mapped_part(b)) else { continue }; + let Some(&first) = part.first() else { continue }; + let mut front = BezPath::new(); + front.move_to(first); + part.iter().skip(1).for_each(|p| front.line_to(*p)); + front.close_path(); + let cut = vectorcraft_pathops::boolean( + &placed, + piece.rule, + &PathData::from_bezpath(&front), + FillRule::NonZero, + vectorcraft_pathops::BoolOp::Intersect, + ); + rule = FillRule::NonZero; + map_path(&cut, map, affine, room) + } + done => done, + }; + let mapped = match mapped { + Ok(mapped) => mapped, + Err(NotMapped::Full) => return None, + Err(NotMapped::Behind) => continue, + }; + budget.elements = before.saturating_add(mapped.elements().len()); + if !crate::revolve::paint_copies_add(copies, 1, &piece.paint) { + return None; + } + children.push(Arc::new(piece_node(id, piece.paint, (piece.opacity, piece.blend), (mapped, rule), gradient_map, recolor, None))); + } + if children.is_empty() { + return Some(vec![]); + } + // An end's holes are contours of the same path wound against its outline, so turning the + // whole path keeps them holes under the nonzero rule. + let mut outline = f.path().to_bezpath(); + if vectorcraft_geom::kurbo::Shape::area(&outline) < 0.0 { + outline = outline.reverse_subpaths(); + } + let clip = Node::path(id, PathData::from_bezpath(&outline), Appearance::default()); + Some(vec![Arc::new(Node::new(id, NodeKind::Group { children: vec![Arc::new(clip), Arc::new(Node::group(id, children))], clip: true }))]) + } + + /// The areas of map `m`'s symbol placed on `surface` laid out flat, cut into straight pieces. + /// Empty for a symbol the document does not have or whose art is past the limits of a + /// graphic's art. `None` when the pieces of the object's maps take more than + /// [`MAX_ELEMENTS`] points together. + fn unrolled(&self, m: &SurfaceMap, surface: &SolidSurface, budget: &mut MapBudget) -> Option> { + let Some(symbol) = self.doc.symbols.iter().find(|s| s.name == m.symbol) else { return Some(vec![]) }; + let Ok(art) = pieces_of(self.doc, symbol) else { return Some(vec![]) }; + let Some(bounds) = art.iter().filter_map(|p| p.path.bounds()).reduce(|a, b| a.union(b)) else { return Some(vec![]) }; + let place = m.placement(bounds, flat_center(surface), false); + let mut pieces = vec![]; + for piece in art { + let placed = place * piece.path.to_bezpath(); + let mut polygons = straight_pieces(&placed, &mut budget.input)?; + polygons.retain(|p| p.len() >= 3 && p.iter().all(|q| q.is_finite())); + let boxes: Vec = polygons.iter().filter_map(|polygon| box_of(polygon)).collect(); + let Some(bounds) = boxes.iter().copied().reduce(|a, b| a.union(b)) else { continue }; + pieces.push(Unrolled { + polygons, + boxes, + bounds, + rule: piece.rule, + paint: piece.paint, + opacity: piece.opacity, + blend: piece.blend, + place, + }); + } + Some(pieces) + } +} + +/// The center of `surface` laid out flat, which a map's offset is measured from: the middle of a +/// wall or a bevel, whose flat coordinates start at its corner, and the origin of Revolve's side, +/// whose flat coordinates start at its middle. +pub fn flat_center(surface: &SolidSurface) -> Point { + match surface.kind { + SurfaceKind::Side => Point::ZERO, + SurfaceKind::End(_) => surface.center.unwrap_or(Point::ZERO), + SurfaceKind::Wall | SurfaceKind::Bevel => Point::new(surface.width / 2.0, surface.height / 2.0), + } +} + +fn box_of(points: &[Point]) -> Option { + points.iter().map(|p| Rect::from_points(*p, *p)).reduce(|a, b| a.union(b)) +} + +/// A map from a region of a flat surface onto the page. +enum Mapper { + Affine(Affine), + /// The projective map that takes the rectangle with corner `origin` and size `size` onto a + /// quadrilateral: `rows` are its coefficients on the unit square. + Quad { + origin: Point, + size: (f64, f64), + rows: [f64; 8], + }, +} + +impl Mapper { + fn at(&self, p: Point) -> Point { + match self { + Mapper::Affine(a) => *a * p, + Mapper::Quad { origin, size, rows: [a, b, c, d, e, f, g, h] } => { + let (u, v) = ((p.x - origin.x) / size.0, (p.y - origin.y) / size.1); + let w = g * u + h * v + 1.0; + Point::new((a * u + b * v + c) / w, (d * u + e * v + f) / w) + } + } + } + + /// The affine map nearest this one around `p`, for gradients and patterns. + fn local(&self, p: Point, step: f64) -> Affine { + match self { + Mapper::Affine(a) => *a, + Mapper::Quad { .. } => { + let (o, x, y) = (self.at(p), self.at(Point::new(p.x + step, p.y)), self.at(Point::new(p.x, p.y + step))); + let (dx, dy) = ((x - o) / step, (y - o) / step); + Affine::new([dx.x, dx.y, dy.x, dy.y, o.x - dx.x * p.x - dy.x * p.y, o.y - dx.y * p.x - dy.y * p.y]) + } + } + } +} + +/// The projective map of `cell`, a cell whose flat corners are those of an upright rectangle, in +/// order along its edge nearest the origin and back: exact for a flat wall under a perspective. `None` +/// for any other cell and for a quadrilateral the map turns inside out. +fn quad_mapper(cell: &MapCell) -> Option<(Vec, Mapper)> { + let [mut u0, mut u1, mut u2, mut u3] = <[Point; 4]>::try_from(cell.uv.as_slice()).ok()?; + let [mut p0, mut p1, mut p2, mut p3] = <[Point; 4]>::try_from(cell.page.as_slice()).ok()?; + // A cell whose first edge runs from right to left is read from its other end. + if u1.x < u0.x { + (u0, u1, u2, u3) = (u1, u0, u3, u2); + (p0, p1, p2, p3) = (p1, p0, p3, p2); + } + let size = (u1.x - u0.x, u3.y - u0.y); + let upright = u1.y == u0.y && u2.x == u1.x && u2.y == u3.y && u3.x == u0.x && size.0 > 1e-9 && size.1 > 1e-9; + if !upright { + return None; + } + let (dx1, dx2, sx) = (p1.x - p2.x, p3.x - p2.x, p0.x - p1.x + p2.x - p3.x); + let (dy1, dy2, sy) = (p1.y - p2.y, p3.y - p2.y, p0.y - p1.y + p2.y - p3.y); + let den = dx1 * dy2 - dx2 * dy1; + let scale = dx1.abs() + dx2.abs() + dy1.abs() + dy2.abs(); + if den.is_nan() || den.abs() <= 1e-12 * scale * scale { + return None; + } + let (g, h) = ((sx * dy2 - dx2 * sy) / den, (dx1 * sy - sx * dy1) / den); + let rows = [p1.x - p0.x + g * p1.x, p3.x - p0.x + h * p3.x, p0.x, p1.y - p0.y + g * p1.y, p3.y - p0.y + h * p3.y, p0.y, g, h]; + let inside = g + 1.0 > 1e-6 && h + 1.0 > 1e-6 && g + h + 1.0 > 1e-6; + (inside && rows.iter().all(|v| v.is_finite())).then(|| (vec![u0, u1, u2, u3], Mapper::Quad { origin: u0, size, rows })) +} + +/// The regions of `cell` on its flat surface, each a convex polygon wound as [`clip_convex`] reads +/// it, with its map onto the page: the whole of an upright rectangle ([`quad_mapper`]), else the +/// triangles the cell is cut into. +fn regions(cell: &MapCell) -> Vec<(Vec, Mapper)> { + if let Some(quad) = quad_mapper(cell) { + return vec![quad]; + } + let triangles: &[[usize; 3]] = if cell.uv.len() == 3 { &[[0, 1, 2]] } else { &[[0, 1, 2], [0, 2, 3]] }; + triangles + .iter() + .filter_map(|corners| { + let pick = |of: &[Point]| corners.iter().map(|k| of.get(*k).copied()).collect::>>(); + let (uv, page) = (pick(&cell.uv)?, pick(&cell.page)?); + Some((counterclockwise(&uv)?.to_vec(), Mapper::Affine(triangle_map(&uv, &page)?))) + }) + .collect() +} + +/// The part of `polygon` inside the convex `window` (one step of Sutherland and Hodgman's clip for +/// each of its edges), wound so that its inside is on the positive side of each edge. +fn clip_convex(polygon: &[Point], window: &[Point]) -> Vec { + let mut out = polygon.to_vec(); + for (k, &a) in window.iter().enumerate() { + let Some(&b) = window.get((k + 1) % window.len()) else { continue }; + let side = |p: Point| (b - a).cross(p - a); + let input = std::mem::take(&mut out); + for (i, &p) in input.iter().enumerate() { + let Some(&q) = input.get((i + 1) % input.len()) else { continue }; + let (sp, sq) = (side(p), side(q)); + if sp >= 0.0 { + out.push(p); + } + if (sp >= 0.0) != (sq >= 0.0) { + out.push(p.lerp(q, sp / (sp - sq))); + } + } + if out.len() < 3 { + return vec![]; + } + } + out +} + +/// The parts of `pieces`, a map's art on its flat surface, that fall on `cell`, the cell of facet +/// `f`, drawn on the page. `None` past the limits. +fn cell_art( + id: NodeId, + pieces: &[Unrolled], + cell: &MapCell, + f: &Facet, + recolor: &dyn Fn(Color) -> Color, + budget: &mut MapBudget, + copies: &mut usize, +) -> Option>> { + if cell.uv.len() != cell.page.len() || !(3..=4).contains(&cell.uv.len()) { + return Some(vec![]); + } + let Some(reach) = box_of(&cell.uv) else { return Some(vec![]) }; + let apart = |b: &Rect| b.x1 < reach.x0 || b.x0 > reach.x1 || b.y1 < reach.y0 || b.y0 > reach.y1; + let regions = regions(cell); + // A facet cut after it was built, or one whose edges follow the profile's curves, draws only the + // part of the art inside its own outline. + let whole = f.outline.is_none() && f.contours.first() == Some(&cell.page); + let mut out = vec![]; + for piece in pieces.iter().filter(|p| !apart(&p.bounds)) { + let mut path = BezPath::new(); + for (window, mapper) in ®ions { + for (polygon, _) in piece.polygons.iter().zip(&piece.boxes).filter(|(_, b)| !apart(b)) { + budget.cuts = budget.cuts.saturating_add(polygon.len()); + if budget.cuts > MAX_SURFACE_CUTS { + return None; + } + let cut = clip_convex(polygon, window); + let Some((first, rest)) = cut.split_first() else { continue }; + path.move_to(mapper.at(*first)); + rest.iter().for_each(|q| path.line_to(mapper.at(*q))); + path.close_path(); + budget.points = budget.points.saturating_add(cut.len()); + } + } + if budget.points > MAX_SURFACE_POINTS { + return None; + } + if path.elements().is_empty() { + continue; + } + let (path, rule) = if whole { + (path, piece.rule) + } else { + let cut = vectorcraft_pathops::boolean( + &PathData::from_bezpath(&path), + piece.rule, + &f.path(), + FillRule::NonZero, + vectorcraft_pathops::BoolOp::Intersect, + ); + (cut.to_bezpath(), FillRule::NonZero) + }; + if path.elements().is_empty() || !path.elements().iter().all(el_is_finite) { + continue; + } + let seam = takes_seam(piece); + if !crate::revolve::paint_copies_add(copies, 1 + usize::from(seam), &piece.paint) { + return None; + } + // Gradients and patterns follow the cell's map as it is at the cell's middle. + let middle = reach.center(); + let local = regions.first().map_or(Affine::IDENTITY, |(_, m)| m.local(middle, (reach.width().max(reach.height()) * 1e-3).max(1e-6))); + let node = piece_node( + id, + piece.paint.clone(), + (piece.opacity, piece.blend), + (path, rule), + local * piece.place, + recolor, + seam.then_some(SURFACE_SEAM), + ); + out.push(Arc::new(node)); + } + Some(out) +} + +fn el_is_finite(el: &vectorcraft_geom::kurbo::PathEl) -> bool { + use vectorcraft_geom::kurbo::PathEl; + match *el { + PathEl::MoveTo(p) | PathEl::LineTo(p) => p.is_finite(), + PathEl::QuadTo(a, p) => a.is_finite() && p.is_finite(), + PathEl::CurveTo(a, b, p) => a.is_finite() && b.is_finite() && p.is_finite(), + PathEl::ClosePath => true, + } +} + +/// One painted area of mapped art on the page: `path` filled under `rule` with `paint`, its +/// gradients and pattern tiles placed through `gradient_map`, its colors through `recolor`, and +/// with `seam` a stroke of that width in the same paint over the seams between neighboring parts. +fn piece_node( + id: NodeId, + mut paint: Paint, + (opacity, blend): (f32, vectorcraft_doc::color::BlendMode), + (path, rule): (BezPath, FillRule), + gradient_map: Affine, + recolor: &dyn Fn(Color) -> Color, + seam: Option, +) -> Node { + if let Paint::Pattern { xf, .. } = &mut paint { + *xf = gradient_map * *xf; + } + let mut fill = FillLayer::new(paint); + fill.opacity = opacity; + fill.blend = blend; + let mut appearance = Appearance { items: vec![AppearanceItem::Fill(fill)], ..Default::default() }; + appearance.transform_gradients(gradient_map); + for item in appearance.items.iter_mut() { + if let AppearanceItem::Fill(f) = item { + // Pattern tiles keep their colors: the document's pattern draws them. + vectorcraft_doc::recolor::map_paint(&mut f.paint, recolor); + } + } + if let (Some(width), Some(AppearanceItem::Fill(f))) = (seam, appearance.items.first()) { + let mut stroke = vectorcraft_doc::StrokeLayer::new(f.paint.clone(), width); + stroke.join = vectorcraft_doc::LineJoin::Round; + appearance.items.push(AppearanceItem::Stroke(stroke)); + } + let mut node = Node::path(id, PathData::from_bezpath(&path), appearance); + if let NodeKind::Path { rule: r, .. } = &mut node.kind { + *r = rule; + } + node +} + +#[cfg(test)] +#[path = "tests_map_art.rs"] +mod tests; diff --git a/crates/effects/src/solids/tests.rs b/crates/effects/src/solids/tests.rs index b77903714e..74636721b8 100644 --- a/crates/effects/src/solids/tests.rs +++ b/crates/effects/src/solids/tests.rs @@ -776,6 +776,7 @@ fn a_stroke_face_through_a_fill_wall_is_cut_where_their_depths_meet() { end: None, surface: None, plane: Some(DepthPlane { normal, offset, center: Point::ZERO, eye: None }), + cell: None, }; let wall = facet(0.0, [0.0, 0.0, 1.0], 0.0); // z = x - 8: behind the wall left of x = 8, in front of it right of it. diff --git a/crates/effects/src/solids/tests_graphics_side.rs b/crates/effects/src/solids/tests_graphics_side.rs index d216ff7d0d..a35757257f 100644 --- a/crates/effects/src/solids/tests_graphics_side.rs +++ b/crates/effects/src/solids/tests_graphics_side.rs @@ -186,6 +186,7 @@ fn a_piece_cut_from_a_face_draws_its_own_part() { end: None, surface: Some(vectorcraft_three_d::SurfaceCell { page: square, uv, outward: true }), plane: Some(vectorcraft_three_d::DepthPlane { normal, offset, center: Point::ZERO, eye: None }), + cell: None, } }; let wall = facet(0.0, [0.0, 0.0, 1.0], 0.0); diff --git a/crates/effects/src/solids/tests_map_art.rs b/crates/effects/src/solids/tests_map_art.rs new file mode 100644 index 0000000000..dfa35a019d --- /dev/null +++ b/crates/effects/src/solids/tests_map_art.rs @@ -0,0 +1,495 @@ +use serde_json::json; +use vectorcraft_doc::Symbol; +use vectorcraft_geom::shapes; + +use super::super::super::{CLASSIC_EXTRUDE, CLASSIC_ROTATE, MapSurface, map_surfaces_at, solid_art_in, validate_three_d_at_in, validate_three_d_in}; +use super::*; +use crate::CLASSIC_REVOLVE; + +const RED: Color = Color::Rgb { r: 1.0, g: 0.0, b: 0.0 }; +const GREEN: Color = Color::Rgb { r: 0.0, g: 1.0, b: 0.0 }; +const BLUE: Color = Color::Rgb { r: 0.0, g: 0.0, b: 1.0 }; + +fn square(id: u64, r: Rect, c: Color) -> Node { + Node::path(NodeId(id), shapes::rectangle(r), Appearance::basic(Paint::solid(c), Paint::None, 0.0)) +} + +/// A document with symbol "Mark", a red 10 × 10 square, and symbol "Corner", 30 × 30: a red square +/// at its top left, a blue one to the right of it and a green one below it. +fn document() -> Document { + let mut d = Document::new(1000.0, 1000.0); + d.symbols.push(Symbol { dynamic: false, name: "Mark".into(), art: Arc::new(square(0, Rect::new(500.0, 500.0, 510.0, 510.0), RED)) }); + let corner = Node::group( + NodeId(0), + vec![ + Arc::new(square(0, Rect::new(0.0, 0.0, 10.0, 10.0), RED)), + Arc::new(square(0, Rect::new(20.0, 0.0, 30.0, 10.0), BLUE)), + Arc::new(square(0, Rect::new(0.0, 20.0, 10.0, 30.0), GREEN)), + ], + ); + d.symbols.push(Symbol { dynamic: false, name: "Corner".into(), art: Arc::new(corner) }); + d +} + +/// A gray 100 × 100 square at (0, 0) with effect `id`, its parameters `params` over a view +/// straight on with No Shading. +fn object(id: &str, params: Value) -> Node { + let mut p = json!({"rotationX": 0.0, "rotationY": 0.0, "rotationZ": 0.0, "surface": "none"}); + if let (Some(p), Some(extra)) = (p.as_object_mut(), params.as_object()) { + p.extend(extra.clone()); + } + let mut n = square(7, Rect::new(0.0, 0.0, 100.0, 100.0), Color::rgb(0.5, 0.5, 0.5)); + n.appearance.effects.push(crate::new_effect(id, &p).unwrap()); + n +} + +/// The paths of `art` filled with color `c`, in drawing order. +fn filled(art: &Node, c: Color) -> Vec { + let mut out = vec![]; + art.walk(&mut |n| { + let fill = n.appearance.items.iter().find_map(|i| match i { + AppearanceItem::Fill(f) => f.paint.color(), + AppearanceItem::Stroke(_) => None, + }); + if fill.is_some_and(|f| f.to_rgb().iter().zip(c.to_rgb()).all(|(a, b)| (a - b).abs() < 1e-4)) + && let Some(p) = n.path_data() + { + out.push(p.clone()); + } + }); + out +} + +fn bounds_of(paths: &[PathData]) -> Rect { + paths.iter().filter_map(|p| p.bounds()).reduce(|a, b| a.union(b)).unwrap() +} + +fn close(a: Rect, b: Rect) -> bool { + [(a.x0, b.x0), (a.y0, b.y0), (a.x1, b.x1), (a.y1, b.y1)].iter().all(|(p, q)| (p - q).abs() < 1e-6) +} + +fn surfaces(n: &Node) -> Vec { + map_surfaces_at(Some(&document()), n, None, 0).unwrap() +} + +/// Which way round the "Corner" symbol reads in `art`: positive when its blue square is to the +/// right of its red one and its green one below, as the symbol is drawn, at any turn; negative +/// when it is mirrored. +fn handedness(art: &Node) -> f64 { + let at = |c: Color| bounds_of(&filled(art, c)).center(); + (at(BLUE) - at(RED)).cross(at(GREEN) - at(RED)) +} + +#[test] +fn the_surfaces_are_the_caps_then_each_wall_then_each_bevel() { + let kinds = |n: &Node| surfaces(n).iter().map(|s| s.kind).collect::>(); + let (front, back) = (SurfaceKind::End(PlanarFace::Front), SurfaceKind::End(PlanarFace::Back)); + let solid = object(CLASSIC_EXTRUDE, json!({})); + assert_eq!(kinds(&solid), [vec![front, back], vec![SurfaceKind::Wall; 4]].concat()); + // Each wall runs from corner to corner of the square and is as deep as the solid. + for wall in surfaces(&solid).iter().skip(2) { + assert!((wall.width - 100.0).abs() < 1e-6 && (wall.height - 50.0).abs() < 1e-6, "{wall:?}"); + } + assert_eq!(kinds(&object(CLASSIC_EXTRUDE, json!({"cap": false}))), vec![SurfaceKind::Wall; 4]); + let beveled = object(CLASSIC_EXTRUDE, json!({"bevel": "classic"})); + assert_eq!(kinds(&beveled), [vec![front, back], vec![SurfaceKind::Wall; 4], vec![SurfaceKind::Bevel; 4]].concat()); + // With no depth the art is a plane, which has its front only. + assert_eq!(kinds(&object(CLASSIC_EXTRUDE, json!({"depth": 0}))), vec![front]); + // An outline with no corner has one wall. + let mut round = Node::path(NodeId(7), shapes::ellipse(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::basic(Paint::solid(RED), Paint::None, 0.0)); + round.appearance.effects.push(crate::new_effect(CLASSIC_EXTRUDE, &json!({})).unwrap()); + assert_eq!(kinds(&round), vec![front, back, SurfaceKind::Wall]); + // Revolve (Classic) has its side, and Rotate (Classic) takes no maps. + assert_eq!(kinds(&object(CLASSIC_REVOLVE, json!({}))), vec![SurfaceKind::Side]); + assert_eq!(map_surfaces_at(Some(&document()), &object(CLASSIC_ROTATE, json!({})), None, 0), None); + // Seen straight on, only the front cap is turned toward the viewer. + let seen: Vec = surfaces(&solid).iter().map(|s| s.visible).collect(); + assert_eq!(seen, [true, false, false, false, false, false]); +} + +#[test] +fn a_map_on_the_front_cap_draws_the_symbol_at_its_offset_scales_and_turn() { + let d = document(); + let map = |m: Value| solid_art_in(Some(&d), &object(CLASSIC_EXTRUDE, json!({"mapArt": [m]}))).unwrap(); + // Without a map nothing red is drawn. + assert!(filled(&solid_art_in(Some(&d), &object(CLASSIC_EXTRUDE, json!({}))).unwrap(), RED).is_empty()); + // The art's center is at the center of the cap, its size the symbol's own. + let centered = filled(&map(json!({"surface": 1, "symbol": "Mark"})), RED); + assert!(close(bounds_of(¢ered), Rect::new(45.0, 45.0, 55.0, 55.0)), "{:?}", bounds_of(¢ered)); + // An offset moves it, and each scale sizes one side. + let moved = filled(&map(json!({"surface": 1, "symbol": "Mark", "x": 10, "y": -5, "scaleX": 200, "scaleY": 300})), RED); + assert!(close(bounds_of(&moved), Rect::new(50.0, 30.0, 70.0, 60.0)), "{:?}", bounds_of(&moved)); + // A quarter turn swaps the sides. + let turned = filled(&map(json!({"surface": 1, "symbol": "Mark", "scaleX": 200, "rotation": 90})), RED); + assert!(close(bounds_of(&turned), Rect::new(45.0, 40.0, 55.0, 60.0)), "{:?}", bounds_of(&turned)); + // The art is clipped to the cap. + let past = filled(&map(json!({"surface": 1, "symbol": "Mark", "x": 50})), RED); + assert_eq!(past.len(), 1); + let art = map(json!({"surface": 1, "symbol": "Mark", "x": 50})); + let mut clipped = false; + art.walk(&mut |n| clipped |= matches!(&n.kind, NodeKind::Group { clip: true, .. })); + assert!(clipped); +} + +#[test] +fn a_map_on_a_side_wall_reads_the_right_way_round_from_outside() { + let d = document(); + let all_walls: Vec = (3..=6).map(|k| json!({"surface": k, "symbol": "Corner"})).collect(); + for turn in [-90.0, 90.0] { + // Seen from one side, one wall faces the viewer: it alone carries its map. + let n = object(CLASSIC_EXTRUDE, json!({"rotationY": turn, "mapArt": all_walls})); + let art = solid_art_in(Some(&d), &n).unwrap(); + assert_eq!(filled(&art, RED).len(), 1, "one wall is seen at {turn}"); + // The wall is 100 along the outline and 50 deep: the art keeps its size at its middle. + let whole = bounds_of(&[filled(&art, RED), filled(&art, BLUE), filled(&art, GREEN)].concat()); + assert!((whole.width() - 30.0).abs() < 1e-6 && (whole.height() - 30.0).abs() < 1e-6, "{whole:?}"); + assert!((whole.center().x - 50.0).abs() < 1e-6 && (whole.center().y - 50.0).abs() < 1e-6, "{whole:?}"); + assert!(handedness(&art) > 0.0, "the art is mirrored at {turn}"); + } + // The walls seen from above and below read the right way round too. + for turn in [-90.0, 90.0] { + let n = object(CLASSIC_EXTRUDE, json!({"rotationX": turn, "mapArt": all_walls})); + assert!(handedness(&solid_art_in(Some(&d), &n).unwrap()) > 0.0, "the art is mirrored at {turn}"); + } +} + +#[test] +fn a_wall_beside_a_bevel_is_laid_out_at_its_own_length() { + let d = document(); + // A bevel 10 wide added around the square sets each wall 10 out, so each wall is 120 long; a + // bevel takes the length of the wall it sits above. Carved in, the walls are the square's own. + for (inside, length) in [(false, 120.0), (true, 100.0)] { + let solid = object(CLASSIC_EXTRUDE, json!({"bevel": "classic", "bevelHeight": 10, "bevelInside": inside})); + for side in surfaces(&solid).iter().skip(2) { + assert!((side.width - length).abs() < 1e-6, "inside {inside}: {side:?}"); + } + // Seen from one side, the art on the wall that faces the viewer keeps its size. + let walls: Vec = (3..=6).map(|k| json!({"surface": k, "symbol": "Corner"})).collect(); + let n = object(CLASSIC_EXTRUDE, json!({"bevel": "classic", "bevelHeight": 10, "bevelInside": inside, "rotationY": 90, "mapArt": walls})); + let art = solid_art_in(Some(&d), &n).unwrap(); + let whole = bounds_of(&[filled(&art, RED), filled(&art, BLUE), filled(&art, GREEN)].concat()); + assert!((whole.width() - 30.0).abs() < 1e-6 && (whole.height() - 30.0).abs() < 1e-6, "inside {inside}: {whole:?}"); + } +} + +#[test] +fn art_on_a_facet_with_a_curved_edge_is_clipped_to_that_edge() { + let quad = vec![Point::new(0.0, 0.0), Point::new(10.0, 0.0), Point::new(10.0, 10.0), Point::new(0.0, 10.0)]; + // The facet's top edge follows a curve that bows into the quad, down to y = 2. + let mut curved = BezPath::new(); + curved.move_to((0.0, 0.0)); + curved.curve_to((10.0 / 3.0, 8.0 / 3.0), (20.0 / 3.0, 8.0 / 3.0), (10.0, 0.0)); + curved.line_to((10.0, 10.0)); + curved.line_to((0.0, 10.0)); + curved.close_path(); + let facet = Facet { + contours: vec![quad.clone()], + depth: 0.0, + brightness: 1.0, + illumination: [1.0; 3], + normal: [0.0, 0.0, 1.0], + rgb_gradient: None, + outline: Some(PathData::from_bezpath(&curved)), + side: true, + away: false, + end: None, + plane: None, + surface: None, + cell: None, + }; + let cell = MapCell { surface: 0, page: quad.clone(), uv: quad.clone() }; + let whole = Rect::new(0.0, 0.0, 10.0, 10.0); + let art = Unrolled { + polygons: vec![quad], + boxes: vec![whole], + bounds: whole, + rule: FillRule::NonZero, + paint: Paint::solid(RED), + opacity: 1.0, + blend: Default::default(), + place: Affine::IDENTITY, + }; + let (mut budget, mut copies) = (MapBudget::default(), 0); + let out = cell_art(NodeId(1), &[art], &cell, &facet, &|c| c, &mut budget, &mut copies).unwrap(); + let area: f64 = out.iter().filter_map(|n| n.path_data()).map(|p| vectorcraft_geom::kurbo::Shape::area(&p.to_bezpath()).abs()).sum(); + let want = vectorcraft_geom::kurbo::Shape::area(&curved).abs(); + assert!((area - want).abs() < 1e-2, "{area} drawn, {want} inside the curved edge"); +} + +#[test] +fn a_map_on_the_back_cap_reads_the_right_way_round_from_behind() { + let d = document(); + let n = object(CLASSIC_EXTRUDE, json!({"rotationY": 180, "mapArt": [{"surface": 1, "symbol": "Corner"}, {"surface": 2, "symbol": "Corner"}]})); + let art = solid_art_in(Some(&d), &n).unwrap(); + // Only the back cap is seen. + assert_eq!(filled(&art, RED).len(), 1); + assert!(handedness(&art) > 0.0); +} + +#[test] +fn a_wall_under_a_perspective_maps_its_art_whole() { + let d = document(); + let all_walls: Vec = (3..=6).map(|k| json!({"surface": k, "symbol": "Mark"})).collect(); + let n = object(CLASSIC_EXTRUDE, json!({"rotationY": -60, "perspectiveAngle": 90, "mapArt": all_walls})); + let art = solid_art_in(Some(&d), &n).unwrap(); + // The wall is one flat face: the square maps onto it as one four-cornered area, not as two + // pieces that meet along the face's diagonal. + let marks = filled(&art, RED); + assert_eq!(marks.len(), 1); + let mark = &marks[0]; + assert_eq!((mark.subpaths.len(), mark.subpaths[0].anchors.len()), (1, 4), "{mark:?}"); + // Nearer the viewer the square's side is longer. + let side = |i: usize| mark.subpaths[0].anchors[i].p.distance(mark.subpaths[0].anchors[(i + 1) % 4].p); + let uneven = (side(0) - side(2)).abs().max((side(1) - side(3)).abs()); + assert!(uneven > 0.05, "{} {} {} {}", side(0), side(1), side(2), side(3)); +} + +#[test] +fn shade_artwork_and_invisible_geometry_change_what_is_drawn() { + let d = document(); + let params = |extra: Value| { + let mut p = json!({"surface": "diffuse", "rotationY": -60, "lightIntensity": 0, "ambient": 20, "mapArt": [{"surface": 1, "symbol": "Mark"}]}); + p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + solid_art_in(Some(&d), &object(CLASSIC_EXTRUDE, p)).unwrap() + }; + // Unshaded, the art keeps its own color on a shaded face. + assert_eq!(filled(¶ms(json!({})), RED).len(), 1); + // Shaded, it darkens toward black with its face. + let shaded = params(json!({"mapShade": true})); + assert!(filled(&shaded, RED).is_empty()); + let mut darkest = 1.0f32; + shaded.walk(&mut |n| { + for item in &n.appearance.items { + if let AppearanceItem::Fill(f) = item + && let Some([r, g, b]) = f.paint.color().map(|c| c.to_rgb()) + && g < 1e-4 + && b < 1e-4 + && r > 0.0 + { + darkest = darkest.min(r); + } + } + }); + assert!(darkest < 0.999, "the art is as dark as its face: {darkest}"); + // With Invisible Geometry only the art is drawn. + let count = |art: &Node| { + let mut paths = 0; + art.walk(&mut |n| paths += usize::from(n.path_data().is_some() && !n.appearance.items.is_empty())); + paths + }; + assert!(count(¶ms(json!({}))) > 1); + assert_eq!(count(¶ms(json!({"mapInvisible": true}))), 1); + // Without a map Invisible Geometry leaves the solid as it is, and Wireframe draws no art. + let plain = object(CLASSIC_EXTRUDE, json!({"mapInvisible": true})); + assert!(count(&solid_art_in(Some(&d), &plain).unwrap()) > 0); + assert!(filled(¶ms(json!({"surface": "wireframe"})), RED).is_empty()); +} + +#[test] +fn a_map_past_the_surfaces_draws_nothing_and_a_missing_symbol_is_left_out() { + let d = document(); + let art = |maps: Value| solid_art_in(Some(&d), &object(CLASSIC_EXTRUDE, json!({"mapArt": maps}))).unwrap(); + assert!(filled(&art(json!([{"surface": 7, "symbol": "Mark"}])), RED).is_empty()); + assert!(filled(&art(json!([{"surface": 1, "symbol": "Gone"}])), RED).is_empty()); + // A hollow solid's first surface is its first wall, so the cap's map draws nothing there. + let hollow = object(CLASSIC_EXTRUDE, json!({"cap": false, "mapArt": [{"surface": 1, "symbol": "Mark"}]})); + assert!(filled(&solid_art_in(Some(&d), &hollow).unwrap(), RED).is_empty()); + assert_eq!(missing(&d, &json!({"mapArt": [{"surface": 1, "symbol": "Gone"}]})), Some("Gone".to_string())); + assert_eq!(missing(&d, &json!({"mapArt": [{"surface": 1, "symbol": "Mark"}]})), None); +} + +#[test] +fn the_points_drawn_on_earlier_surfaces_leave_the_next_symbol_its_own_allowance() { + let d = document(); + let art = MapArt::of(Some(&d), CLASSIC_EXTRUDE, &json!({"mapArt": [{"surface": 3, "symbol": "Mark"}]})).unwrap(); + let wall = SolidSurface { kind: SurfaceKind::Wall, width: 100.0, height: 50.0, center: None }; + // Earlier surfaces drew more points on their faces than one symbol may take cut into pieces. + let mut budget = MapBudget { points: MAX_ELEMENTS + 1, ..MapBudget::default() }; + let pieces = art.unrolled(&art.maps[0], &wall, &mut budget).expect("the symbol is cut into pieces"); + assert_eq!(pieces.len(), 1); +} + +#[test] +fn art_past_the_paint_copies_allowance_leaves_the_allowance_to_later_art() { + let d = document(); + let mut b = BezPath::new(); + b.move_to((100.0, 0.0)); + b.line_to((100.0, 100.0)); + let path = PathData::from_bezpath(&b); + let gray = Paint::solid(Color::rgb(0.5, 0.5, 0.5)); + let n = Node::path(NodeId(7), path.clone(), Appearance::basic(Paint::None, gray.clone(), 1.0)); + let p = crate::merged_params( + CLASSIC_REVOLVE, + &json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0, "surface": "none", "offset": 40, "mapArt": [{"surface": 1, "symbol": "Mark"}]}), + ); + let art = MapArt::of(Some(&d), CLASSIC_REVOLVE, &p).unwrap(); + let bounds = path.bounds().unwrap(); + let options = vectorcraft_three_d::Revolve { map_surface: true, ..crate::revolve::options_of(CLASSIC_REVOLVE, &p) }; + let (width, height) = vectorcraft_three_d::revolve_surface_size(&path, bounds, options).unwrap(); + let layout = SolidLayout { first: 0, surfaces: vec![SolidSurface { kind: SurfaceKind::Side, width, height, center: None }], ends: None }; + let facets = vectorcraft_three_d::revolve_facets(&path, bounds, options).unwrap(); + // The side's art, with the copies of its paint and its points counted from `copies` and + // `budget` already used. + let draw = |copies: &mut usize, budget: &mut MapBudget| { + let mapped = crate::solids::classic::Mapped { art: &art, layout: &layout, budget, copies }; + let blend = vectorcraft_doc::color::BlendMode::Normal; + crate::solids::classic::surface(&n, facets.clone(), &gray, (1.0, blend), &p, Some(mapped), false).0 + }; + let (mut copies, mut budget) = (0, MapBudget::default()); + assert!(!filled(&draw(&mut copies, &mut budget), RED).is_empty()); + assert!(copies > 0 && budget != MapBudget::default()); + // With the allowance used up, the art is left out, and so are the copies and the points it + // would have taken. + let full = crate::revolve::MAX_PAINT_COPIES; + let (mut copies, mut budget) = (full, MapBudget::default()); + assert!(filled(&draw(&mut copies, &mut budget), RED).is_empty()); + assert_eq!(copies, full); + assert_eq!(budget, MapBudget::default()); +} + +fn missing(d: &Document, p: &Value) -> Option { + super::super::missing_symbol(d, p, None) +} + +#[test] +fn revolve_classic_wraps_its_map_around_the_side() { + let d = document(); + let mut b = BezPath::new(); + b.move_to((100.0, 0.0)); + b.line_to((100.0, 100.0)); + let mut n = Node::path(NodeId(7), PathData::from_bezpath(&b), Appearance::basic(Paint::None, Paint::solid(Color::rgb(0.5, 0.5, 0.5)), 1.0)); + let view = + json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0, "surface": "none", "offset": 40, "mapArt": [{"surface": 1, "symbol": "Corner"}]}); + n.appearance.effects.push(crate::new_effect(CLASSIC_REVOLVE, &view).unwrap()); + let art = crate::revolve_art_in(Some(&d), &n).unwrap(); + // The art is drawn at the middle of the side that faces the viewer, the right way round. + assert!(!filled(&art, RED).is_empty()); + assert!(handedness(&art) > 0.0); + let whole = bounds_of(&[filled(&art, RED), filled(&art, BLUE), filled(&art, GREEN)].concat()); + assert!((whole.center().y - 50.0).abs() < 1.0, "{whole:?}"); + // A map of another surface draws nothing. + n.appearance.effects[0].params["mapArt"] = json!([{"surface": 2, "symbol": "Corner"}]); + assert!(filled(&crate::revolve_art_in(Some(&d), &n).unwrap(), RED).is_empty()); +} + +#[test] +fn invisible_geometry_leaves_out_every_member_of_a_revolved_group() { + let d = document(); + let gray = Color::rgb(0.5, 0.5, 0.5); + let line = |id: u64, x: f64, height: f64| { + let mut b = BezPath::new(); + b.move_to((x, 0.0)); + b.line_to((x, height)); + Arc::new(Node::path(NodeId(id), PathData::from_bezpath(&b), Appearance::basic(Paint::None, Paint::solid(gray), 1.0))) + }; + // The map goes on the side of the longer member; the shorter one has none. + let art = |extra: Value| { + let mut p = + json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0, "surface": "none", "offset": 40, "mapArt": [{"surface": 1, "symbol": "Mark"}]}); + p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + let mut g = Node::group(NodeId(7), vec![line(8, 100.0, 100.0), line(9, 140.0, 30.0)]); + g.appearance.effects.push(crate::new_effect(CLASSIC_REVOLVE, &p).unwrap()); + crate::revolve_art_in(Some(&d), &g).unwrap() + }; + let shown = art(json!({})); + assert!(!filled(&shown, RED).is_empty() && !filled(&shown, gray).is_empty()); + let hidden = art(json!({"mapInvisible": true})); + assert!(!filled(&hidden, RED).is_empty()); + assert!(filled(&hidden, gray).is_empty(), "no member's faces are drawn"); + // On Wireframe the members are drawn as they are without a map. + let wire = art(json!({"mapInvisible": true, "surface": "wireframe"})); + let mut strokes = 0; + wire.walk(&mut |n| strokes += usize::from(n.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(_))))); + assert!(strokes > 0); +} + +#[test] +fn bad_maps_are_refused() { + let d = document(); + let check = |id: &str, p: Value| { + let n = object(id, json!({})); + validate_three_d_in(Some(&d), &n, id, &crate::merged_params(id, &p)) + }; + assert_eq!(check(CLASSIC_EXTRUDE, json!({"mapArt": [{"surface": 3, "symbol": "Mark", "scaleX": 50}]})), Ok(())); + assert_eq!(check(CLASSIC_REVOLVE, json!({"mapArt": [{"surface": 1, "symbol": "Mark"}], "mapShade": true})), Ok(())); + for (p, error) in [ + (json!({"mapArt": {}}), "`mapArt` must be an array"), + (json!({"mapArt": [7]}), "each of `mapArt` must be an object"), + (json!({"mapArt": [{"symbol": "Mark"}]}), "needs `surface`"), + (json!({"mapArt": [{"surface": 0, "symbol": "Mark"}]}), "needs `surface`"), + (json!({"mapArt": [{"surface": 1.5, "symbol": "Mark"}]}), "needs `surface`"), + (json!({"mapArt": [{"surface": 100001, "symbol": "Mark"}]}), "needs `surface`"), + (json!({"mapArt": [{"surface": 1}]}), "needs `symbol`"), + (json!({"mapArt": [{"surface": 1, "symbol": "Mark", "face": "front"}]}), "not `face`"), + (json!({"mapArt": [{"surface": 1, "symbol": "Mark", "scaleX": 0}]}), "scaleX must be a number from 1 to 10000"), + (json!({"mapArt": [{"surface": 1, "symbol": "Mark", "rotation": 361}]}), "rotation must be a number from -360 to 360"), + (json!({"mapArt": [{"surface": 1, "symbol": "Mark", "x": "left"}]}), "x must be a number"), + (json!({"mapArt": [{"surface": 1, "symbol": "Mark"}, {"surface": 1, "symbol": "Corner"}]}), "maps surface 1 more than once"), + (json!({"mapShade": 1}), "`mapShade` must be true or false"), + (json!({"mapInvisible": "yes"}), "`mapInvisible` must be true or false"), + ] { + for id in [CLASSIC_EXTRUDE, CLASSIC_REVOLVE] { + let e = check(id, p.clone()).unwrap_err(); + assert!(e.contains(error), "{id} {p}: {e}"); + } + } + let many: Vec = (1..=65).map(|k| json!({"surface": k, "symbol": "Mark"})).collect(); + assert!(check(CLASSIC_EXTRUDE, json!({"mapArt": many})).unwrap_err().contains("at most 64 maps")); + // Rotate (Classic) has no surface to map onto. + let e = check(CLASSIC_ROTATE, json!({"mapArt": [{"surface": 1, "symbol": "Mark"}]})).unwrap_err(); + assert!(e.contains(MAP_ART_NOT_TAKEN), "{e}"); +} + +#[test] +fn a_mapped_symbol_past_the_limits_of_a_graphics_art_is_refused() { + let mut d = document(); + // A zigzag of more straight sides than one 3D effect's graphics may draw. + let mut b = BezPath::new(); + b.move_to((0.0, 0.0)); + for i in 1..=MAX_ELEMENTS { + b.line_to((i as f64 * 0.001, (i % 2) as f64)); + } + b.close_path(); + let dense = Node::path(NodeId(0), PathData::from_bezpath(&b), Appearance::basic(Paint::solid(RED), Paint::None, 0.0)); + d.symbols.push(Symbol { dynamic: false, name: "Dense".into(), art: Arc::new(dense) }); + for id in [CLASSIC_EXTRUDE, CLASSIC_REVOLVE] { + let p = crate::merged_params(id, &json!({"mapArt": [{"surface": 1, "symbol": "Dense"}]})); + let e = validate_three_d_in(Some(&d), &object(id, json!({})), id, &p).unwrap_err(); + assert!(e.contains("too complex"), "{id}: {e}"); + } + // On a fill, as on the object. + let plain = square(7, Rect::new(0.0, 0.0, 100.0, 100.0), Color::rgb(0.5, 0.5, 0.5)); + let p = crate::merged_params(CLASSIC_REVOLVE, &json!({"mapArt": [{"surface": 1, "symbol": "Dense"}]})); + let e = validate_three_d_at_in(Some(&d), &plain, CLASSIC_REVOLVE, &p, (Some(0), 0)).unwrap_err(); + assert!(e.contains("too complex"), "{e}"); +} + +#[test] +fn maps_are_set_cleared_and_renamed_with_their_symbols() { + let p = json!({"depth": 20}); + let map = + |surface: usize, symbol: &str| SurfaceMap { surface, symbol: symbol.into(), x: 0.0, y: 0.0, scale_x: 100.0, scale_y: 100.0, rotation: 0.0 }; + let p = with_surface_map(&p, 4, Some(&map(4, "Mark"))); + let p = with_surface_map(&p, 2, Some(&map(2, "Corner"))); + let p = with_surface_map(&p, 4, Some(&map(4, "Corner"))); + // One map for a surface, in the order of the surfaces; the other parameters stay. + assert_eq!(surface_maps(&p), vec![map(2, "Corner"), map(4, "Corner")]); + assert_eq!(p["depth"], json!(20)); + assert_eq!(surface_maps(&with_surface_map(&p, 2, None)), vec![map(4, "Corner")]); + // A file's maps: entries that are not valid and a surface's second map are left out. + let loaded = json!({"mapArt": [{"surface": 1, "symbol": "Mark"}, {"surface": 1, "symbol": "Corner"}, {"surface": 0, "symbol": "Mark"}, 3]}); + assert_eq!(surface_maps(&loaded), vec![map(1, "Mark")]); + // Renaming a symbol renames it in the maps of the effects that take them. + let mut n = object(CLASSIC_EXTRUDE, json!({"mapArt": [{"surface": 1, "symbol": "Mark"}]})); + assert_eq!(super::super::graphic_symbols(&n), vec!["Mark".to_string()]); + assert!(super::super::rename_graphic_symbol(&mut n, "Mark", "Logo")); + assert_eq!(surface_maps(&n.appearance.effects[0].params)[0].symbol, "Logo"); + // Scale to Fit fills the surface: each side by its own scale when the art is square to it. + assert_eq!(map(1, "Mark").fitting_scales(Rect::new(0.0, 0.0, 10.0, 10.0), (100.0, 50.0)), Some((1000.0, 500.0))); + let turned = SurfaceMap { rotation: 90.0, ..map(1, "Mark") }; + assert_eq!(turned.fitting_scales(Rect::new(0.0, 0.0, 10.0, 20.0), (100.0, 50.0)), Some((500.0, 500.0))); + let aslant = SurfaceMap { rotation: 45.0, ..map(1, "Mark") }; + let (sx, sy) = aslant.fitting_scales(Rect::new(0.0, 0.0, 10.0, 10.0), (100.0, 50.0)).unwrap(); + assert!((sx - sy).abs() < 1e-9 && (sx - 50.0 / (20.0 * 0.5f64.sqrt()) * 100.0).abs() < 1e-6, "{sx} {sy}"); + assert_eq!(map(1, "Mark").fitting_scales(Rect::new(0.0, 0.0, 0.0, 10.0), (100.0, 50.0)), None); +} diff --git a/crates/engine/src/cmd/brushsym.rs b/crates/engine/src/cmd/brushsym.rs index c026a1086e..5a4b8931d5 100644 --- a/crates/engine/src/cmd/brushsym.rs +++ b/crates/engine/src/cmd/brushsym.rs @@ -220,7 +220,7 @@ pub fn specs() -> Vec { "Symbol Options…", [], None, - "{name?, newName?, registration?: 0..8, exportType?: movieClip|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static|dynamic, alignToPixelGrid?: bool} rename a symbol (its instances and the graphics mapped onto 3D objects follow the new name) and/or set Symbol Options › Registration, Export Type, 9-slice guides (nineSliceGuides [left, top, right, bottom] fractions in from each edge, each -16..16, with left + right < 1 and top + bottom < 1), Symbol Type (a dynamic symbol's instances may change the appearance of objects in its art and stay linked; making it static drops those changes) and Align to Pixel Grid (on: the horizontal and vertical straight segments of the paths in the symbol's art snap to whole points, or half points for an odd centered stroke, at the symbol's natural size, its stroke weights become whole points, and every instance placed at that size, reflected across one axis or not, moves to whole points and goes back to them after each move; a scaled, rotated (a half turn included) or sheared instance, and an instance in another symbol's art, is left where it is; the art snaps again after it is edited); alignToPixelGrid alone with the value the symbol already has changes nothing and adds no undo step; default name: current → {name, registration, exportType, nineSlice, type, alignToPixelGrid}", + "{name?, newName?, registration?: 0..8, exportType?: movieClip|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static|dynamic, alignToPixelGrid?: bool} rename a symbol (its instances and the graphics and Map Art maps on 3D objects follow the new name) and/or set Symbol Options › Registration, Export Type, 9-slice guides (nineSliceGuides [left, top, right, bottom] fractions in from each edge, each -16..16, with left + right < 1 and top + bottom < 1), Symbol Type (a dynamic symbol's instances may change the appearance of objects in its art and stay linked; making it static drops those changes) and Align to Pixel Grid (on: the horizontal and vertical straight segments of the paths in the symbol's art snap to whole points, or half points for an odd centered stroke, at the symbol's natural size, its stroke weights become whole points, and every instance placed at that size, reflected across one axis or not, moves to whole points and goes back to them after each move; a scaled, rotated (a half turn included) or sheared instance, and an instance in another symbol's art, is left where it is; the art snaps again after it is edited); alignToPixelGrid alone with the value the symbol already has changes nothing and adds no undo step; default name: current → {name, registration, exportType, nineSlice, type, alignToPixelGrid}", has_doc, symbol_options ), @@ -338,7 +338,7 @@ pub fn specs() -> Vec { "Select All Unused", [], None, - "{} → {names: [the symbols nothing places, in panel order]} (the Symbols panel selects them): instances in the art (opacity masks included), graphics mapped onto 3D objects (threeD.mapGraphic), graph designs, pattern tiles (with the tiles that pattern editing's Cancel puts back) and brush art count, and so do instances in the art of a symbol that is used", + "{} → {names: [the symbols nothing places, in panel order]} (the Symbols panel selects them): instances in the art (opacity masks included), graphics and Map Art maps on 3D objects (threeD.mapGraphic, threeD.mapArt), graph designs, pattern tiles (with the tiles that pattern editing's Cancel puts back) and brush art count, and so do instances in the art of a symbol that is used", has_doc, symbol_unused ), diff --git a/crates/engine/src/cmd/clipboard/resources.rs b/crates/engine/src/cmd/clipboard/resources.rs index 04bd35cae8..0c2e3888e7 100644 --- a/crates/engine/src/cmd/clipboard/resources.rs +++ b/crates/engine/src/cmd/clipboard/resources.rs @@ -681,11 +681,19 @@ impl Relink { } } } - // A 3D effect's mapped graphics follow their symbols' names in the document. Each name is - // looked up once, so renames that chain (A to B, B to C) do not apply twice. + // A 3D effect's mapped graphics and Map Art maps follow their symbols' names in the + // document. Each name is looked up once, so renames that chain (A to B, B to C) do not + // apply twice. let items = a.items.iter_mut().flat_map(|i| i.effects_mut().iter_mut()); - for e in a.effects.iter_mut().chain(items).filter(|e| vectorcraft_render::effects::takes_graphics(&e.id)) { - let list = e.params.get_mut(vectorcraft_render::effects::GRAPHICS).and_then(Value::as_array_mut); + for e in a.effects.iter_mut().chain(items) { + let key = if vectorcraft_render::effects::takes_graphics(&e.id) { + vectorcraft_render::effects::GRAPHICS + } else if vectorcraft_render::effects::takes_map_art(&e.id) { + vectorcraft_render::effects::MAP_ART + } else { + continue; + }; + let list = e.params.get_mut(key).and_then(Value::as_array_mut); for g in list.into_iter().flatten() { if let Some(Value::String(s)) = g.get_mut("symbol") { self.name(Res::Symbol, s); diff --git a/crates/engine/src/cmd/effectcmd/graphics.rs b/crates/engine/src/cmd/effectcmd/graphics.rs index 868f6f5c5c..fe97de4765 100644 --- a/crates/engine/src/cmd/effectcmd/graphics.rs +++ b/crates/engine/src/cmd/effectcmd/graphics.rs @@ -32,6 +32,15 @@ pub(super) fn specs() -> Vec { has_doc, map_graphic ), + cmd!( + "threeD.mapArt", + "Map Art", + [], + None, + "{surface?: integer (1..the object's surface count: Extrude & Bevel (Classic) numbers each solid's front cap and back cap (none on a hollow solid, cap false), then each side wall from corner to corner of the outline, then the bevel above each wall; Revolve (Classic)'s swept side is surface 1, in a group the side of the member with the longest profile, and the other members take no map), symbol?: name of a document symbol|null (with surface: the symbol mapped onto it; null removes the surface's map, also a map kept past the surface count, and is refused with x, y, scaleX, scaleY, rotation or fit true; omitted: the surface's map keeps its symbol, and a surface with no map is refused), x?: pt, y?: pt (-1000000..1000000; the offset of the art's center from the center of the surface laid out flat; a new map starts at 0, 0), scaleX?: %, scaleY?: % (1..10000; of the symbol's own width and height; a new map starts at 100), rotation?: degrees (-360..360; counterclockwise; a new map starts at 0), fit?: bool (false; true is Scale to Fit: the art is centered and scaled to fill the surface, each side on its own when the art is square to the surface, else in proportion; art with no area keeps its scales), clearAll?: bool (false; true removes every map first, so with surface only that surface's map is left), shade?: bool (Shade Artwork: the mapped art takes the tone and highlight of its face), invisible?: bool (Invisible Geometry: with at least one map, only the mapped art is drawn), index?: int (the 3D effect's position; default: each object's first Extrude & Bevel (Classic) or Revolve (Classic), its own before its fills' and strokes'), item?: appearance item index|null (refused without index; as effect.setParams), ids?|id?} set, edit or remove the art mapped onto the numbered surfaces of each selected object's 3D effect, which must be Extrude & Bevel (Classic) or Revolve (Classic) (Rotate (Classic) takes no map); one of surface, clearAll, shade or invisible is required; the maps are the effect's mapArt, mapShade and mapInvisible parameters; one undo step, and none when nothing changes → {ids: [the objects changed], maps: [the first object's maps]}", + has_doc, + map_art + ), ] } @@ -158,6 +167,176 @@ fn map_graphic(s: &mut Session, p: &Value) -> Result { Ok(json!({ "ids": ids_json(&ids), "graphic": first })) } +/// The effect of `n` that Map Art edits when none is named: its first Extrude & Bevel (Classic) or +/// Revolve (Classic), its own before its fills' and strokes'. +fn first_mapped(n: &Node) -> Option<(Option, usize)> { + let at = |fx: &[Effect]| fx.iter().position(|e| effects::takes_map_art(&e.id)); + at(&n.appearance.effects) + .map(|i| (None, i)) + .or_else(|| n.appearance.items.iter().enumerate().find_map(|(k, item)| at(item.effects()).map(|i| (Some(k), i)))) +} + +/// `threeD.mapArt`: sets, edits or removes the maps of each target's classic 3D effect, after +/// checking that every target takes the change. Nothing is recorded when no target changes. +fn map_art(s: &mut Session, p: &Value) -> Result { + const C: &str = "threeD.mapArt"; + const PLACING: [&str; 6] = ["symbol", "x", "y", "scaleX", "scaleY", "rotation"]; + const KEYS: [&str; 15] = + ["surface", "symbol", "x", "y", "scaleX", "scaleY", "rotation", "fit", "clearAll", "shade", "invisible", "index", "item", "ids", "id"]; + if let Some(key) = p.as_object().and_then(|m| m.keys().find(|k| !KEYS.contains(&k.as_str()))) { + return Err(bad(C, format!("unknown parameter `{key}`"))); + } + if p.get("item").is_some() && p.get("index").is_none() { + return Err(bad(C, "`item` needs `index`")); + } + let surface = match p.get("surface") { + None => None, + Some(v) => Some( + v.as_u64() + .and_then(|n| usize::try_from(n).ok()) + .filter(|n| (1..=effects::MAX_MAP_SURFACE).contains(n)) + .ok_or_else(|| bad(C, "`surface` must be a whole number from 1 to the object's surface count"))?, + ), + }; + let fit = super::super::switch_or(p, "fit", false, C)?; + let clear_all = super::super::switch_or(p, "clearAll", false, C)?; + let flag = |key: &str| -> Result> { + match p.get(key) { + None => Ok(None), + Some(_) => super::super::switch_or(p, key, false, C).map(Some), + } + }; + let (shade, invisible) = (flag("shade")?, flag("invisible")?); + match surface { + None if fit || PLACING.iter().any(|k| p.get(*k).is_some()) => { + return Err(bad(C, "`symbol`, `x`, `y`, `scaleX`, `scaleY`, `rotation` and `fit` need `surface`")); + } + None if !clear_all && shade.is_none() && invisible.is_none() => { + return Err(bad(C, "give `surface`, `clearAll`, `shade` or `invisible`")); + } + _ => {} + } + let removes = p.get("symbol").is_some_and(Value::is_null); + if removes && (fit || PLACING[1..].iter().any(|k| p.get(*k).is_some())) { + return Err(bad(C, "`symbol: null` removes the map: leave out `x`, `y`, `scaleX`, `scaleY`, `rotation` and `fit`")); + } + let d = &s.doc()?.doc; + let targets: Vec<(NodeId, Option, usize)> = if p.get("index").is_some() { + let index = index_param(p, "index", C)?; + let item = item_target(s, p, C)?; + effect_targets(s, p, item, index, C)? + } else { + let mut out = vec![]; + for id in edit_targets(s, p, C)? { + let found = d.node(id).and_then(first_mapped); + let (item, index) = found.ok_or_else(|| bad(C, format!("object {}: {}", id.0, effects::MAP_ART_NOT_TAKEN)))?; + out.push((id, item, index)); + } + out + }; + if targets.is_empty() { + return Err(bad(C, "select an object with a 3D effect")); + } + let mut edits = Vec::with_capacity(targets.len()); + for &(id, item, index) in &targets { + let n = d.node(id).ok_or(EngineError::NoNode(id))?; + let Some(effect) = n.appearance.effects_at(item).and_then(|fx| fx.get(index)).filter(|e| effects::is_three_d(&e.id)) else { + return Err(bad(C, format!("object {} needs a 3D effect at index {index}", id.0))); + }; + if !effects::takes_map_art(&effect.id) { + return Err(bad(C, format!("object {}: {}", id.0, effects::MAP_ART_NOT_TAKEN))); + } + let merged = effects::merged_params(&effect.id, &effect.params); + let mut params = merged.clone(); + if clear_all { + params[effects::MAP_ART] = json!([]); + } + if let Some(surface) = surface { + // Art that can't be built has no surfaces: the effect's own check says why. + let surfaces = match effects::map_surfaces_at(Some(d), n, item, index) { + Some(surfaces) => surfaces, + None => { + effects::validate_three_d_at_in(Some(d), n, &effect.id, &merged, (item, index)).map_err(|e| bad(C, e))?; + vec![] + } + }; + // Read before clearAll empties the list, so with clearAll the surface keeps its map. + let current = effects::surface_maps(&merged).into_iter().find(|m| m.surface == surface); + // A map kept past the surface count (the solid lost surfaces) can still be removed. + let flat = surfaces.get(surface - 1); + if flat.is_none() && !(removes && current.is_some()) { + return Err(bad(C, format!("object {}: `surface` must be from 1 to {}, the object's surface count", id.0, surfaces.len()))); + } + if removes { + params = effects::with_surface_map(¶ms, surface, None); + } else if let Some(flat) = flat { + // The values given go over the surface's map, or over a new map's defaults. + let mut given = match (¤t, p.get("symbol")) { + (Some(m), _) => m.to_value(), + (None, Some(_)) => json!({ "surface": surface }), + (None, None) => return Err(bad(C, format!("object {}: surface {surface} has no map: give `symbol`", id.0))), + }; + for key in PLACING { + if let Some(v) = p.get(key) { + given[key] = v.clone(); + } + } + let mut map = effects::SurfaceMap::from_value(&given).map_err(|e| bad(C, e))?; + if !d.symbols.iter().any(|sym| sym.name == map.symbol) && current.as_ref().is_none_or(|m| m.symbol != map.symbol) { + return Err(bad(C, format!("no symbol named `{}`", map.symbol))); + } + if fit { + // Art or a surface with no area has no size to fit: the map is centered and + // keeps its scales. + let scales = effects::graphic_bounds(d, &map.symbol).and_then(|art| map.fitting_scales(art, (flat.width, flat.height))); + let (scale_x, scale_y) = scales.unwrap_or((map.scale_x, map.scale_y)); + map = effects::SurfaceMap { x: 0.0, y: 0.0, scale_x, scale_y, ..map }; + } + params = effects::with_surface_map(¶ms, surface, Some(&map)); + } + } + for (key, value) in [(effects::MAP_SHADE, shade), (effects::MAP_INVISIBLE, invisible)] { + if let Some(on) = value { + params[key] = json!(on); + } + } + effects::validate_three_d_at_in(Some(d), n, &effect.id, ¶ms, (item, index)).map_err(|e| bad(C, e))?; + let state = |p: &Value| { + let on = |key: &str| p.get(key).and_then(Value::as_bool).unwrap_or(false); + (effects::surface_maps(p), on(effects::MAP_SHADE), on(effects::MAP_INVISIBLE)) + }; + let maps: Vec = effects::surface_maps(¶ms).iter().map(effects::SurfaceMap::to_value).collect(); + let changed = state(¶ms) != state(&merged); + edits.push((id, item, index, params, changed, maps)); + } + let first = edits.first().map(|(.., maps)| maps.clone()).unwrap_or_default(); + if !edits.iter().any(|(.., changed, _)| *changed) { + return Ok(json!({ "ids": [], "maps": first })); + } + let ids = s.edit("Map Art", |d, _| { + let mut done = vec![]; + for (id, item, index, params, changed, _) in &edits { + let Some(e) = d.node_mut(*id).and_then(|n| n.appearance.effects_mut(*item)).and_then(|fx| fx.get_mut(*index)).filter(|_| *changed) else { + continue; + }; + let mut current = effects::upgrade_params(&e.id, &e.params); + for key in [effects::MAP_ART, effects::MAP_SHADE, effects::MAP_INVISIBLE] { + if let (Some(v), Some(m)) = (params.get(key), current.as_object_mut()) { + m.insert(key.into(), v.clone()); + } + } + e.params = current; + done.push(*id); + } + Ok(done) + })?; + Ok(json!({ "ids": ids_json(&ids), "maps": first })) +} + #[cfg(test)] #[path = "graphics_tests.rs"] mod tests; + +#[cfg(test)] +#[path = "map_art_tests.rs"] +mod map_art_tests; diff --git a/crates/engine/src/cmd/effectcmd/map_art_tests.rs b/crates/engine/src/cmd/effectcmd/map_art_tests.rs new file mode 100644 index 0000000000..d20033cda4 --- /dev/null +++ b/crates/engine/src/cmd/effectcmd/map_art_tests.rs @@ -0,0 +1,241 @@ +#![allow(clippy::unwrap_used, clippy::panic)] +use serde_json::{Value, json}; +use vectorcraft_doc::NodeId; + +use crate::Session; + +/// A 100 × 100 square with `effect` seen straight on, and a 10 × 20 red rectangle beside it kept +/// as symbol "Mark" (11 × 21 with its stroke). +fn setup(effect: &str) -> (Session, NodeId) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width":400,"height":400})).unwrap(); + let mark = s.execute("path.create", &json!({"d":"M300 300L310 300L310 320L300 320Z"})).unwrap()["id"].clone(); + s.execute("paint.setFill", &json!({"color":"#ff0000"})).unwrap(); + s.execute("threeD.addGraphic", &json!({"name": "Mark", "ids": [mark]})).unwrap(); + let id = NodeId(s.execute("path.create", &json!({"d":"M100 100L200 100L200 200L100 200Z"})).unwrap()["id"].as_u64().unwrap()); + s.execute("paint.setFill", &json!({"color":"#338ad6"})).unwrap(); + s.execute("effect.apply", &json!({"effect":effect,"item":null,"params":{"rotationX":0.0,"rotationY":0.0,"rotationZ":0.0}})).unwrap(); + (s, id) +} + +fn params(s: &Session, id: NodeId) -> Value { + s.doc().unwrap().doc.node(id).unwrap().appearance.effects[0].params.clone() +} + +fn undo_len(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +fn map(surface: u64, x: f64, scale: (f64, f64), rotation: f64) -> Value { + json!({"surface": surface, "symbol": "Mark", "x": x, "y": 0.0, "scaleX": scale.0, "scaleY": scale.1, "rotation": rotation}) +} + +#[test] +fn map_art_sets_edits_and_removes_a_surfaces_map_one_undo_step_each() { + let (mut s, id) = setup("threeD.classicExtrude"); + let before = s.doc().unwrap().doc.clone(); + let history = undo_len(&s); + let r = s.execute("threeD.mapArt", &json!({"surface": 1, "symbol": "Mark", "x": 5.0, "rotation": 30.0})).unwrap(); + assert_eq!(r["ids"], json!([id.0])); + assert_eq!(r["maps"], json!([map(1, 5.0, (100.0, 100.0), 30.0)])); + assert_eq!(params(&s, id)["mapArt"], json!([map(1, 5.0, (100.0, 100.0), 30.0)])); + assert_eq!(undo_len(&s), history + 1); + // Without a symbol the surface's map keeps its own, and only the values given change. + s.execute("threeD.mapArt", &json!({"surface": 1, "scaleX": 50.0})).unwrap(); + assert_eq!(params(&s, id)["mapArt"], json!([map(1, 5.0, (50.0, 100.0), 30.0)])); + // Another surface takes a map of its own, kept in the order of the surfaces. + s.execute("threeD.mapArt", &json!({"surface": 4, "symbol": "Mark"})).unwrap(); + s.execute("threeD.mapArt", &json!({"surface": 2, "symbol": "Mark"})).unwrap(); + let surfaces: Vec = params(&s, id)["mapArt"].as_array().unwrap().iter().map(|m| m["surface"].as_u64().unwrap()).collect(); + assert_eq!(surfaces, [1, 2, 4]); + // Shade Artwork and Invisible Geometry are the effect's own flags. + s.execute("threeD.mapArt", &json!({"shade": true, "invisible": true})).unwrap(); + assert_eq!((params(&s, id)["mapShade"].clone(), params(&s, id)["mapInvisible"].clone()), (json!(true), json!(true))); + // A null symbol clears one surface, and clearAll every surface. + s.execute("threeD.mapArt", &json!({"surface": 2, "symbol": null})).unwrap(); + assert_eq!(params(&s, id)["mapArt"].as_array().unwrap().len(), 2); + let r = s.execute("threeD.mapArt", &json!({"clearAll": true})).unwrap(); + assert_eq!((r["maps"].clone(), params(&s, id)["mapArt"].clone()), (json!([]), json!([]))); + // With a surface, clearAll leaves that surface's new map alone. + s.execute("threeD.mapArt", &json!({"surface": 1, "symbol": "Mark"})).unwrap(); + s.execute("threeD.mapArt", &json!({"surface": 3, "symbol": "Mark", "clearAll": true})).unwrap(); + assert_eq!(params(&s, id)["mapArt"], json!([map(3, 0.0, (100.0, 100.0), 0.0)])); + // Without a symbol, clearAll keeps the surface's own map and edits it. + s.execute("threeD.mapArt", &json!({"surface": 1, "symbol": "Mark"})).unwrap(); + s.execute("threeD.mapArt", &json!({"surface": 3, "x": 4.0, "clearAll": true})).unwrap(); + assert_eq!(params(&s, id)["mapArt"], json!([map(3, 4.0, (100.0, 100.0), 0.0)])); + assert_eq!(undo_len(&s), history + 11); + for _ in 0..11 { + s.execute("edit.undo", &json!({})).unwrap(); + } + assert_eq!(s.doc().unwrap().doc.layers, before.layers); +} + +#[test] +fn a_map_past_the_surface_count_can_still_be_removed() { + let (mut s, id) = setup("threeD.classicExtrude"); + s.execute("threeD.mapArt", &json!({"surface": 1, "symbol": "Mark"})).unwrap(); + s.execute("threeD.mapArt", &json!({"surface": 6, "symbol": "Mark"})).unwrap(); + // With no depth the solid is a plane with fewer surfaces, and the map of surface 6 stays. + s.execute("effect.setParams", &json!({"index": 0, "item": null, "params": {"depth": 0}})).unwrap(); + let e = s.execute("threeD.mapArt", &json!({"surface": 6, "symbol": "Mark", "x": 3.0})).unwrap_err().to_string(); + assert!(e.contains("the object's surface count"), "{e}"); + s.execute("threeD.mapArt", &json!({"surface": 6, "symbol": null})).unwrap(); + assert_eq!(params(&s, id)["mapArt"], json!([map(1, 0.0, (100.0, 100.0), 0.0)])); + // A surface past the count with no map is still refused. + let e = s.execute("threeD.mapArt", &json!({"surface": 9, "symbol": null})).unwrap_err().to_string(); + assert!(e.contains("the object's surface count"), "{e}"); +} + +#[test] +fn scale_to_fit_centers_the_art_and_fills_the_surface() { + let (mut s, id) = setup("threeD.classicExtrude"); + // The cap is 100 × 100 and the symbol's art 11 × 21. + s.execute("threeD.mapArt", &json!({"surface": 1, "symbol": "Mark", "x": 20.0, "y": 3.0, "fit": true})).unwrap(); + let m = ¶ms(&s, id)["mapArt"][0]; + assert_eq!((m["x"].as_f64(), m["y"].as_f64()), (Some(0.0), Some(0.0))); + assert!((m["scaleX"].as_f64().unwrap() - 100.0 / 11.0 * 100.0).abs() < 1e-6, "{m}"); + assert!((m["scaleY"].as_f64().unwrap() - 100.0 / 21.0 * 100.0).abs() < 1e-6, "{m}"); + // A side wall is 100 along the outline and as deep as the solid, 50. + s.execute("threeD.mapArt", &json!({"surface": 3, "symbol": "Mark", "fit": true})).unwrap(); + let m = ¶ms(&s, id)["mapArt"][1]; + assert!((m["scaleY"].as_f64().unwrap() - 50.0 / 21.0 * 100.0).abs() < 1e-6, "{m}"); +} + +#[test] +fn a_change_that_changes_nothing_records_no_undo_step() { + let (mut s, id) = setup("threeD.classicExtrude"); + s.execute("threeD.mapArt", &json!({"surface": 1, "symbol": "Mark"})).unwrap(); + let history = undo_len(&s); + let same = params(&s, id); + for p in [ + json!({"surface": 1, "symbol": "Mark"}), + json!({"surface": 1, "x": 0.0, "scaleX": 100.0}), + json!({"surface": 2, "symbol": null}), + json!({"shade": false}), + json!({"invisible": false}), + ] { + let r = s.execute("threeD.mapArt", &p).unwrap(); + assert_eq!(r["ids"], json!([]), "{p}"); + assert_eq!((undo_len(&s), params(&s, id)), (history, same.clone()), "{p}"); + } + // Clearing an object with no map records nothing either. + let (mut s, _) = setup("threeD.classicRevolve"); + let history = undo_len(&s); + assert_eq!(s.execute("threeD.mapArt", &json!({"clearAll": true})).unwrap()["ids"], json!([])); + assert_eq!(undo_len(&s), history); +} + +#[test] +fn bad_surfaces_symbols_and_values_are_refused() { + let (mut s, id) = setup("threeD.classicExtrude"); + let history = undo_len(&s); + let maps = params(&s, id)["mapArt"].clone(); + for (p, error) in [ + (json!({}), "give `surface`, `clearAll`, `shade` or `invisible`"), + (json!({"surface": 0, "symbol": "Mark"}), "`surface` must be a whole number"), + (json!({"surface": 1.5, "symbol": "Mark"}), "`surface` must be a whole number"), + (json!({"surface": "front", "symbol": "Mark"}), "`surface` must be a whole number"), + // The fill's solid has 6 surfaces and the stroke's, a square ring, 10: two caps and the + // four walls of each of its two outlines. + (json!({"surface": 17, "symbol": "Mark"}), "`surface` must be from 1 to 16"), + (json!({"surface": 1, "symbol": "Gone"}), "no symbol named `Gone`"), + (json!({"surface": 1, "symbol": 3}), "needs `symbol`"), + (json!({"surface": 1}), "surface 1 has no map: give `symbol`"), + (json!({"surface": 1, "symbol": "Mark", "scaleX": 0}), "scaleX must be a number from 1 to 10000"), + (json!({"surface": 1, "symbol": "Mark", "scaleY": 10001}), "scaleY must be a number from 1 to 10000"), + (json!({"surface": 1, "symbol": "Mark", "rotation": -361}), "rotation must be a number from -360 to 360"), + (json!({"surface": 1, "symbol": "Mark", "x": 1e7}), "x must be a number"), + (json!({"surface": 1, "symbol": "Mark", "y": "up"}), "y must be a number"), + (json!({"surface": 1, "symbol": "Mark", "fit": 1}), "fit"), + (json!({"surface": 1, "symbol": null, "x": 4.0}), "`symbol: null` removes the map"), + (json!({"surface": 1, "symbol": null, "rotation": 30.0}), "`symbol: null` removes the map"), + (json!({"surface": 1, "symbol": null, "fit": true}), "`symbol: null` removes the map"), + (json!({"symbol": "Mark"}), "need `surface`"), + (json!({"fit": true}), "need `surface`"), + (json!({"shade": "on"}), "shade"), + (json!({"invisible": 1}), "invisible"), + (json!({"clearAll": "yes"}), "clearAll"), + (json!({"surface": 1, "symbol": "Mark", "face": "front"}), "unknown parameter `face`"), + (json!({"surface": 1, "symbol": "Mark", "item": null}), "`item` needs `index`"), + (json!({"surface": 1, "symbol": "Mark", "index": 3}), "needs a 3D effect at index 3"), + ] { + let e = s.execute("threeD.mapArt", &p).unwrap_err().to_string(); + assert!(e.contains(error), "{p}: {e}"); + } + assert_eq!((undo_len(&s), params(&s, id)["mapArt"].clone()), (history, maps)); + // Revolve (Classic) has one surface, and the other 3D effects take no map. + let (mut s, _) = setup("threeD.classicRevolve"); + s.execute("threeD.mapArt", &json!({"surface": 1, "symbol": "Mark"})).unwrap(); + let e = s.execute("threeD.mapArt", &json!({"surface": 2, "symbol": "Mark"})).unwrap_err().to_string(); + assert!(e.contains("`surface` must be from 1 to 1"), "{e}"); + for effect in ["threeD.classicRotate", "threeD.extrude", "threeD.revolve"] { + let (mut s, _) = setup(effect); + for p in [json!({"surface": 1, "symbol": "Mark"}), json!({"surface": 1, "symbol": "Mark", "index": 0})] { + let e = s.execute("threeD.mapArt", &p).unwrap_err().to_string(); + assert!(e.contains("Map Art maps symbols onto Extrude & Bevel (Classic) and Revolve (Classic)"), "{effect}: {e}"); + } + // The effect's own parameters refuse a map too. + let e = s.execute("effect.setParams", &json!({"index": 0, "item": null, "params": {"mapArt": [{"surface": 1, "symbol": "Mark"}]}})); + assert!(e.is_err(), "{effect}"); + } +} + +#[test] +fn a_mapped_symbol_is_drawn_expanded_renamed_and_kept_in_use() { + let (mut s, id) = setup("threeD.classicExtrude"); + s.execute("threeD.mapArt", &json!({"surface": 1, "symbol": "Mark", "scaleX": 300.0})).unwrap(); + // effect.setParams takes the same maps and refuses a symbol the document does not have. + let e = s.execute("effect.setParams", &json!({"index": 0, "item": null, "params": {"mapArt": [{"surface": 1, "symbol": "Gone"}]}})); + assert!(e.unwrap_err().to_string().contains("Gone")); + // The symbol counts as used, and renaming it renames it in the map. + assert_eq!(s.execute("symbol.unused", &json!({})).unwrap()["names"], json!([])); + s.execute("symbol.options", &json!({"name": "Mark", "newName": "Logo"})).unwrap(); + assert_eq!(params(&s, id)["mapArt"][0]["symbol"], "Logo"); + // Expand Appearance keeps the mapped art: the red fill is among the expanded paths. + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("effect.expandAppearance", &json!({})).unwrap(); + let d = &s.doc().unwrap().doc; + let mut red = 0; + for l in &d.layers { + l.walk(&mut |n| { + for item in &n.appearance.items { + if let vectorcraft_doc::AppearanceItem::Fill(f) = item + && f.paint.color().is_some_and(|c| c.to_rgb()[0] > 0.9 && c.to_rgb()[1] < 0.1 && c.to_rgb()[2] < 0.1) + && n.visual_bounds().is_some_and(|b| b.x0 < 250.0) + { + red += 1; + } + } + }); + } + assert!(red > 0, "the expanded art holds the mapped symbol's red fill"); +} + +#[test] +fn pasted_into_another_document_a_map_brings_its_symbol() { + let (mut s, id) = setup("threeD.classicExtrude"); + s.execute("threeD.mapArt", &json!({"surface": 1, "symbol": "Mark"})).unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + // The symbol the pasted object's map names, and the size of that symbol's art. + let pasted = |s: &mut Session| { + s.execute("edit.paste", &json!({})).unwrap(); + let st = s.doc().unwrap(); + let n = st.doc.node(st.selection.objects[0]).unwrap(); + let name = n.appearance.effects[0].params["mapArt"][0]["symbol"].as_str().unwrap().to_string(); + let size = vectorcraft_render::effects::graphic_bounds(&st.doc, &name).map(|r| (r.width(), r.height())); + (name, size) + }; + // A document without the symbol gets it. + s.execute("file.new", &json!({"width":400,"height":400})).unwrap(); + assert_eq!(pasted(&mut s), ("Mark".to_string(), Some((11.0, 21.0)))); + // A document whose symbol "Mark" is other art gets the copied symbol under a free name, and + // the map names it. + s.execute("file.new", &json!({"width":400,"height":400})).unwrap(); + let other = s.execute("path.create", &json!({"d":"M0 0L50 0L50 50L0 50Z"})).unwrap()["id"].clone(); + s.execute("threeD.addGraphic", &json!({"name": "Mark", "ids": [other]})).unwrap(); + let (name, size) = pasted(&mut s); + assert_ne!(name, "Mark"); + assert_eq!(size, Some((11.0, 21.0))); +} diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 0f462add09..20f00fc112 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -658,6 +658,7 @@ pub(super) const ALLOWED: &[&str] = &[ "text.thread.remove", "text.touchType", "threeD.addGraphic", + "threeD.mapArt", "threeD.mapGraphic", "transparency.disableOpacityMask", "transparency.editOpacityMask", diff --git a/crates/three-d/src/lib.rs b/crates/three-d/src/lib.rs index c6b00ed851..fc875fd8f2 100644 --- a/crates/three-d/src/lib.rs +++ b/crates/three-d/src/lib.rs @@ -12,8 +12,9 @@ pub mod fold; mod solid; mod visibility; pub use solid::{ - Bevel, BevelShape, DepthPlane, Extrude, FaceMap, Facet, Inflate, MeshFace, PlanarFace, TOO_COMPLEX_SOLID, View, extrude, extrude_face_map, - extrude_mesh_face, extrude_side_size, inflate, inflate_each, inflate_together, plane, plane_face_map, plane_mesh_face, + Bevel, BevelShape, DepthPlane, Extrude, FaceMap, Facet, Inflate, MapCell, MeshFace, PlanarFace, SolidSurface, SurfaceKind, TOO_COMPLEX_SOLID, + View, extrude, extrude_face_map, extrude_mesh_face, extrude_side_size, extrude_surfaces, inflate, inflate_each, inflate_together, plane, + plane_face_map, plane_mesh_face, }; pub use visibility::{VisibleFace, visible_faces}; mod shading; diff --git a/crates/three-d/src/solid.rs b/crates/three-d/src/solid.rs index 5029a79910..0ea03dcbf9 100644 --- a/crates/three-d/src/solid.rs +++ b/crates/three-d/src/solid.rs @@ -28,7 +28,7 @@ pub(crate) use build::PLANES; #[cfg(test)] use build::{Camera, cuts, edge_distance, newell, section}; pub(crate) use build::{Face3, Keep, extrude_faces, plane_faces}; -pub use build::{extrude, extrude_side_size, plane}; +pub use build::{extrude, extrude_side_size, extrude_surfaces, plane}; pub use face_map::{FaceMap, MeshFace, extrude_face_map, extrude_mesh_face, plane_face_map, plane_mesh_face}; #[cfg(test)] use inflate::GRID_WORK; @@ -219,6 +219,9 @@ pub struct Extrude { /// Keep the faces of a closed solid that are turned away from the viewer (Draw Hidden Faces, /// and the classic Wireframe surface), drawn behind the faces turned toward it. pub hidden: bool, + /// Lay out the solid's numbered surfaces ([`extrude_surfaces`]): each facet of a wall or a + /// bevel band then carries its [`MapCell`]. A solid with a twist or a taper has none. + pub map_surfaces: bool, /// Graphics are mapped onto the side: the pieces of the walls and bevels of the solid's longest /// contour carry a [`Facet::surface`]. Off by default, which leaves the facets without one. pub map_surface: bool, @@ -226,10 +229,44 @@ pub struct Extrude { impl Default for Extrude { fn default() -> Self { - Self { depth: 50.0, twist: 0.0, taper: 1.0, cap: true, bevel: None, hidden: false, map_surface: false } + Self { depth: 50.0, twist: 0.0, taper: 1.0, cap: true, bevel: None, hidden: false, map_surfaces: false, map_surface: false } } } +/// Where a facet lies on one of its solid's numbered surfaces, laid out flat: the surface's index, +/// the facet's corners on the page, and the point of the flat surface at each corner, in points +/// (x along the surface from its left edge as it is seen from outside the solid, y from the edge +/// nearer the front of the solid). +#[derive(Clone, Debug, PartialEq)] +pub struct MapCell { + pub surface: usize, + pub page: Vec, + pub uv: Vec, +} + +/// What a numbered surface of a solid is. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SurfaceKind { + /// The front or back cap, or a plane's only face. + End(PlanarFace), + /// A side wall: the part of the side between two corners of the outline. + Wall, + /// The bevel between the front cap and a side wall. + Bevel, + /// Revolve's swept side. + Side, +} + +/// One numbered surface of a solid: its kind and its size laid out flat, in points. An end also +/// has the center of its bounds in the art's plane. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct SolidSurface { + pub kind: SurfaceKind, + pub width: f64, + pub height: f64, + pub center: Option, +} + /// Inflate's options. #[derive(Clone, Copy, Debug, PartialEq)] pub struct Inflate { @@ -311,6 +348,10 @@ pub struct Facet { /// point of the drawing ([`Facet::depth_at`]). `None` for a face whose corners lie more than /// 0.001 pt off one plane (a piece of a twisted wall) or reach the eye. pub plane: Option, + /// Where the facet lies on one of its solid's numbered surfaces. `None` unless the solid was + /// built with its surfaces laid out ([`Extrude::map_surfaces`], [`Revolve::map_surface`]), + /// and for the ends, whose art is placed through a [`FaceMap`]. + pub cell: Option>, /// The contours in view space, before projection, for tests that measure depths. #[cfg(test)] view: Vec>, @@ -383,7 +424,11 @@ impl Facet { /// Revolve's face `face` as a facet: its polygon, curved outline, depth, plane, normal and lighting. /// A face that joins the profile's ends round the axis is a side; a cap is an end. pub(crate) fn of_face(face: crate::Face) -> Self { + // The side is the surface's only numbered surface. A face that shows its inside carries + // no cell. + let cell = face.surface.filter(|c| c.outward && !face.cap).map(|c| Box::new(MapCell { surface: 0, page: c.page, uv: c.uv })); Facet { + cell, contours: vec![face.points], depth: face.depth, brightness: face.brightness, diff --git a/crates/three-d/src/solid/build.rs b/crates/three-d/src/solid/build.rs index 29d5debcc3..d7d68c261e 100644 --- a/crates/three-d/src/solid/build.rs +++ b/crates/three-d/src/solid/build.rs @@ -7,8 +7,8 @@ use super::rings::{ }; use super::side; use super::{ - Bevel, DepthPlane, Extrude, Facet, FillRule, MAX_FACES, MAX_SOLID_FACES, ParamCurve, PathData, PlanarFace, Point, Rect, Revolve, V3, View, - eye_distance, perspective_scale, + Bevel, DepthPlane, Extrude, Facet, FillRule, MAX_FACES, MAX_SOLID_FACES, MapCell, ParamCurve, PathData, PlanarFace, Point, Rect, Revolve, + SolidSurface, SurfaceKind, V3, View, eye_distance, perspective_scale, }; use crate::shadow::Projection; @@ -102,6 +102,16 @@ pub(super) struct Builder<'a> { /// The faces kept for the mesh passed [`MAX_SOLID_FACES`] while the facets were built too: the /// mesh is too complex, and `mesh` keeps no more faces. pub(super) lost: bool, + /// The cells the facets of the next band carry ([`Builder::curved_band`]). + pub(super) cells: Option, +} + +/// The cells of one band's facets: for each edge of the ring, its numbered surface and where the +/// edge starts and ends along it (`None` for an edge of no length), and where the band's two rings +/// lie across the surface. +pub(super) struct BandCells { + edges: Vec>, + across: (f64, f64), } /// Where a face goes in the order the facets are drawn, back to front. @@ -123,7 +133,16 @@ pub(super) enum Order { impl<'a> Builder<'a> { /// A builder for one solid seen by `camera`, keeping what `keep` asks for. pub(super) fn new(camera: &'a Camera, closed: bool, hidden: bool, keep: Keep) -> Self { - Self { camera, closed, hidden, facets: vec![], mesh: (keep != Keep::Facets).then(Vec::new), draw: keep != Keep::Faces, lost: false } + Self { + camera, + closed, + hidden, + facets: vec![], + mesh: (keep != Keep::Facets).then(Vec::new), + draw: keep != Keep::Faces, + lost: false, + cells: None, + } } /// Add a face of view-space contours with outward normal `n` (view space), drawn in `order`. @@ -214,6 +233,7 @@ impl<'a> Builder<'a> { end: None, surface: None, plane, + cell: None, #[cfg(test)] view, }); @@ -300,6 +320,12 @@ impl<'a> Builder<'a> { && let Some(f) = self.facets.last_mut() { f.side = true; + // An edge drawn in one piece carries its place on its numbered surface. + let cell = self.cells.as_ref().filter(|_| pieces == 1).and_then(|c| Some((c.edges.get(i).copied().flatten()?, c.across))); + if let (Some(((surface, u0, u1), (v0, v1))), Some(page)) = (cell, f.contours.first()) { + let uv = vec![Point::new(u0, v0), Point::new(u1, v0), Point::new(u1, v1), Point::new(u0, v1)]; + f.cell = Some(Box::new(MapCell { surface, page: page.clone(), uv })); + } if let Some(s) = side.as_ref() && let (Some([x0, x1]), Some(page)) = (s.x.get(i).copied(), f.contours.first()) { @@ -534,6 +560,16 @@ struct Step { face: f64, } +/// How far the walls are inset (negative: outset). With the bevel inside, the cap is inset by its +/// width and the wall is the outline; outside, the cap is the outline and the wall is outset by +/// the width. +fn wall_inset(o: &Extrude) -> f64 { + match o.bevel.filter(|b| b.width > 0.0 || b.height > 0.0) { + Some(b) if !b.inside => -b.width, + _ => 0.0, + } +} + /// The outline's steps from the front cap's edge to the back cap's edge. fn steps(o: &Extrude) -> Vec { let d = o.depth.max(1e-6); @@ -563,12 +599,7 @@ fn steps(o: &Extrude) -> Vec { } pts }; - // With the bevel inside, the cap is inset by its width and the wall is the outline; outside, - // the cap is the outline and the wall is outset by the width. - let wall = match bevel { - Some(b) if !b.inside => -b.width, - _ => 0.0, - }; + let wall = wall_inset(o); // A twist turns a bevel's steps too: each step between two samples is cut into steps that // turn no further than 6°, as the walls' slices do at most. let refine = |pts: Vec<(f64, f64)>| -> Vec<(f64, f64)> { @@ -694,6 +725,8 @@ pub(crate) fn extrude_faces(path: &PathData, rule: FillRule, bounds: Rect, optio }) .collect(); let mut budget = Budget::default(); + // The numbered surfaces of the sides, for a solid whose walls stay flat. + let layout = (o.map_surfaces && o.twist == 0.0 && o.taper == 1.0).then(|| (sides(&traced, wall_inset(&o)), band_spans(&steps, o.depth))); // With graphics on the side, the longest contour's pieces carry where they lie on it unrolled. let unrolled = o .map_surface @@ -708,6 +741,12 @@ pub(crate) fn extrude_faces(path: &PathData, rule: FillRule, bounds: Rect, optio let placed: Vec> = steps.iter().map(|s| ring_at(ring, s)).collect(); for (k, pair) in placed.windows(2).enumerate() { let ([a, c], Some(s0), Some(s1)) = (pair, steps.get(k), steps.get(k + 1)) else { continue }; + b.cells = layout.as_ref().and_then(|(sides, spans)| { + let (bevel, v0, v1) = spans.get(k).copied().flatten()?; + let base = caps + if bevel { sides.lengths.len() } else { 0 }; + let edges = sides.edges.get(r)?.iter().map(|e| e.map(|(section, u0, u1)| (base + section, u0, u1))).collect(); + Some(BandCells { edges, across: (v0, v1) }) + }); // A band between two front bevel steps borders the front, one reaching a back bevel // step the back; the rest are walls. let face = if s1.face < 0.0 { @@ -725,6 +764,7 @@ pub(crate) fn extrude_faces(path: &PathData, rule: FillRule, bounds: Rect, optio b.curved_band(a, c, pieces, |i| outward(ring, i, face), curves, side)?; } } + b.cells = None; if o.cap { // A cap turned toward the viewer covers the walls it overlaps, even those nearer than its // center: twisted walls, and the walls of a fill inside the solid of its stroke. @@ -743,6 +783,139 @@ pub(crate) fn extrude_faces(path: &PathData, rule: FillRule, bounds: Rect, optio Ok(b.finish()) } +/// The turn of the outline, in degrees, past which the side wall on one side of a point is another +/// numbered surface than the wall on its other side. +const CORNER: f64 = 20.0; + +/// How the sides of a solid's rings divide into numbered surfaces: for each ring, each edge's +/// surface (counted through the rings in order) and where the edge starts and ends along it, and +/// each surface's length. A surface runs from one corner of its ring to the next, and a ring with +/// no corner is one surface from its first point. The edges of one curve of the outline are never +/// parted. An edge of no length belongs to no surface. An edge starts farther along its surface +/// than it ends: the surface is measured from its left edge as it is seen from outside the solid. +/// Lengths are measured on the ring moved to the walls' inset `wall`, so a wall set out by a bevel +/// is laid out at its own length, and a bevel band at the length of the wall below it. +struct Sides { + edges: Vec>>, + lengths: Vec, +} + +fn sides(rings: &[Ring], wall: f64) -> Sides { + let mut out = Sides { edges: vec![], lengths: vec![] }; + for ring in rings { + let n = ring.points.len(); + let point = |i: usize| ring.points.get(i % n.max(1)).copied().unwrap_or_default(); + let at_wall = inset(&ring.points, wall); + let wall_point = |i: usize| at_wall.get(i % n.max(1)).copied().unwrap_or_default(); + // An edge of the outline with no length (a corner cut square) stays off every surface. + let length = |i: usize| if point(i).distance(point(i + 1)) > 1e-9 { wall_point(i).distance(wall_point(i + 1)) } else { 0.0 }; + let direction = |i: usize| { + let d = point(i + 1) - point(i); + let l = d.hypot(); + (l > 1e-9).then(|| d / l) + }; + let curve = |i: usize| ring.spans.get(i % n.max(1)).copied().flatten().map(|s| s.curve); + // Point `i` is a corner when the edge that leaves it turns from the last edge with a + // length before it, and the two do not follow one curve. + let corner = |i: usize| { + let Some(leaving) = direction(i) else { return false }; + let Some(before) = (1..n).map(|k| i + n - k).find(|e| direction(*e).is_some()) else { return false }; + let one_curve = matches!((curve(before), curve(i)), (Some(a), Some(b)) if a == b); + !one_curve && direction(before).is_some_and(|d| d.dot(leaving) < CORNER.to_radians().cos()) + }; + let start = (0..n).find(|i| corner(*i)).unwrap_or(0); + let mut edges = vec![None; n]; + let mut along = 0.0; + out.lengths.push(0.0); + for k in 0..n { + let i = (start + k) % n; + if k > 0 && corner(i) { + out.lengths.push(0.0); + along = 0.0; + } + let l = length(i); + if let Some(slot) = edges.get_mut(i).filter(|_| l > 1e-9) { + *slot = Some((out.lengths.len() - 1, along, along + l)); + } + along += l; + if let Some(total) = out.lengths.last_mut() { + *total = along; + } + } + // A ring runs from right to left as its side is seen from outside the solid, so each edge + // is placed from its surface's far end. + for (surface, from, to) in edges.iter_mut().flatten() { + let length = out.lengths.get(*surface).copied().unwrap_or(0.0); + (*from, *to) = (length - *from, length - *to); + } + out.edges.push(edges); + } + out +} + +/// Where the band between each two neighboring steps lies across its numbered surface: whether it +/// is part of the front bevel (else of the wall), and the distances of its two rings from the +/// surface's edge nearer the front. `None` for a band of a back bevel. +fn band_spans(steps: &[Step], depth: f64) -> Vec> { + let (mut bevel_at, mut wall_at) = (0.0, 0.0); + steps + .windows(2) + .map(|pair| { + let [s0, s1] = pair else { return None }; + if s1.face < 0.0 { + return None; + } + let across = (s1.inset - s0.inset).hypot((s1.t - s0.t) * depth); + let bevel = s0.face > 0.0 && s1.face > 0.0; + let at = if bevel { &mut bevel_at } else { &mut wall_at }; + let from = *at; + *at += across; + Some((bevel, from, *at)) + }) + .collect() +} + +/// The numbered surfaces of the solid [`extrude`] builds from `path`, in order: the front and back +/// caps of a solid with caps, then each side wall, ring by ring from each ring's first corner, then +/// the bevel above each wall in the same order. A plane (no depth) has its front only, and a solid +/// with a twist or a taper has only its caps. The facets of a solid built with +/// [`Extrude::map_surfaces`] carry these indexes ([`MapCell`]). +pub fn extrude_surfaces(path: &PathData, rule: FillRule, bounds: Rect, options: Extrude) -> Result, String> { + check_bounds(bounds)?; + let o = options.sanitized(); + let end = + |face: PlanarFace, b: Rect| SolidSurface { kind: SurfaceKind::End(face), width: b.width(), height: b.height(), center: Some(b.center()) }; + if o.depth <= 0.0 { + return Ok(path.bounds().map(|b| end(PlanarFace::Front, b)).into_iter().collect()); + } + let steps = steps(&o); + let (bands, caps) = (steps.len().saturating_sub(1), if o.cap { 2 } else { 0 }); + let size = bounds.width().max(bounds.height()); + let most = curve_pieces(path, size, bands, caps)?; + let side = steps.iter().map(|s| s.inset).find(|w| *w != 0.0).unwrap_or(0.0); + let traced: Vec = solid_rings_traced(path, rule, size, MAX_SOLID_POINTS, most)?.iter().map(|r| square_corners(r, side)).collect(); + let mut out = vec![]; + if o.cap { + for (step, face) in [(steps.first(), PlanarFace::Front), (steps.last(), PlanarFace::Back)] { + let Some(step) = step else { continue }; + let mut points = traced.iter().flat_map(|r| inset(&r.points, step.inset)); + let Some(first) = points.next() else { continue }; + out.push(end(face, points.fold(Rect::from_points(first, first), |b, p| b.union_pt(p)))); + } + } + if o.twist != 0.0 || o.taper != 1.0 { + return Ok(out); + } + let sides = sides(&traced, wall_inset(&o)); + let spans = band_spans(&steps, o.depth); + let across = |bevel: bool| spans.iter().flatten().filter(|s| s.0 == bevel).map(|s| s.2).fold(0.0, f64::max); + let kinds = [(SurfaceKind::Wall, false)].into_iter().chain(spans.iter().flatten().any(|s| s.0).then_some((SurfaceKind::Bevel, true))); + for (kind, bevel) in kinds { + out.extend(sides.lengths.iter().map(|l| SolidSurface { kind, width: *l, height: across(bevel), center: None })); + } + Ok(out) +} + /// The size of Extrude & Bevel's side unrolled flat ([`super::side`]), for a solid of `path` built /// as [`extrude`] builds it: the length of its longest contour's outline, the length across its /// bevels and walls, front to back, and the width about x = 0 that does not reach the side's cut. diff --git a/crates/three-d/src/solid/tests.rs b/crates/three-d/src/solid/tests.rs index b32faf1097..78d2fcdcbe 100644 --- a/crates/three-d/src/solid/tests.rs +++ b/crates/three-d/src/solid/tests.rs @@ -438,6 +438,7 @@ fn malformed_and_degenerate_input_is_bounded() { cap: true, bevel: Some(Bevel { width: f64::NAN, height: 1e12, repeat: usize::MAX, space: 7.0, ..Bevel::default() }), hidden: false, + map_surfaces: false, map_surface: true, }; let f = extrude(&p, FillRule::EvenOdd, b, wild, View { rotation_x: f64::NAN, perspective: 900.0, ..front() }).unwrap(); diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 7dd0d2975f..f528d7da71 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -893,6 +893,7 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { let revolves = revolve_gizmo::active(&d); if revolves { revolve_gizmo::show(app, ctx, &mut d); + three_d_classic::surface_outline(app, ctx, &d); } let initial = if revolves { egui::vec2((ctx.content_rect().width() / 2.0 - 226.0).max(0.0), -40.0) } else { egui::vec2(0.0, -40.0) }; let id = egui::Id::unique(("dialog", d.kind.as_str())); diff --git a/crates/ui-egui/src/dialogs/revolve.rs b/crates/ui-egui/src/dialogs/revolve.rs index c7c98a5de0..1812f41d42 100644 --- a/crates/ui-egui/src/dialogs/revolve.rs +++ b/crates/ui-egui/src/dialogs/revolve.rs @@ -37,12 +37,19 @@ pub(super) fn body(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { let id = d.str("__effect"); let defaults = vectorcraft_effects::default_params(&id).unwrap_or(json!({})); - // Reset all resets the shape, view and light; the mapped graphics and the render - // settings stay. + // Reset all resets the shape, view and light; the mapped graphics, Map Art with its + // options and the render settings stay. let defaults = match defaults { Value::Object(mut m) => { - m.remove(vectorcraft_effects::GRAPHICS); - m.remove(vectorcraft_effects::RENDER); + for key in [ + vectorcraft_effects::GRAPHICS, + vectorcraft_effects::RENDER, + vectorcraft_effects::MAP_ART, + vectorcraft_effects::MAP_SHADE, + vectorcraft_effects::MAP_INVISIBLE, + ] { + m.remove(key); + } Value::Object(m) } other => other, @@ -175,6 +182,11 @@ pub(super) fn c3(s: &'static str) -> &'static str { /// first two, the light gizmo on Lighting. fn solid_controls(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, id: &str) { let classic = vectorcraft_effects::is_classic_three_d(id); + // Map Art takes the place of the tabs until its Done. + if classic && super::three_d_classic::map_art_open(d) { + super::three_d_classic::map_art_controls(app, ui, d); + return; + } let object = id == EXTRUDE || id == INFLATE || id == CLASSIC_EXTRUDE || id == CLASSIC_REVOLVE; let mut tabs = vec![]; if object { diff --git a/crates/ui-egui/src/dialogs/revolve/tests.rs b/crates/ui-egui/src/dialogs/revolve/tests.rs index 223c617981..dd5f05ad5d 100644 --- a/crates/ui-egui/src/dialogs/revolve/tests.rs +++ b/crates/ui-egui/src/dialogs/revolve/tests.rs @@ -106,6 +106,83 @@ fn button(pos: Pos2, pressed: bool) -> Event { Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Default::default() } } +#[test] +fn map_art_maps_a_symbol_onto_a_surface_of_extrude_and_bevel_classic() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width":300,"height":300})).unwrap(); + let mark = app.run("path.create", json!({"d":"M250 250L260 250L260 270L250 270Z"})).unwrap()["id"].clone(); + app.run("threeD.addGraphic", json!({"name":"Mark","ids":[mark]})).unwrap(); + app.run("path.create", json!({"d":"M50 50L150 50L150 150L50 150Z"})).unwrap(); + app.run("effect.dialog", json!({"effect":CLASSIC_EXTRUDE,"item":null})).unwrap(); + let ctx = egui::Context::default(); + theme::install_fonts(&ctx); + theme::apply(&ctx, Default::default()); + let mut h = Harness { app, ctx, screen: vec2(1280.0, 900.0), texts: vec![] }; + h.settle(); + h.click(h.rect("Map Art…").center()); + assert!(h.app.ui.dialog.as_ref().unwrap().bool("__mapArt"), "Map Art… opens Map Art"); + let count: usize = h.texts.iter().find_map(|(s, _)| s.strip_prefix("/ ")).and_then(|n| n.parse().ok()).expect("the surface count"); + assert!(count >= 6, "a square's solid has at least six surfaces: {count}"); + // The Symbol menu maps the symbol onto the surface shown, the first. + h.click(h.rect("None").center()); + h.click(h.rect("Mark").center()); + let maps = |h: &Harness| vectorcraft_effects::surface_maps(&json!({"mapArt": h.app.ui.dialog.as_ref().unwrap().fields.get("mapArt").cloned()})); + assert_eq!(maps(&h).iter().map(|m| (m.surface, m.symbol.as_str(), m.scale_x)).collect::>(), [(1, "Mark", 100.0)]); + // The next surface has no map until it is given one; Scale to Fit fills the first. + h.click(h.rect(">").center()); + assert_eq!(h.value("__mapSurface"), 2.0); + assert_eq!(maps(&h).len(), 1); + h.click(h.rect("<").center()); + h.click(h.rect("Scale to Fit").center()); + assert!(maps(&h)[0].scale_x > 100.0, "the 10-point art is scaled up to the 100-point cap: {:?}", maps(&h)); + h.click(h.rect("Done").center()); + assert!(!h.app.ui.dialog.as_ref().unwrap().bool("__mapArt"), "Done goes back to the effect's options"); + dialogs::confirm(&mut h.app).unwrap(); + let state = h.app.session.doc().unwrap(); + let id = state.selection.objects[0]; + let params = &state.doc.node(id).unwrap().appearance.effects[0].params; + assert_eq!(vectorcraft_effects::surface_maps(params).len(), 1, "{params}"); + assert!(params.get("__mapArt").is_none() && params.get("__mapSurface").is_none(), "the dialog's own state stays out of the effect"); +} + +#[test] +fn map_art_maps_no_more_surfaces_than_an_object_takes() { + let max = vectorcraft_effects::MAX_MAPS; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width":300,"height":300})).unwrap(); + let mark = app.run("path.create", json!({"d":"M250 250L260 250L260 270L250 270Z"})).unwrap()["id"].clone(); + app.run("threeD.addGraphic", json!({"name":"Mark","ids":[mark]})).unwrap(); + // A star with 36 points has 72 corners, so its solid has two caps and 72 walls. + let corners: Vec = (0..72) + .map(|i| { + let (r, a) = (if i % 2 == 0 { 100.0 } else { 60.0 }, f64::from(i) * std::f64::consts::TAU / 72.0); + format!("{:.3} {:.3}", 150.0 + r * a.cos(), 150.0 + r * a.sin()) + }) + .collect(); + app.run("path.create", json!({"d": format!("M{}Z", corners.join(" L"))})).unwrap(); + app.run("effect.dialog", json!({"effect":CLASSIC_EXTRUDE,"item":null})).unwrap(); + let ctx = egui::Context::default(); + theme::install_fonts(&ctx); + theme::apply(&ctx, Default::default()); + let mut h = Harness { app, ctx, screen: vec2(1280.0, 900.0), texts: vec![] }; + h.settle(); + h.click(h.rect("Map Art…").center()); + let count: usize = h.texts.iter().find_map(|(s, _)| s.strip_prefix("/ ")).and_then(|n| n.parse().ok()).expect("the surface count"); + assert!(count > max, "{count} surfaces"); + // Every map the object takes is used, and the surface shown has none. + let full: Vec = (1..=max).map(|surface| json!({"surface": surface, "symbol": "Mark"})).collect(); + let d = h.app.ui.dialog.as_mut().unwrap(); + d.fields.insert("mapArt".into(), json!(full)); + d.fields.insert("__mapSurface".into(), json!(max + 1)); + h.settle(); + h.click(h.rect("None").center()); + if h.texts.iter().any(|(s, _)| s == "Mark") { + h.click(h.rect("Mark").center()); + } + let raw = h.app.ui.dialog.as_ref().unwrap().fields.get("mapArt").cloned().unwrap_or_default(); + assert_eq!(raw.as_array().map(Vec::len), Some(max), "no map past the limit is written"); +} + #[test] fn values_labels_sliders_and_reset_dots_change_the_live_effect_in_one_undo_step() { let mut h = Harness::new(vec2(1280.0, 900.0)); @@ -694,6 +771,27 @@ fn every_3d_dialog_has_color_and_reset_all_restores_white() { } } +#[test] +fn reset_all_keeps_map_art_and_its_options() { + for effect in [CLASSIC_EXTRUDE, CLASSIC_REVOLVE] { + let mut h = Harness::with("M100 100L200 100L200 200L100 200Z", effect, vec2(1280.0, 900.0)); + h.settle(); + let maps = json!([{"surface": 1, "symbol": "Mark"}]); + let d = h.app.ui.dialog.as_mut().unwrap(); + d.fields.insert("mapArt".into(), maps.clone()); + d.fields.insert("mapShade".into(), json!(true)); + d.fields.insert("mapInvisible".into(), json!(true)); + d.fields.insert("rotationX".into(), json!(40.0)); + h.settle(); + h.click(h.response("revolve-reset-all").center()); + let d = h.app.ui.dialog.as_ref().unwrap(); + assert_eq!(d.f64("rotationX", 0.0), -21.88, "{effect}: the view is reset"); + assert_eq!(d.fields.get("mapArt"), Some(&maps), "{effect}: the maps stay"); + assert!(d.bool("mapShade") && d.bool("mapInvisible"), "{effect}: Shade Artwork and Invisible Geometry stay"); + dialogs::cancel(&mut h.app); + } +} + #[test] fn light_list_add_select_edit_delete_and_reset_keep_each_light_independent() { for effect in [REVOLVE, EXTRUDE, INFLATE, vectorcraft_effects::ROTATE] { diff --git a/crates/ui-egui/src/dialogs/tests_track_cube.rs b/crates/ui-egui/src/dialogs/tests_track_cube.rs index 9b99efb105..9e36fb89f0 100644 --- a/crates/ui-egui/src/dialogs/tests_track_cube.rs +++ b/crates/ui-egui/src/dialogs/tests_track_cube.rs @@ -182,3 +182,37 @@ fn grips_follow_what_is_under_the_pointer() { let m = rotation([0.0, 0.0, 0.0]); assert_eq!(edges().filter(|&(i, _, axis)| edge_visible(m, i, axis)).count(), 4); } + +/// Map Art lists each document's own surfaces: after a switch to another document whose object has +/// the same id, effect settings and revision, the surfaces are those of the other document's object. +#[test] +fn map_art_surfaces_follow_the_active_document() { + let mut app = crate::VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + for d in ["M50 50L150 50L150 150L50 150Z", "M50 50L80 50L80 200L50 200Z"] { + app.run("file.new", json!({"width":300,"height":300})).unwrap(); + app.run("path.create", json!({"d": d})).unwrap(); + } + app.run("effect.dialog", json!({"effect":CLASSIC_EXTRUDE,"item":null})).unwrap(); + let d = app.ui.dialog.take().unwrap(); + let ctx = egui::Context::default(); + let key = |app: &crate::VectorcraftApp| { + let st = app.session.active().unwrap(); + (st.selection.objects.first().copied(), st.revision) + }; + let second = surfaces(&app, &ctx, &d).unwrap(); + let at_second = key(&app); + assert!(app.session.set_active(0)); + assert_eq!(key(&app), at_second, "both documents' objects have the same id and revision"); + let first = surfaces(&app, &ctx, &d).unwrap(); + let st = app.session.active().unwrap(); + let id = st.selection.objects[0]; + let own = vectorcraft_effects::map_surfaces_with( + Some(&st.doc), + st.doc.node(id).unwrap(), + (None, None), + CLASSIC_EXTRUDE, + &super::super::form::params(&d), + ); + assert_ne!(first, second, "the two objects' solids differ in size"); + assert_eq!(Some(first.as_ref()), own.as_ref(), "the first document's surfaces"); +} diff --git a/crates/ui-egui/src/dialogs/three_d_classic.rs b/crates/ui-egui/src/dialogs/three_d_classic.rs index e8c0e5c122..b3f1ebd3d9 100644 --- a/crates/ui-egui/src/dialogs/three_d_classic.rs +++ b/crates/ui-egui/src/dialogs/three_d_classic.rs @@ -7,7 +7,7 @@ use egui::{Color32, Id, Pos2, Rect, Sense, Stroke, Vec2, vec2}; use serde_json::{Value, json}; use vectorcraft_doc::Unit; -use vectorcraft_effects::{CLASSIC_EXTRUDE, CLASSIC_REVOLVE, CLASSIC_ROTATE}; +use vectorcraft_effects::{CLASSIC_EXTRUDE, CLASSIC_REVOLVE, CLASSIC_ROTATE, MAP_ART, MAP_INVISIBLE, MAP_SHADE, MapSurface, SurfaceMap}; use super::revolve::{c3, choice, heading, label, light_list, light_record, number, reset_dot, selected_light, store_selected, toggle}; use crate::state::Dialog; @@ -26,6 +26,359 @@ pub(super) fn object_controls(ui: &mut egui::Ui, d: &mut Dialog, unit: Unit) { number(ui, d, "bevelHeight", tl!("Height"), (1.0, 100.0), "", 1, Some(unit)); toggle(ui, d, "bevelInside", tl!("Bevel Inside"), false); }); + map_art_button(ui, d); +} + +/// The field of [`Dialog::fields`] that is true while the dialog shows Map Art in place of its +/// tabs. It is UI state and never enters the effect's parameters. +pub(super) const MAP_ART_OPEN: &str = "__mapArt"; +/// The field that holds the number of the surface Map Art shows. +const MAP_SURFACE: &str = "__mapSurface"; + +/// Map Art…, which opens [`map_art_controls`]. The 3D and Materials panel has no such button. +fn map_art_button(ui: &mut egui::Ui, d: &mut Dialog) { + if d.bool("__panel") { + return; + } + ui.add_space(10.0); + if ui.button(tl!("Map Art…")).clicked() { + d.fields.insert(MAP_ART_OPEN.into(), json!(true)); + } +} + +/// Is Map Art open in the dialog? +pub(super) fn map_art_open(d: &Dialog) -> bool { + d.bool(MAP_ART_OPEN) && vectorcraft_effects::takes_map_art(&d.str("__effect")) +} + +/// The numbered surfaces of the first selected object with the dialog's effect and settings +/// ([`vectorcraft_effects::map_surfaces_with`]), kept until the object, the document or a setting +/// that shapes the solid changes. +fn surfaces(app: &crate::VectorcraftApp, ctx: &egui::Context, d: &Dialog) -> Option>> { + use std::hash::{Hash, Hasher}; + let st = app.session.active()?; + let id = *st.selection.objects.first()?; + let effect = d.str("__effect"); + // The maps themselves do not change the surfaces. + let mut p = super::form::params(d); + if let Some(m) = p.as_object_mut() { + for key in [MAP_ART, MAP_SHADE, MAP_INVISIBLE] { + m.remove(key); + } + } + let item = d.fields.get("__item").and_then(Value::as_u64).map(|i| i as usize); + // The effect being edited, when the dialog edits one already on the object. + let index = d.fields.get("__index").and_then(Value::as_u64).map(|i| i as usize); + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + (st.uid, id.0, item, index, &effect, p.to_string(), st.revision).hash(&mut hasher); + let key = hasher.finish(); + let cache = egui::Id::unique("map-art-surfaces"); + if let Some((at, kept)) = ctx.data(|m| m.get_temp::<(u64, std::sync::Arc>)>(cache)) + && at == key + { + return Some(kept); + } + let listed = std::sync::Arc::new(vectorcraft_effects::map_surfaces_with(Some(&st.doc), st.doc.node(id)?, (item, index), &effect, &p)?); + ctx.data_mut(|m| m.insert_temp(cache, (key, listed.clone()))); + Some(listed) +} + +/// The dialog's maps, read as the effect reads them. +fn maps_of(d: &Dialog) -> Vec { + vectorcraft_effects::surface_maps(&json!({ MAP_ART: d.fields.get(MAP_ART).cloned().unwrap_or(Value::Null) })) +} + +/// The surface Map Art shows, from 1, among `count` surfaces. +fn shown_surface(d: &Dialog, count: usize) -> usize { + (d.f64(MAP_SURFACE, 1.0).round().max(1.0) as usize).min(count.max(1)) +} + +/// Map Art: the surface (first, previous, its number, next, last, and whether the viewer sees +/// it), the symbol mapped onto it, the surface laid out flat with the art's box to move, scale and +/// rotate, the same values as numbers, Scale to Fit, Clear, Clear All, Shade Artwork and Invisible +/// Geometry. Edits the effect's `mapArt`, `mapShade` and `mapInvisible` in `d.fields`, which the +/// dialog previews and applies with its other settings. Done, beside the heading, goes back to the +/// effect's options. +pub(super) fn map_art_controls(app: &crate::VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { + ui.horizontal(|ui| { + heading(ui, tl!("Map Art")); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.button(tl!("Done")).clicked() { + d.fields.remove(MAP_ART_OPEN); + } + }); + }); + let listed = surfaces(app, ui.ctx(), d).filter(|s| !s.is_empty()); + let Some(listed) = listed else { return }; + let count = listed.len(); + let mut current = shown_surface(d, count); + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 4.0; + label(ui, tl!("Surface")); + let step = |ui: &mut egui::Ui, text: &str, tip: &str, enabled: bool| { + let r = ui.add_enabled(enabled, egui::Button::new(text).min_size(egui::vec2(26.0, 24.0))); + r.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, enabled, tip)); + r.on_hover_text(tip).clicked() + }; + let mut next = None; + if step(ui, "|<", tl!("First Surface"), current > 1) { + next = Some(1); + } + if step(ui, "<", tl!("Previous Surface"), current > 1) { + next = Some(current - 1); + } + let mut typed = current; + let field = ui.add_sized([44.0, 24.0], egui::DragValue::new(&mut typed).range(1..=count).speed(0.1)); + field.widget_info(|| egui::WidgetInfo::labeled(egui::Role::SpinButton, true, tl!("Surface"))); + if field.changed() { + next = Some(typed); + } + ui.label(format!("/ {count}")); + if step(ui, ">", tl!("Next Surface"), current < count) { + next = Some(current + 1); + } + if step(ui, ">|", tl!("Last Surface"), current < count) { + next = Some(count); + } + if let Some(n) = next { + current = n.clamp(1, count); + } + // A light mark for a surface the viewer sees, a dark one for a hidden surface. + let seen = listed.get(current - 1).is_some_and(|s| s.visible); + let (mark, _) = ui.allocate_exact_size(egui::vec2(14.0, 14.0), egui::Sense::hover()); + ui.painter().rect_filled(mark, 2.0, if seen { egui::Color32::from_gray(205) } else { egui::Color32::from_gray(90) }); + if !seen { + crate::widgets::dim_label(ui, "Hidden"); + } + }); + d.fields.insert(MAP_SURFACE.into(), json!(current)); + let Some(surface) = listed.get(current - 1) else { return }; + let maps = maps_of(d); + let map = maps.iter().find(|m| m.surface == current).cloned(); + let mut edited = map.clone(); + let names: Vec = app.session.active().map(|st| st.doc.symbols.iter().map(|s| s.name.clone()).collect()).unwrap_or_default(); + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 6.0; + label(ui, tl!("Symbol")); + let none = tl!("None"); + let options: Vec<&str> = std::iter::once(none).chain(names.iter().map(String::as_str)).collect(); + let shown = map.as_ref().map_or(none, |m| m.symbol.as_str()); + // With every map the object takes in use, a surface without one cannot be given one. + let room = map.is_some() || maps.len() < vectorcraft_effects::MAX_MAPS; + let picked = ui.add_enabled_ui(room, |ui| crate::widgets::dropdown_names(ui, "map-art-symbol", shown, &options, 190.0)).inner; + if let Some(k) = picked.filter(|_| room) { + edited = k.checked_sub(1).and_then(|k| names.get(k)).map(|name| match &map { + Some(m) => SurfaceMap { symbol: name.clone(), ..m.clone() }, + None => SurfaceMap { surface: current, symbol: name.clone(), x: 0.0, y: 0.0, scale_x: 100.0, scale_y: 100.0, rotation: 0.0 }, + }); + } + }); + ui.add_space(6.0); + let art = edited.as_ref().and_then(|m| app.session.active().and_then(|st| vectorcraft_effects::graphic_bounds(&st.doc, &m.symbol))); + flat_view(app, ui, surface, &mut edited, art); + ui.add_space(6.0); + ui.add_enabled_ui(edited.is_some(), |ui| { + let shown = edited.clone().unwrap_or(SurfaceMap { + surface: current, + symbol: String::new(), + x: 0.0, + y: 0.0, + scale_x: 100.0, + scale_y: 100.0, + rotation: 0.0, + }); + let unit = app.session.general_unit(); + let mut fields = Dialog { kind: "mapArt".into(), fields: Default::default() }; + fields.fields.insert("__defaults".into(), json!({"mapX": 0.0, "mapY": 0.0, "mapScaleX": 100.0, "mapScaleY": 100.0, "mapRotation": 0.0})); + for (key, value) in + [("mapX", shown.x), ("mapY", shown.y), ("mapScaleX", shown.scale_x), ("mapScaleY", shown.scale_y), ("mapRotation", shown.rotation)] + { + fields.fields.insert(key.into(), json!(value)); + } + let offsets = (-vectorcraft_effects::GRAPHIC_MAX_OFFSET, vectorcraft_effects::GRAPHIC_MAX_OFFSET); + number(ui, &mut fields, "mapX", "X", offsets, "", 1, Some(unit)); + number(ui, &mut fields, "mapY", "Y", offsets, "", 1, Some(unit)); + number(ui, &mut fields, "mapScaleX", tl!("Horizontal Scale"), vectorcraft_effects::GRAPHIC_SCALE_RANGE, "%", 1, None); + number(ui, &mut fields, "mapScaleY", tl!("Vertical Scale"), vectorcraft_effects::GRAPHIC_SCALE_RANGE, "%", 1, None); + number(ui, &mut fields, "mapRotation", tl!("Rotation"), (-360.0, 360.0), "°", 1, None); + if let Some(m) = edited.as_mut() { + m.x = fields.f64("mapX", m.x); + m.y = fields.f64("mapY", m.y); + m.scale_x = fields.f64("mapScaleX", m.scale_x); + m.scale_y = fields.f64("mapScaleY", m.scale_y); + m.rotation = fields.f64("mapRotation", m.rotation); + } + }); + let mut clear_all = false; + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 6.0; + if ui.add_enabled(edited.is_some() && art.is_some(), egui::Button::new(tl!("Scale to Fit"))).clicked() + && let (Some(m), Some(art)) = (edited.as_mut(), art) + { + let (scale_x, scale_y) = m.fitting_scales(art, (surface.width, surface.height)).unwrap_or((m.scale_x, m.scale_y)); + *m = SurfaceMap { x: 0.0, y: 0.0, scale_x, scale_y, ..m.clone() }; + } + if ui.add_enabled(edited.is_some(), egui::Button::new(tl!("Clear"))).clicked() { + edited = None; + } + clear_all = ui.add_enabled(!maps.is_empty(), egui::Button::new(tl!("Clear All"))).clicked(); + }); + ui.add_space(4.0); + toggle(ui, d, MAP_SHADE, tl!("Shade Artwork"), false); + toggle(ui, d, MAP_INVISIBLE, tl!("Invisible Geometry"), false); + if clear_all { + d.fields.insert(MAP_ART.into(), json!([])); + } else if edited != map { + let raw = json!({ MAP_ART: d.fields.get(MAP_ART).cloned().unwrap_or(Value::Null) }); + let next = vectorcraft_effects::with_surface_map(&raw, current, edited.as_ref()); + d.fields.insert(MAP_ART.into(), next.get(MAP_ART).cloned().unwrap_or_else(|| json!([]))); + } +} + +/// What a drag in the flat view changes. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Grab { + Move, + /// A handle of the art's box: -1, 0 or 1 across and down, from its center. + Scale(f32, f32), + Rotate, +} + +/// A drag in the flat view: what it changes, the map as it was when the drag began and where the +/// pointer was then. +#[derive(Clone, Debug)] +struct MapDrag { + grab: Grab, + from: SurfaceMap, + origin: egui::Pos2, +} + +/// The surface laid out flat, as large as fits the view, in a light gray when the viewer sees it +/// and a dark gray when it is hidden, with the box of the mapped art `art` (its bounds at its own +/// size) on it: the art's thumbnail while it is not turned, its outline and its eight handles. A +/// drag inside the box moves the art, a drag of a handle scales it about its center, and a drag +/// just outside the box turns it. +fn flat_view( + app: &crate::VectorcraftApp, + ui: &mut egui::Ui, + surface: &MapSurface, + map: &mut Option, + art: Option, +) { + let t = crate::theme::Tokens::get(ui.ctx()); + let (view, response) = ui.allocate_exact_size(egui::vec2(ui.available_width().clamp(120.0, 330.0), 150.0), egui::Sense::click_and_drag()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Image, true, tl!("Surface"))); + ui.painter().rect_filled(view, 3.0, t.input); + ui.painter().rect_stroke(view, 3.0, egui::Stroke::new(1.0, t.input_border), egui::StrokeKind::Inside); + let (width, height) = (surface.width.max(1e-6), surface.height.max(1e-6)); + // Screen points for each point of the surface. + let scale = ((f64::from(view.width()) - 28.0) / width).min((f64::from(view.height()) - 28.0) / height).max(1e-6); + let flat = egui::Rect::from_center_size(view.center(), egui::vec2((width * scale) as f32, (height * scale) as f32)); + let painter = ui.painter().with_clip_rect(view.intersect(ui.clip_rect())); + painter.rect_filled(flat, 0.0, if surface.visible { egui::Color32::from_gray(205) } else { egui::Color32::from_gray(90) }); + let drag_id = egui::Id::unique("map-art-drag"); + let (Some(m), Some(art)) = (map.as_mut(), art) else { + ui.data_mut(|d| d.remove::(drag_id)); + return; + }; + let box_of = |m: &SurfaceMap| { + let center = view.center() + egui::vec2((m.x * scale) as f32, (m.y * scale) as f32); + let half = egui::vec2((art.width() * m.scale_x / 100.0 * scale / 2.0) as f32, (art.height() * m.scale_y / 100.0 * scale / 2.0) as f32); + // Counterclockwise on a screen whose y runs down. + let (sin, cos) = (-m.rotation.to_radians() as f32).sin_cos(); + (center, half, sin, cos) + }; + let (center, half, sin, cos) = box_of(m); + let handles: Vec<(f32, f32)> = + [-1.0f32, 0.0, 1.0].iter().flat_map(|y| [-1.0f32, 0.0, 1.0].map(|x| (x, *y))).filter(|h| *h != (0.0, 0.0)).collect(); + if response.drag_started() + && let Some(origin) = ui.input(|i| i.pointer.press_origin()) + { + // The pointer in the box's own frame. + let local = egui::vec2((origin - center).x * cos + (origin - center).y * sin, -(origin - center).x * sin + (origin - center).y * cos); + let handle = handles.iter().copied().find(|(x, y)| (local - egui::vec2(x * half.x, y * half.y)).length() <= 7.0); + let grab = if let Some((x, y)) = handle { + Some(Grab::Scale(x, y)) + } else if local.x.abs() <= half.x && local.y.abs() <= half.y { + Some(Grab::Move) + } else if local.x.abs() <= half.x + 18.0 && local.y.abs() <= half.y + 18.0 { + Some(Grab::Rotate) + } else { + None + }; + match grab { + Some(grab) => { + ui.data_mut(|d| d.insert_temp(drag_id, MapDrag { grab, from: m.clone(), origin })); + } + None => ui.data_mut(|d| d.remove::(drag_id)), + } + } + if let (Some(drag), Some(p)) = (ui.data(|d| d.get_temp::(drag_id)), response.interact_pointer_pos().filter(|_| response.dragged())) { + let (from_center, _, from_sin, from_cos) = box_of(&drag.from); + let round = |v: f64, places: i32| (v * 10f64.powi(places)).round() / 10f64.powi(places); + let limit = vectorcraft_effects::GRAPHIC_MAX_OFFSET; + let (lo, hi) = vectorcraft_effects::GRAPHIC_SCALE_RANGE; + match drag.grab { + Grab::Move => { + m.x = round(drag.from.x + f64::from(p.x - drag.origin.x) / scale, 2).clamp(-limit, limit); + m.y = round(drag.from.y + f64::from(p.y - drag.origin.y) / scale, 2).clamp(-limit, limit); + } + Grab::Scale(x, y) => { + let v = p - from_center; + let local = egui::vec2(v.x * from_cos + v.y * from_sin, -v.x * from_sin + v.y * from_cos); + if x != 0.0 && art.width() > 0.0 { + m.scale_x = round(f64::from(local.x.abs()) * 2.0 / (art.width() * scale) * 100.0, 2).clamp(lo, hi); + } + if y != 0.0 && art.height() > 0.0 { + m.scale_y = round(f64::from(local.y.abs()) * 2.0 / (art.height() * scale) * 100.0, 2).clamp(lo, hi); + } + } + Grab::Rotate => { + let angle = |q: egui::Pos2| f64::from((q - from_center).y.atan2((q - from_center).x)).to_degrees(); + // The screen's angles run clockwise. + let rotation = drag.from.rotation - (angle(p) - angle(drag.origin)); + m.rotation = round((rotation + 180.0).rem_euclid(360.0) - 180.0, 1); + } + } + } + if response.drag_stopped() { + ui.data_mut(|d| d.remove::(drag_id)); + } + let (center, half, sin, cos) = box_of(m); + let turned_now = |v: egui::Vec2| egui::vec2(v.x * cos - v.y * sin, v.x * sin + v.y * cos); + if m.rotation.abs() < 0.01 + && let Some(st) = app.session.active() + { + let keys = crate::panels::symbols::document_symbols(st); + let mut inner = ui.new_child(egui::UiBuilder::new().max_rect(view)); + inner.set_clip_rect(view.intersect(ui.clip_rect())); + let r = egui::Rect::from_center_size(center, half * 2.0); + crate::panels::symbols::art_chip(&inner, &st.doc, &keys, r, &m.symbol, art); + } + let corners: Vec = [(-1.0f32, -1.0f32), (1.0, -1.0), (1.0, 1.0), (-1.0, 1.0)] + .iter() + .map(|(x, y)| center + turned_now(egui::vec2(x * half.x, y * half.y))) + .collect(); + painter.add(egui::Shape::closed_line(corners, egui::Stroke::new(1.0, t.accent))); + for (x, y) in handles { + let at = center + turned_now(egui::vec2(x * half.x, y * half.y)); + let handle = egui::Rect::from_center_size(at, egui::vec2(6.0, 6.0)); + painter.rect_filled(handle, 0.0, egui::Color32::WHITE); + painter.rect_stroke(handle, 0.0, egui::Stroke::new(1.0, t.accent), egui::StrokeKind::Inside); + } +} + +/// While Map Art is open with Preview on, the surface it shows, outlined in red on the artboard. +pub(super) fn surface_outline(app: &crate::VectorcraftApp, ctx: &egui::Context, d: &Dialog) { + if !map_art_open(d) || !d.bool("preview") { + return; + } + let (Some(listed), Some(xf)) = (surfaces(app, ctx, d), app.canvas_xf()) else { return }; + let Some(surface) = listed.get(shown_surface(d, listed.len()).saturating_sub(1)) else { return }; + let painter = ctx.layer_painter(egui::LayerId::new(egui::Order::Middle, egui::Id::unique("map-art-outline"))).with_clip_rect(xf.rect); + for [a, b] in &surface.outline { + painter.line_segment([xf.to_screen(*a), xf.to_screen(*b)], egui::Stroke::new(1.5, egui::Color32::RED)); + } } /// Revolve (Classic)'s angle, cap and offset, and the edge of the profile's bounds the axis is at. @@ -40,6 +393,7 @@ pub(super) fn revolve_controls(ui: &mut egui::Ui, d: &mut Dialog, unit: Unit) { .map(|(label, value)| (json!(value), label)) .collect(); choice(ui, d, "edge", tl!("Axis side"), &sides); + map_art_button(ui, d); } /// The surface, then for Diffuse and Plastic the lighting sphere, the lights, Ambient Light, the diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index f9e329e38c..2119e79190 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -1229,6 +1229,17 @@ font-technology Variable Променливи Shading Color Цвят на засенчването Black Overprint Черно с напечатване Draw Hidden Faces Изчертаване на скритите страни + Map Art… Картографиране на графика… + Map Art Картографиране на графика + First Surface Първа повърхност + Previous Surface Предишна повърхност + Next Surface Следваща повърхност + Last Surface Последна повърхност + Horizontal Scale Хоризонтален мащаб + Vertical Scale Вертикален мащаб + Scale to Fit Мащабиране до побиране + Shade Artwork Засенчване на графиката + Invisible Geometry Невидима геометрия Eyedropper Пипета Eyedropper Applies: Пипетата прилага: Eyedropper Options Опции за пипетата diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 0d132f4d48..79993ae742 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -539,6 +539,17 @@ Shading Color Boja sjenčenja Black Overprint Crni pretisak Draw Hidden Faces Crtaj skrivene strane + Map Art… Mapiranje crteža… + Map Art Mapiranje crteža + First Surface Prva površina + Previous Surface Prethodna površina + Next Surface Sljedeća površina + Last Surface Posljednja površina + Horizontal Scale Horizontalna skala + Vertical Scale Vertikalna skala + Scale to Fit Skaliraj da stane + Shade Artwork Osjenči crtež + Invisible Geometry Nevidljiva geometrija Revolve… Rotaciono tijelo… Inflate… Napuhni… Materials… Materijali… diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 8d13eb0e55..aba3b168d8 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -1729,6 +1729,15 @@ antiAlias Sharp Nítid Shading Color Color de l’ombra Black Overprint Negre en sobreimpressió Draw Hidden Faces Dibuixa les cares ocultes + Map Art… Mapatge d’art… + Map Art Mapatge d’art + First Surface Primera superfície + Previous Surface Superfície anterior + Next Surface Superfície següent + Last Surface Última superfície + Scale to Fit Escala per ajustar + Shade Artwork Ombreja l’art + Invisible Geometry Geometria invisible Eyedropper Comptagotes Eyedropper Applies: El comptagotes aplica: Eyedropper Options Opcions del comptagotes diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index b152216eba..90c5e4e1e9 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -550,6 +550,15 @@ Shading Color Barva stínování Black Overprint Přetisk černou Draw Hidden Faces Kreslit skryté stěny + Map Art… Mapovat kresbu… + Map Art Mapovat kresbu + First Surface První povrch + Previous Surface Předchozí povrch + Next Surface Další povrch + Last Surface Poslední povrch + Scale to Fit Změnit velikost podle povrchu + Shade Artwork Stínovat kresbu + Invisible Geometry Neviditelná geometrie Revolve… Rotační těleso… Inflate… Nafouknutí… Materials… Materiály… diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 0037a3372a..faa2efd0ac 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -3239,6 +3239,17 @@ liquify-list-end {0}, {1} {0} og {1} Shading Color Skyggefarve Black Overprint Sort overprint Draw Hidden Faces Tegn skjulte flader + Map Art… Kortlæg grafik… + Map Art Kortlæg grafik + First Surface Første overflade + Previous Surface Forrige overflade + Next Surface Næste overflade + Last Surface Sidste overflade + Horizontal Scale Vandret skalering + Vertical Scale Lodret skalering + Scale to Fit Skalér til at passe + Shade Artwork Skyg grafik + Invisible Geometry Usynlig geometri Revolve… Omdrej… Inflate… Pust op… Materials… Materialer… diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 0448eec255..4299f8b022 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -1258,6 +1258,15 @@ font-technology Variable Variabel Shading Color Schattierungsfarbe Black Overprint Überdruckendes Schwarz Draw Hidden Faces Verdeckte Flächen zeichnen + Map Art… Bildmaterial zuordnen… + Map Art Bildmaterial zuordnen + First Surface Erste Oberfläche + Previous Surface Vorherige Oberfläche + Next Surface Nächste Oberfläche + Last Surface Letzte Oberfläche + Scale to Fit Auf Oberfläche skalieren + Shade Artwork Bildmaterial schattieren + Invisible Geometry Unsichtbare Geometrie Eyedropper Pipette Sample Color from Screen Farbe vom Bildschirm aufnehmen This system has no screen color sampler Dieses System hat keine Farbaufnahme vom Bildschirm diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 7769b05fd0..61ad0ae42f 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -1218,6 +1218,15 @@ font-technology Variable Μεταβλητές Shading Color Χρώμα σκίασης Black Overprint Μαύρο με υπερεκτύπωση Draw Hidden Faces Σχεδίαση κρυφών εδρών + Map Art… Αντιστοίχιση γραφικών… + Map Art Αντιστοίχιση γραφικών + First Surface Πρώτη επιφάνεια + Previous Surface Προηγούμενη επιφάνεια + Next Surface Επόμενη επιφάνεια + Last Surface Τελευταία επιφάνεια + Scale to Fit Κλιμάκωση για προσαρμογή + Shade Artwork Σκίαση γραφικών + Invisible Geometry Αόρατη γεωμετρία Eyedropper Σταγονόμετρο (Eyedropper Tool) Eyedropper Applies: Το σταγονόμετρο εφαρμόζει: Eyedropper Options Επιλογές σταγονόμετρου diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 07f7f9a95a..5b9275061c 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -1283,6 +1283,15 @@ font-technology Variable Variables Shading Color Color de sombreado Black Overprint Negro sobreimpreso Draw Hidden Faces Dibujar caras ocultas + Map Art… Asignar ilustración… + Map Art Asignar ilustración + First Surface Primera superficie + Previous Surface Superficie anterior + Next Surface Superficie siguiente + Last Surface Última superficie + Scale to Fit Escalar para encajar + Shade Artwork Sombrear ilustración + Invisible Geometry Geometría invisible Eyedropper Cuentagotas Sample Color from Screen Tomar color de la pantalla This system has no screen color sampler Este sistema no tiene muestreador de color de la pantalla diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 77ec92bf86..e3ceaaa423 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -547,6 +547,15 @@ Shading Color Varjostusväri Black Overprint Päällepainettu musta Draw Hidden Faces Piirrä piilotetut pinnat + Map Art… Kartoita kuvitus… + Map Art Kartoita kuvitus + First Surface Ensimmäinen pinta + Previous Surface Edellinen pinta + Next Surface Seuraava pinta + Last Surface Viimeinen pinta + Scale to Fit Skaalaa sopivaksi + Shade Artwork Varjosta kuvitus + Invisible Geometry Näkymätön geometria Revolve… Pyöräytä… Inflate… Täytä ilmalla… Materials… Materiaalit… diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index ee29c117ed..ac29cefa31 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -1274,6 +1274,15 @@ font-technology Variable Variables Shading Color Couleur d’ombrage Black Overprint Noir en surimpression Draw Hidden Faces Dessiner les faces cachées + Map Art… Placage d’illustration… + Map Art Placage d’illustration + First Surface Première surface + Previous Surface Surface précédente + Next Surface Surface suivante + Last Surface Dernière surface + Scale to Fit Mettre à l’échelle pour ajuster + Shade Artwork Ombrer l’illustration + Invisible Geometry Géométrie invisible Eyedropper Pipette Sample Color from Screen Prélever une couleur à l’écran This system has no screen color sampler Ce système n’a pas d’outil de prélèvement de couleur à l’écran diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index b95a3207ba..fb65e671a3 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -1143,6 +1143,15 @@ Draw દોરો Draw Dashed Lines as Solid Lines ડેશ્ડ રેખાઓ સોલિડ રેખાઓ તરીકે દોરો Draw Hidden Faces છુપાયેલી સપાટીઓ દોરો + Map Art… આર્ટવર્ક મેપ કરો… + Map Art આર્ટવર્ક મેપ કરો + First Surface પ્રથમ સપાટી + Previous Surface પાછલી સપાટી + Next Surface આગલી સપાટી + Last Surface છેલ્લી સપાટી + Scale to Fit ફિટ થાય તેમ સ્કેલ કરો + Shade Artwork આર્ટવર્કને છાયા આપો + Invisible Geometry અદૃશ્ય ભૂમિતિ Draw in Perspective પર્સ્પેક્ટિવમાં દોરો Draw: દોરો: Drawer menu ડ્રોઅર મેનુ diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index bb93caaec5..3d6907c016 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -1927,6 +1927,15 @@ antiAlias Sharp शार्प Shading Color शेडिंग रंग Black Overprint काला ओवरप्रिंट Draw Hidden Faces छिपे हुए फलक बनाएँ + Map Art… आर्टवर्क मैप करें… + Map Art आर्टवर्क मैप करें + First Surface पहली सतह + Previous Surface पिछली सतह + Next Surface अगली सतह + Last Surface अंतिम सतह + Scale to Fit फ़िट होने तक स्केल करें + Shade Artwork आर्टवर्क पर छाया दें + Invisible Geometry अदृश्य ज्यामिति Eyedropper आईड्रॉपर Eyedropper Applies: आईड्रॉपपर लागू होता है: Eyedropper Options आईड्रॉपर ऑप्शन्स diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 1451874d42..03f8fd5411 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -1582,6 +1582,15 @@ font-technology Variable Változó Shading Color Árnyékolás színe Black Overprint Felülnyomó fekete Draw Hidden Faces Rejtett lapok rajzolása + Map Art… Grafika leképezése… + Map Art Grafika leképezése + First Surface Első felület + Previous Surface Előző felület + Next Surface Következő felület + Last Surface Utolsó felület + Scale to Fit Méretezés a felülethez + Shade Artwork Grafika árnyékolása + Invisible Geometry Láthatatlan geometria Eyedropper Pipetta Sample Color from Screen Szín mintavétele a képernyőről This system has no screen color sampler Ezen a rendszeren nincs képernyős színmintavevő diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 2fc0375ce6..856775b35b 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -506,6 +506,17 @@ Shading Color Warna pengarsiran Black Overprint Hitam overprint Draw Hidden Faces Gambar sisi tersembunyi + Map Art… Petakan karya seni… + Map Art Petakan karya seni + First Surface Permukaan pertama + Previous Surface Permukaan sebelumnya + Next Surface Permukaan berikutnya + Last Surface Permukaan terakhir + Horizontal Scale Skala horizontal + Vertical Scale Skala vertikal + Scale to Fit Skalakan agar pas + Shade Artwork Beri bayangan karya seni + Invisible Geometry Geometri tak terlihat Revolve… Revolusi… Inflate… Gelembungkan… Materials… Material… diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 9eeddeb828..d4120854cb 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -1295,6 +1295,15 @@ font-technology Variable Variabili Shading Color Colore ombreggiatura Black Overprint Nero in sovrastampa Draw Hidden Faces Disegna facce nascoste + Map Art… Mappa grafica… + Map Art Mappa grafica + First Surface Prima superficie + Previous Surface Superficie precedente + Next Surface Superficie successiva + Last Surface Ultima superficie + Scale to Fit Ridimensiona per adattare + Shade Artwork Ombreggia grafica + Invisible Geometry Geometria invisibile Eyedropper Contagocce Sample Color from Screen Campiona colore dallo schermo This system has no screen color sampler Questo sistema non ha un campionatore di colore dello schermo diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 82f0917d4a..684d7037a6 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -614,6 +614,15 @@ digits Malayalam マラヤーラム数字 Shading Color 陰影のカラー Black Overprint ブラックオーバープリント Draw Hidden Faces 隠れた面を描画 + Map Art… アートをマップ… + Map Art アートをマップ + First Surface 最初の面 + Previous Surface 前の面 + Next Surface 次の面 + Last Surface 最後の面 + Scale to Fit サイズに合わせる + Shade Artwork アートワークに陰影をつける + Invisible Geometry 不可視のジオメトリ Revolve… 回転体… Inflate… 膨張… Materials… マテリアル… diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 4f7f783e00..84cdbad530 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -2679,6 +2679,15 @@ Shading Color დაჩრდილვის ფერი Black Overprint ზედდაბეჭდილი შავი Draw Hidden Faces დამალული წახნაგების დახატვა + Map Art… ნახატის მიბმა… + Map Art ნახატის მიბმა + First Surface პირველი ზედაპირი + Previous Surface წინა ზედაპირი + Next Surface შემდეგი ზედაპირი + Last Surface ბოლო ზედაპირი + Scale to Fit მასშტაბირება მორგებით + Shade Artwork ნახატის დაჩრდილვა + Invisible Geometry უხილავი გეომეტრია Revolve… ბრუნვა… Inflate… გაბერვა… Materials… მასალები… diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 90690432ab..6fee2a120d 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -607,6 +607,15 @@ digits Malayalam 말라얄람어 Shading Color 셰이딩 색상 Black Overprint 검정 겹쳐찍기 Draw Hidden Faces 숨겨진 면 그리기 + Map Art… 아트 매핑… + Map Art 아트 매핑 + First Surface 첫 번째 표면 + Previous Surface 이전 표면 + Next Surface 다음 표면 + Last Surface 마지막 표면 + Scale to Fit 크기에 맞게 조절 + Shade Artwork 아트워크 음영 처리 + Invisible Geometry 보이지 않는 형상 Revolve… 회전체… Inflate… 부풀리기… Materials… 재질… diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 4c9b87bdcd..90e79c7f0f 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -1108,6 +1108,17 @@ liquify-list-end {0}, {1} {0} en {1} Shading Color Arceringskleur Black Overprint Zwart overprinten Draw Hidden Faces Verborgen vlakken tekenen + Map Art… Artwork toewijzen… + Map Art Artwork toewijzen + First Surface Eerste oppervlak + Previous Surface Vorig oppervlak + Next Surface Volgend oppervlak + Last Surface Laatste oppervlak + Horizontal Scale Horizontale schaal + Vertical Scale Verticale schaal + Scale to Fit Schalen om te passen + Shade Artwork Artwork arceren + Invisible Geometry Onzichtbare geometrie Revolve… Draaien… Inflate… Opblazen… Materials… Materialen… diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 16f73aee32..6cd49c3a61 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -509,6 +509,15 @@ Shading Color Kolor cieniowania Black Overprint Czarny nadruk Draw Hidden Faces Rysuj ukryte ściany + Map Art… Mapuj grafikę… + Map Art Mapuj grafikę + First Surface Pierwsza powierzchnia + Previous Surface Poprzednia powierzchnia + Next Surface Następna powierzchnia + Last Surface Ostatnia powierzchnia + Scale to Fit Skaluj, aby dopasować + Shade Artwork Cieniuj grafikę + Invisible Geometry Niewidoczna geometria Revolve… Obrót… Inflate… Nadmuchanie… Materials… Materiały… diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 437c4fad9e..64917fc1f3 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -1173,6 +1173,15 @@ antiAlias Sharp Nítido Shading Color Cor do Sombreamento Black Overprint Preto em Sobreimpressão Draw Hidden Faces Desenhar Faces Ocultas + Map Art… Mapear Ilustração… + Map Art Mapear Ilustração + First Surface Primeira Superfície + Previous Surface Superfície Anterior + Next Surface Próxima Superfície + Last Surface Última Superfície + Scale to Fit Dimensionar para Caber + Shade Artwork Sombrear Ilustração + Invisible Geometry Geometria Invisível Eyedropper Conta-gotas Eyedropper Applies: O Conta-gotas Aplica: Eyedropper Options Opções do Conta-gotas diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index e2d2f64681..b25bc3ac4b 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -1281,6 +1281,15 @@ font-technology Variable Вариативные Shading Color Цвет затенения Black Overprint Чёрный с наложением Draw Hidden Faces Рисовать скрытые грани + Map Art… Наложение графики… + Map Art Наложение графики + First Surface Первая поверхность + Previous Surface Предыдущая поверхность + Next Surface Следующая поверхность + Last Surface Последняя поверхность + Scale to Fit Масштабировать по размеру + Shade Artwork Затенять графику + Invisible Geometry Невидимая геометрия Eyedropper Пипетка Sample Color from Screen Взять цвет с экрана This system has no screen color sampler В этой системе нет средства выбора цвета с экрана diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index e3c57c8881..1a3b828014 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -1252,6 +1252,15 @@ font-technology Variable Variabla Shading Color Skuggningsfärg Black Overprint Svart övertryck Draw Hidden Faces Rita dolda ytor + Map Art… Mappa bildmaterial… + Map Art Mappa bildmaterial + First Surface Första ytan + Previous Surface Föregående yta + Next Surface Nästa yta + Last Surface Sista ytan + Scale to Fit Skala för att passa + Shade Artwork Skugga bildmaterial + Invisible Geometry Osynlig geometri Eyedropper Pipett Eyedropper Applies: Pipetten tillämpar: Eyedropper Options Pipettalternativ diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index dd38a79f1b..7a1a4484da 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -1250,6 +1250,15 @@ font-technology Variable Değişken Shading Color Gölgeleme Rengi Black Overprint Siyah Üst Baskı Draw Hidden Faces Gizli Yüzleri Çiz + Map Art… Çizimi Eşle… + Map Art Çizimi Eşle + First Surface İlk Yüzey + Previous Surface Önceki Yüzey + Next Surface Sonraki Yüzey + Last Surface Son Yüzey + Scale to Fit Sığacak Şekilde Ölçekle + Shade Artwork Çizimi Gölgelendir + Invisible Geometry Görünmez Geometri Eyedropper Damlalık Sample Color from Screen Ekrandan Örnek Renk This system has no screen color sampler Bu sistemin ekran rengi örnekleyicisi yok diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index bdf4262aa2..477451770c 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1289,6 +1289,15 @@ font-technology Variable Варіативні Shading Color Колір затінення Black Overprint Чорний із накладенням Draw Hidden Faces Малювати приховані грані + Map Art… Накладання графіки… + Map Art Накладання графіки + First Surface Перша поверхня + Previous Surface Попередня поверхня + Next Surface Наступна поверхня + Last Surface Остання поверхня + Scale to Fit Масштабувати за розміром + Shade Artwork Затінювати графіку + Invisible Geometry Невидима геометрія Eyedropper Піпетка Sample Color from Screen Взяти колір з екрана This system has no screen color sampler У цій системі немає засобу вибору кольору з екрана diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 936fa2646a..8cc9ea0826 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -1469,6 +1469,15 @@ font-technology Variable Biến thiên Shading Color Màu tô bóng Black Overprint Đen in chồng Draw Hidden Faces Vẽ các mặt ẩn + Map Art… Ánh xạ tác phẩm… + Map Art Ánh xạ tác phẩm + First Surface Bề mặt đầu tiên + Previous Surface Bề mặt trước + Next Surface Bề mặt tiếp theo + Last Surface Bề mặt cuối cùng + Scale to Fit Co giãn cho vừa + Shade Artwork Tô bóng tác phẩm + Invisible Geometry Hình học vô hình Eyedropper Ống hút màu Sample Color from Screen Lấy mẫu màu từ màn hình This system has no screen color sampler Hệ thống này không có công cụ lấy mẫu màu trên màn hình diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 2043394463..1e47ab17e7 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -1226,6 +1226,15 @@ antiAlias Sharp 锐利 Shading Color 底纹颜色 Black Overprint 黑色叠印 Draw Hidden Faces 绘制隐藏表面 + Map Art… 贴图… + Map Art 贴图 + First Surface 第一个表面 + Previous Surface 上一个表面 + Next Surface 下一个表面 + Last Surface 最后一个表面 + Scale to Fit 缩放以适合 + Shade Artwork 为图稿添加底纹 + Invisible Geometry 无形几何形状 Eyedropper 吸管 Sample Color from Screen 从屏幕取样颜色 This system has no screen color sampler 此系统没有屏幕取色工具 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 72ce896800..7e7d378370 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -1259,6 +1259,15 @@ font-technology Variable 可變 Shading Color 網底顏色 Black Overprint 黑色疊印 Draw Hidden Faces 繪製隱藏表面 + Map Art… 貼圖… + Map Art 貼圖 + First Surface 第一個表面 + Previous Surface 上一個表面 + Next Surface 下一個表面 + Last Surface 最後一個表面 + Scale to Fit 縮放以符合 + Shade Artwork 為圖稿加上網底 + Invisible Geometry 隱形幾何形狀 Eyedropper 滴管 Sample Color from Screen 從螢幕取樣顏色 This system has no screen color sampler 此系統沒有螢幕取色工具 diff --git a/crates/ui-egui/src/panels/symbols.rs b/crates/ui-egui/src/panels/symbols.rs index 048260b45e..373dbdb946 100644 --- a/crates/ui-egui/src/panels/symbols.rs +++ b/crates/ui-egui/src/panels/symbols.rs @@ -24,6 +24,16 @@ use crate::menus::Item; use crate::theme::Tokens; use crate::widgets::{self, PanelDrag, menu_item}; +/// The largest side of a symbol thumbnail, in pixels. A larger chip draws its thumbnail scaled up. +const MAX_THUMB_PX: f32 = 1024.0; + +/// The pixels on a side of the thumbnail for a chip `size` points wide at `pixels_per_point`: 8 +/// to [`MAX_THUMB_PX`]. +fn thumb_px(size: f32, pixels_per_point: f32) -> u32 { + let px = (size * pixels_per_point).round(); + if px.is_nan() { 8 } else { px.clamp(8.0, MAX_THUMB_PX) as u32 } +} + /// A thumbnail of symbol `name` (an instance at its natural size), cached by its key in `keys` /// ([`Thumbs`]). fn thumb(ui: &Ui, doc: &Document, keys: &Thumbs, name: &str, size: f32) -> Option { @@ -31,7 +41,7 @@ fn thumb(ui: &Ui, doc: &Document, keys: &Thumbs, name: &str, size: f32) -> Optio static RENDERER: RefCell = RefCell::new(vectorcraft_render::Renderer::new()); static CACHE: crate::graphics::TexCache> = crate::graphics::TexCache::default(); } - let px = (size * ui.ctx().pixels_per_point()).round().max(8.0) as u32; + let px = thumb_px(size, ui.ctx().pixels_per_point()); let key = (*keys.keys.get(name)?, px); if let Some(t) = CACHE.with(|c| c.borrow().get(&key).cloned()) { return Some(t); @@ -134,6 +144,67 @@ pub(crate) fn chip(ui: &Ui, doc: &Document, keys: &Thumbs, r: egui::Rect, name: } } +/// The cache key of an [`art_chip`]: the symbol's key, the pixels across and down, and the bits of +/// the art's bounds. +type ArtKey = (u64, u32, u32, [u64; 4]); + +/// Symbol `name`'s art on white in `r`, its bounds `art` (at its own size, as a mapped graphic +/// measures them) stretched to fill `r`, as a box the art is scaled into shows it. The art is +/// rendered at most [`MAX_THUMB_PX`] pixels on a side, cached by its key in `keys`. +pub(crate) fn art_chip(ui: &Ui, doc: &Document, keys: &Thumbs, r: egui::Rect, name: &str, art: vectorcraft_geom::Rect) { + thread_local! { + static RENDERER: RefCell = RefCell::new(vectorcraft_render::Renderer::new()); + static CACHE: crate::graphics::TexCache> = crate::graphics::TexCache::default(); + } + ui.painter().rect_filled(r, 0.0, egui::Color32::WHITE); + let ppp = ui.ctx().pixels_per_point(); + let (w, h) = (thumb_px(r.width(), ppp), thumb_px(r.height(), ppp)); + let Some(&symbol) = keys.keys.get(name) else { return }; + let key = (symbol, w, h, [art.x0, art.y0, art.x1, art.y1].map(f64::to_bits)); + let tex = match CACHE.with(|c| c.borrow().get(&key).cloned()) { + Some(t) => t, + None => { + let Some(img) = RENDERER.with(|rr| render_art(&mut rr.borrow_mut(), doc, name, art, (w, h))) else { return }; + let tex = ui.ctx().load_texture(format!("sym-art-{name}-{w}x{h}"), crate::canvas::color_image(&img), egui::TextureOptions::LINEAR); + CACHE.with(|c| { + let mut c = c.borrow_mut(); + if c.len() > 64 { + c.clear(); + } + c.insert(key, tex.clone()); + }); + tex + } + }; + ui.painter().image(tex.id(), r, egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), egui::Color32::WHITE); +} + +/// Symbol `name` of `doc` (an instance at its natural size, as [`render_thumb`] places it) drawn +/// into `w` × `h` pixels with its bounds `art` stretched to fill them. `None` for bounds with no +/// area. +fn render_art( + r: &mut vectorcraft_render::Renderer, + doc: &Document, + name: &str, + art: vectorcraft_geom::Rect, + (w, h): (u32, u32), +) -> Option { + let (aw, ah) = (art.width(), art.height()); + if !(aw.is_finite() && ah.is_finite() && aw > 0.0 && ah > 0.0) { + return None; + } + let (sw, sh) = symbol_size(doc, name); + let mut d = doc.clone(); + let layer = d.alloc_id(); + d.layers = vec![Arc::new(Node::layer(layer, "Preview", vectorcraft_doc::LayerColor::Preset(0)))]; + let id = d.alloc_id(); + let xf = vectorcraft_geom::Affine::scale_non_uniform(sw / 20.0, sh / 20.0); + let n = Arc::new(Node::new(id, NodeKind::SymbolInstance { symbol: name.into(), xf })); + let view = + vectorcraft_geom::Affine::scale_non_uniform(f64::from(w) / aw, f64::from(h) / ah) * vectorcraft_geom::Affine::translate((-art.x0, -art.y0)); + r.render_node(&d, &n, u16::try_from(w).ok()?, u16::try_from(h).ok()?, view) +} + /// The active document's current symbol (`symbol.list`'s `current`), read without running a /// command; `None` without a document or symbols. fn current(app: &VectorcraftApp) -> Option { @@ -865,6 +936,35 @@ mod tests { (painted.len(), red) } + /// A thumbnail is at most 1,024 pixels on a side, whatever the size of the chip it draws. + #[test] + fn thumbnails_are_bounded_in_size() { + assert_eq!(thumb_px(40.0, 2.0), 80); + assert_eq!(thumb_px(1.0, 1.0), 8); + assert_eq!(thumb_px(100_000.0, 2.0), 1024); + assert_eq!(thumb_px(f32::NAN, 1.0), 8); + } + + /// Art drawn into a box fills the box, its bounds stretched to the box's proportions, as the + /// art's map scales it; art with no area draws nothing. + #[test] + fn mapped_art_fills_its_box_in_the_box_s_proportions() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 20})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + s.execute("symbol.new", &json!({"name": "Wide"})).unwrap(); + let doc = &*s.doc().unwrap().doc; + let art = vectorcraft_effects::graphic_bounds(doc, "Wide").expect("the art's bounds"); + let mut r = vectorcraft_render::Renderer::new(); + // A square box draws the 2:1 art stretched to fill it, as its map scales it. + let img = render_art(&mut r, doc, "Wide", art, (40, 40)).expect("the art"); + let (painted, red) = painted(&img); + assert!(red * 10 >= 40 * 40 * 9 && red == painted, "{painted} painted, {red} red"); + assert!(render_art(&mut r, doc, "Wide", vectorcraft_geom::Rect::new(0.0, 0.0, 0.0, 10.0), (40, 40)).is_none()); + } + /// A symbol that nests another (a library's included) shows the nested art in its /// thumbnail: the preview keeps the document's symbols and patterns, not its art. #[test] diff --git a/crates/ui-egui/src/shortcut_editor.rs b/crates/ui-egui/src/shortcut_editor.rs index 8d79863b48..83bced108c 100644 --- a/crates/ui-egui/src/shortcut_editor.rs +++ b/crates/ui-egui/src/shortcut_editor.rs @@ -802,9 +802,9 @@ fn listed(overrides: &Overrides, e: &Entry) -> bool { /// Options, Character, Set Bounds), the exports and saves that give the file back without a `path` /// (Save Document gives the file back when the document has no file yet; File › Save takes a key /// instead), the undo group's begin and end, and the commands that need a point, a value or a name -/// (Create Dimension, Edit Freeform Point, Select by Color, Move Brush, Paintbrush). New Symbol is left out +/// (Create Dimension, Edit Freeform Point, Select by Color, Move Brush, Paintbrush, Map Art). New Symbol is left out /// because the Symbols panel runs it through the Symbol Options dialog. -const NEEDS_A_PARAM: [&str; 75] = [ +const NEEDS_A_PARAM: [&str; 76] = [ "transparency.set", "transparency.setOpacityMask", "stroke.set", @@ -879,6 +879,7 @@ const NEEDS_A_PARAM: [&str; 75] = [ "text.setFormat", "text.setRangeStyle", "text.setStyle", + "threeD.mapArt", "type.ruby", ]; diff --git a/docs/effects-parity.md b/docs/effects-parity.md index d92dc159f7..1b0d755ff8 100644 --- a/docs/effects-parity.md +++ b/docs/effects-parity.md @@ -181,13 +181,13 @@ VectorCraft choices; an original approximation, never compared with another appl | Revolve | initial: live, editable profile, rotation and light gizmos, default-on Cap with continuous curved rims that also closes a partial sweep's cut sides, smooth vector shading and round seam joins, overlapping faces drawn in the order of their depths where they overlap, SVG/PDF output, Expand Appearance ([revolve.md](revolve.md), #846) | | Extrude & Bevel, Inflate, Rotate | initial: live, round seam joins, depth, twist, taper, solid or hollow caps, five original bevel shapes, Inflate volume, both sides, twist, taper and cap, Rotate of every fill and stroke, groups and layers turned about one shared axis (#4506), contours that cross, touch or overlap merged first ([three-d.md](three-d.md)), Position presets, rotation and light gizmos, SVG/PDF output, Expand Appearance ([three-d.md](three-d.md)) | | Materials panel, lighting, ray-traced render | Window › 3D and Materials panel with the object types (Plane, Extrude, Revolve, Inflate) and the Object, Rotation and Lighting settings of the applied effect, Render Settings › Wireframe, which draws the live effect as the edges of its faces, and Quick Actions › Expand as Wireframes ([three-d.md](three-d.md#3d-and-materials-panel)); one to ten directional lights with per-light Color (opaque RGB, white by default), Intensity, Rotation, Height, Softness and neutral Ambient Light, Revolve and colored Inflate use smooth vector shading; Extrude & Bevel and Rotate retain planar shading; original Standard, Diffuse, Top Left and Right lighting rigs; shadows behind or below the object from the first light, blurred by its Softness ([three-d.md](three-d.md#shadows)); the Materials tab's Graphics, document symbols mapped onto Extrude & Bevel's caps and onto a plane, moved with an artboard handle, and wrapped around Extrude & Bevel's walls and bevels and around Revolve's side ([three-d.md](three-d.md#graphics)); no base materials, graphics on Inflate, or ray tracing | -| 3D (Classic): Extrude & Bevel, Revolve, Rotate | Extrude & Bevel (Classic) initial: live, round seam joins, Extrude Depth, Cap, five original bevel shapes with Height and Bevel Extent In or Out, Position presets and rotation gizmo, Perspective, Wireframe, No Shading, Diffuse and Plastic surfaces with one to ten lights, Light Intensity, Ambient Light, Highlight Intensity and Size, Blend Steps, Black, Custom, Black Overprint or no Shading Color ([Black Overprint](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=188)), Draw Hidden Faces ([create 3D objects](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/create-3d-objects.html)); Revolve (Classic) initial: live, round seam joins, Angle, Cap, Offset from the left or right edge, Position presets and rotation gizmo, Perspective, the same four surfaces, lights, highlight, Blend Steps and Shading Color, groups and layers revolved about one shared axis (same page); Rotate (Classic) initial: live, round seam joins, every fill and stroke turned as one plane, Position presets and rotation gizmo, Perspective, No Shading and Diffuse surfaces with lights, Ambient Light, Blend Steps and Shading Color ([rotate objects in 3D](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/rotate-objects-in-3d.html)); Preserve Spot Colors in all three, unavailable with a Custom Shading Color ([Preserve Spot Color](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=260)); all three: a lighting sphere on the Lighting tab whose lights drag, move to the back or front, and are added at the front center or deleted down to one ([lighting options](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=272)); all three: the track cube (face, edge, Shift and ring drags, keyboard steps; [three-d.md](three-d.md#track-cube)); Map Art: none | +| 3D (Classic): Extrude & Bevel, Revolve, Rotate | Extrude & Bevel (Classic) initial: live, round seam joins, Extrude Depth, Cap, five original bevel shapes with Height and Bevel Extent In or Out, Position presets and rotation gizmo, Perspective, Wireframe, No Shading, Diffuse and Plastic surfaces with one to ten lights, Light Intensity, Ambient Light, Highlight Intensity and Size, Blend Steps, Black, Custom, Black Overprint or no Shading Color ([Black Overprint](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=188)), Draw Hidden Faces ([create 3D objects](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/create-3d-objects.html)); Revolve (Classic) initial: live, round seam joins, Angle, Cap, Offset from the left or right edge, Position presets and rotation gizmo, Perspective, the same four surfaces, lights, highlight, Blend Steps and Shading Color, groups and layers revolved about one shared axis (same page); Rotate (Classic) initial: live, round seam joins, every fill and stroke turned as one plane, Position presets and rotation gizmo, Perspective, No Shading and Diffuse surfaces with lights, Ambient Light, Blend Steps and Shading Color ([rotate objects in 3D](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/rotate-objects-in-3d.html)); Preserve Spot Colors in all three, unavailable with a Custom Shading Color ([Preserve Spot Color](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=260)); all three: a lighting sphere on the Lighting tab whose lights drag, move to the back or front, and are added at the front center or deleted down to one ([lighting options](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=272)); all three: the track cube (face, edge, Shift and ring drags, keyboard steps; [three-d.md](three-d.md#track-cube)); Map Art for Extrude & Bevel (Classic) and Revolve (Classic): one document symbol on each numbered surface, surface navigation with visible and hidden marks and a red outline on the artboard, move, scale and rotate on the surface laid out flat, Scale to Fit, Clear, Clear All, Shade Artwork, Invisible Geometry, kept by Expand Appearance and exports, `threeD.mapArt` ([map artwork to a 3D object](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=189)) | | Turntable (30.0 beta) | none | | Export 3D objects (OBJ, USDA, glTF) | initial: Asset Export's Export 3D Object, and the 3D and Materials panel's Export 3D Object button (which then shows Asset Export with the new assets selected, [three-d.md](three-d.md#3d-and-materials-panel)), collect an object with Extrude & Bevel, Revolve, Inflate or Rotate as a 3D asset, and Export writes its solids as a USDA (the default), USDZ, glTF or OBJ mesh with a material in each solid's paint color (`assets.add3D`, `assets.set3DFormat`, `assets.export3D`); graphics mapped onto a plane or Extrude & Bevel's caps are exported as PNG textures of those faces, flat and unlit; no graphics on Revolve's side, no materials and no shading ([3D export help](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/export-3d-vector-artwork.html)) | The `three-d` crate (depends on `geom` and `pathops`, with no UI or GPU dependencies) builds, rotates, projects, shades and depth-sorts the surfaces; the effects crate turns them into art. What's left (materials and shadows, ray-traced rendering, -angular cut caps, exact visibility, the rest of 3D Classic (Map Art), Turntable) is 25–45 h. +angular cut caps, exact visibility, Turntable) is 25–45 h. ## Revision history diff --git a/docs/gaps.md b/docs/gaps.md index 46af191a44..99d90ed106 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -710,9 +710,9 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi - **Done:** an initial live Revolve in the `three-d` crate (#846, from the contributor who offered in #605), with automatic smooth vector shading, default-on circular caps and spike-free continuous rims; Extrude & Bevel, Inflate and Rotate with Position presets ([three-d.md](three-d.md), #1407). Colored Inflate has automatic smooth vector lighting from shared membrane normals. White-light Inflate keeps its polygon shading. Every 3D facet's seam has round joins ([three-d.md](three-d.md#seams)). All four take one to ten colored directional lights, with neutral ambient applied once, a light list and independent previewing controls. Standard, Diffuse, Top Left and Right select original rigs, shared with commands; manual settings show Custom. - **Missing:** materials (base, Substance, graphics), shadows, - ray-traced rendering, angular cut caps, exact visibility for intersecting and concave surfaces, the rest of 3D - Classic (Map Art), Turntable, and in 3D export the graphics on Revolve's side, materials and shading (graphics on - planes and Extrude & Bevel's caps are exported as textures). + ray-traced rendering, angular cut caps, exact visibility for intersecting and concave surfaces, Turntable, and in + 3D export the graphics on Revolve's side, materials and shading (graphics on planes and Extrude & Bevel's caps + are exported as textures). - **Impact:** specialist; Materials is the one menu stub left. - **Estimate:** 25–45 h; plan in `plan/` before coding. diff --git a/docs/mcp.md b/docs/mcp.md index f6380a48c7..3dcda5b431 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5043,6 +5043,50 @@ another shading color is refused with an error and the document is not changed. {"name":"run_command","arguments":{"command":"effect.apply","params":{"effect":"threeD.classicRotate","item":null,"params":{"rotationX":0,"rotationY":40,"rotationZ":0,"surface":"diffuse","blendSteps":64}}}} ``` +## Map Art + +`threeD.mapArt {surface?, symbol?, x?, y?, scaleX?, scaleY?, rotation?, fit?, clearAll?, shade?, invisible?, index?, item?, ids?|id?}` +is the Map Art… button of the Extrude & Bevel (Classic) and Revolve (Classic) dialogs. It maps a document symbol onto +one numbered surface of each selected object's classic 3D effect, edits that map or removes it, in one undo step +([Map artwork to a 3D object](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=189)). +Rotate (Classic) and the other 3D effects take no map. + +- `surface` is a whole number from 1 to the object's surface count. Extrude & Bevel (Classic) numbers the surfaces + through the object's solids in the order they are built: each solid's front cap and back cap, then each side wall + from corner to corner of the outline, then the bevel above each wall. A hollow solid (`cap` false) has no caps, so + its numbering starts at its first side wall. A side wall is laid out at its own length, and a bevel at the length of + the wall below it. Revolve (Classic) has one surface, its swept + side; on a group it is the side of the member with the longest profile, and the other members take no map. The + numbering is VectorCraft's own. +- `symbol` names the symbol mapped onto the surface, and `null` removes the surface's map, also a map kept past the + object's surface count; `null` with `x`, `y`, + `scaleX`, `scaleY`, `rotation` or `fit: true` is refused. Omitted, the surface keeps its map's symbol; a surface with + no map then is refused. +- `x` and `y` (points, -1000000..1000000) place the center of the art from the center of the surface laid out flat, + `scaleX` and `scaleY` (1..10000%) scale it from the symbol's own size, and `rotation` (-360..360 degrees) turns it + counterclockwise. A new map starts at 0, 0, 100%, 100% and 0°. +- `fit` (Scale to Fit) centers the art and scales it to fill the surface. +- `clearAll` (Clear All) removes every map first, so with `surface` only that surface's map is left. +- `shade` (Shade Artwork) gives the mapped art the tone and highlight of its face, and `invisible` (Invisible + Geometry) draws only the mapped art. + +One of `surface`, `clearAll`, `shade` and `invisible` is required. Without `index` each object's first Extrude & +Bevel (Classic) or Revolve (Classic) is edited, its own before its fills' and strokes'; `item` needs `index`. A surface +past the count (except to remove a map kept there), an unknown symbol, a value out of range, an unknown key or an object without one of the two effects is +refused, and nothing changes. When nothing changes, no undo step is recorded. It returns `{ids, maps}`: the objects +changed and the first object's maps. + +The maps are the effects' `mapArt` (up to 64 `{surface, symbol, x, y, scaleX, scaleY, rotation}` objects), +`mapShade` and `mapInvisible` parameters, which `effect.setParams` also edits. A map past the object's surface count +draws nothing, as the archived reference describes; the Wireframe surface draws no mapped art. The canvas, exports and +`effect.expandAppearance` draw the mapped art the same way, and renaming a symbol renames it in the maps. The limits +and the shading of the mapped art are VectorCraft's own; see [three-d.md](three-d.md#map-art). + +```json +{"name":"run_command","arguments":{"command":"threeD.mapArt","params":{"surface":1,"symbol":"Label","fit":true}}} +{"name":"run_command","arguments":{"command":"threeD.mapArt","params":{"surface":3,"symbol":null}}} +``` + ## Edit Colors and Recolor Artwork diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 157050b5f4..302f55829f 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -262,7 +262,7 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Colour, swatches, gradients, patterns, mesh, recolor | 7 | 92% | Picker Lab entry, picker libraries and Assign-row menus complete the deferred #4028 UI paths (#8031); scores and estimates unchanged; Eyedropper copies effective character dimensions across text transforms (#6404); 30.0's gradient additions are done (dither, perceptual blending, presets); freeform gradients in SVG/PDF, mixed spot/process gradients in SVG, PDF gradients mixing a spot color with RGB or Lab stops, and dithered spot gradient fills and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, which PDF export writes as images in process colors| 4–7 | estimated; Recolor model selection is available through the engine and MCP (#2520), and the dialog's color sliders (HSB, RGB, CMYK, Lab, Tint for a spot color) edit the selected row's new color in its mode, and the Edit tab's Global Adjust sliders (Saturation, Brightness, Temperature, Luminosity, -100% to 100%) change every recolored color at once (lowered from 96%: target moved); unpainted zero-width stroke restoration fixed (#1253), score and hours unchanged; Eyedropper source reads regression-tested (#1251); screen-bounded Recolor Edit chip list (#3416), score and hours unchanged; a point on a gradient mesh's outline locates on its edge on every side (#7006: `mesh_locate_takes_a_point_on_any_side_of_the_outline`, `mesh_add_line_exactly_on_the_edge_needs_no_tolerance`), score and hours unchanged; Color panel spectrum grows with the resized panel (#8005) | | Strokes, brushes, width profiles | 5 | 88% | Shift-double-click adjoining adjustment is implemented; brush libraries are done (eleven generated libraries including Tech Circuit, Pressure Sensitive, Ink and Wash, Bristle Brushes, Game Trails, Energy Beams and Dry Media, User Defined, Other Library…, Save Brushes); Art brush Overlap and Pattern brush auto corners are done; remaining: pen pressure on macOS, Stylus Wheel, more built-in brush libraries, tilt, bearing and rotation for Art, Pattern and Bristle brushes and on native Wayland and the web | 8–15 | estimated; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed; evidence below; finite-arithmetic follow-up regressions and full CI passed (evidence below) | | Appearance, transparency, graphic styles, masks | 5 | 97% | raster effect reach in preview bounds | 1–2 | estimated; Transform typing, sliders, preview, and undo are covered in `crates/ui-egui/src/panels/tests_appearance.rs` | -| 3D and Materials (and Turntable) | 4 | ~25% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, painter visibility); materials, light presets, shadows, ray tracing, the rest of 3D Classic (Map Art), Turntable views, textures, map art and shading in 3D export | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12); every 3D seam has round joins (2026-11-12, [three-d.md](three-d.md#seams)), score, gaps and hours unchanged | +| 3D and Materials (and Turntable) | 4 | ~25% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, painter visibility); materials, light presets, shadows, ray tracing, Turntable views, textures, map art and shading in 3D export | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12); Map Art on Extrude & Bevel (Classic) and Revolve (Classic) is covered by `crates/effects/src/solids/tests_map_art.rs` and `crates/engine/src/cmd/effectcmd/map_art_tests.rs` (score and hours unchanged); every 3D seam has round joins (2026-11-12, [three-d.md](three-d.md#seams)), score, gaps and hours unchanged | | Type core | 9 | 80% | Auto-leading style resets are implemented; Hyphenation… and Justification… options are done (#2310, #2755), and a paragraph's Auto Leading also sets the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; remaining: Optical Margin Alignment, Middle Eastern features beyond bidi layout (the Middle Eastern & South Asian and Standard composers are done per paragraph, #4935; `.ai`/EPS/PDF files carry no composer), optional group font-size preservation; transformed character controls fixed (#1034), see [type-parity.md](type-parity.md) | 14–19 | estimated; eleven-language pattern hyphenation in both composers, with grapheme and shaping-cluster protection (#4947, `hyphen::tests` and `layout::wrapping_tests`); Sanskrit patterns pending an allowlisted source; recent-font groups in font pickers (#3515); full-name font matches regression-tested (#1258); mixed paragraph alignment indication implemented; headless regressions, full integration CI and visual review pass; localized legacy family-name fallback with loaded/catalog regressions (#2208); Fractional Widths per type object regression-tested; color emoji fonts with bitmap glyphs (`sbix`, `CBDT`) draw and export; threading ports: every selected area type and type on a path shows its in and out ports (empty, arrow, red "+"), and the Selection tool threads from either, the in port into a frame before it, and a double-click on a threaded port breaks the thread there (`threads::tests::break_splits_the_thread_and_the_story_flows_into_the_first_part`, `select::tests::a_double_click_on_a_threaded_port_breaks_the_thread`, `canvas::tests::a_double_click_on_a_threaded_out_port_breaks_the_thread`) (#2572; `select::tests::a_click_on_the_in_port_threads_into_a_frame_before_it`, `text::tests::selected_type_shows_its_ports_in_each_state`, `threads::tests::add_before_threads_the_story_from_the_new_frame_into_the_clicked_one`, live screenshot); the Glyphs panel highlights and scrolls to the character selected with the Type tool (#4908, `panels::glyphs` tests); the OpenType panel lists only `ss01`–`ss20` sets present in the selected font and uses its custom names when supplied; Type-range desktop Copy publishes styled art and keeps font family, size and color on canvas Paste after editing (#5636); paint-only Arabic harakat keep joining with conditional GDEF-mark ownership and Insert Kashidas base-letter paint (`tests::harakat`) | | Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (ruby, mojikumi), variable font axes, tab leaders, Touch Type, Retype | 20–28 | estimated; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | | Symbols, blends, envelopes, Repeat, perspective | 5 | 88% | remaining: dynamic symbols' `.ai` round trip, further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons and Weather Icons are done), envelope Anti-Alias/Preserve Shape, 9-slice guides outside the art; Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guides (drawn and draggable during symbol editing, #5280) and Symbol Type (dynamic on-canvas fill/stroke including gradient/pattern, opacity and blend, #4938) are done | 4–7 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested | @@ -270,7 +270,7 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Symbols, blends, envelopes, Repeat, perspective | 5 | 88% | remaining: dynamic symbols' `.ai` round trip, further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons and Weather Icons are done), envelope Anti-Alias/Preserve Shape, 9-slice guides outside the art; Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guides (drawn and draggable during symbol editing, #5280) and Symbol Type (dynamic on-canvas fill/stroke including gradient/pattern, opacity and blend, #4938) are done | 4–7 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested | | Image Trace, graphs, image tools | 3 | 75% | graph Column designs, Image Trace Create Strokes depth (Create Object Mosaic is done; junction-returning piece survival has source-generated regressions in `image-trace-quality.md`; simpler contour walk, identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments, so Paths is monotone on the code-drawn sweep) | 5–8 | estimated (raised from 72%); quick presets reveal adjustment controls, Properties reopens them; Live trace result bounds and selection highlights exclude the retained bitmap except in source-image views (scores/hours unchanged); Create Object Mosaic's dialog with New Size, Constrain Ratio, Resize Using Percentages and Use Ratio is covered by `dialogs::object_mosaic::tests` (score, gaps and hours unchanged); High Fidelity Photo traces in Full Tone with abutting shapes, summed mean pixel difference over 19 test images 80.5 to 65.6 levels ([quality notes](image-trace-quality.md#high-fidelity-photo-in-full-tone)), score, gaps and hours unchanged | | Live vector effects | 5 | 85% | Outline Object, SVG Filters | 4–8 | measured count 49/50 (Pathfinder 13/13 with Trap), depth estimated; Warp Options controls verified by focused checks and original-image review | -| 3D and Materials (and Turntable) | 4 | ~25% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, original lighting presets, painter visibility), Revolve (Classic) with Angle, Cap, Offset and the Plastic, Diffuse, No Shading and Wireframe surfaces, the Quick Actions › Expand as Wireframes command (#6354), the Render Settings › Wireframe mode on Extrude & Bevel, Revolve, Inflate and Rotate; materials, shadows, ray tracing, the rest of 3D Classic (Map Art), Turntable views, textures, map art and shading in 3D export | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12); Revolve (Classic) is covered by the `revolve::classic` tests and `dialogs::revolve::tests::classic_revolve_shows_its_options_and_applies_as_one_step`; Expand as Wireframes is covered by `crates/effects/src/solids/wireframe/tests.rs` and `crates/engine/src/cmd/wireframe/tests.rs`, and Render Settings › Wireframe by `crates/effects/src/solids/wireframe/tests.rs` and `crates/ui-egui/src/panels/tests_three_d.rs` (score, gaps and hours unchanged); every 3D seam has round joins (2026-11-12, [three-d.md](three-d.md#seams)), score, gaps and hours unchanged | +| 3D and Materials (and Turntable) | 4 | ~25% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, original lighting presets, painter visibility), Revolve (Classic) with Angle, Cap, Offset and the Plastic, Diffuse, No Shading and Wireframe surfaces, the Quick Actions › Expand as Wireframes command (#6354), the Render Settings › Wireframe mode on Extrude & Bevel, Revolve, Inflate and Rotate; materials, shadows, ray tracing, Turntable views, textures, map art and shading in 3D export | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12); Map Art on Extrude & Bevel (Classic) and Revolve (Classic) is covered by `crates/effects/src/solids/tests_map_art.rs` and `crates/engine/src/cmd/effectcmd/map_art_tests.rs` (score and hours unchanged); Revolve (Classic) is covered by the `revolve::classic` tests and `dialogs::revolve::tests::classic_revolve_shows_its_options_and_applies_as_one_step`; Expand as Wireframes is covered by `crates/effects/src/solids/wireframe/tests.rs` and `crates/engine/src/cmd/wireframe/tests.rs`, and Render Settings › Wireframe by `crates/effects/src/solids/wireframe/tests.rs` and `crates/ui-egui/src/panels/tests_three_d.rs` (score, gaps and hours unchanged); every 3D seam has round joins (2026-11-12, [three-d.md](three-d.md#seams)), score, gaps and hours unchanged | | Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (mojikumi), variable font axes, tab leaders, Touch Type, Retype | 20–28 | estimated; No Break keeps marked characters on one line; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | | Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (mojikumi), tab leaders, Touch Type, Retype | 20–28 | estimated; No Break keeps marked characters on one line; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | | Raster effects (Effect Gallery) | 4 | 55% | — | — | estimated (raised from 52%: the Effect Gallery's filter thumbnails and in-dialog preview, an original landscape drawing passed through each filter, [Filter Gallery overview](https://helpx.adobe.com/photoshop/desktop/effects-filters/get-started-with-filters/filter-gallery.html), `dialogs::effect_gallery::tests::gallery_shows_thumbnails_and_an_in_dialog_preview`; the gallery itself shipped in #2883, six categories, per-filter settings, ordered stack, live canvas preview, one undo step, `stack_ok_is_one_undo_step`, `stack_preview_is_one_interaction`); measured count 57/57 (Artistic complete with Colored Pencil, Fresco, Paint Daubs, Palette Knife, Rough Pastels and Underpainting; Sketch complete with Torn Edges and Conté Crayon, `pixel::tests_sketch::conte_crayon_*`); texture redraw distances optimized (#1257), pixels verified; the score stays under 100% because the filters are original approximations; depth estimated | diff --git a/docs/three-d.md b/docs/three-d.md index 4826df3552..ea4eeadb0e 100644 --- a/docs/three-d.md +++ b/docs/three-d.md @@ -559,6 +559,46 @@ These rules are VectorCraft's own: in the layers, in the art of symbols, patterns, graph designs, brushes and opacity masks, and in graphic styles, and Select All Unused in the Symbols panel counts a symbol a graphic uses as used, a graphic in a graphic style included. +## Map Art + +The Extrude & Bevel (Classic) and Revolve (Classic) dialogs have a **Map Art…** button on their Object tab. It +shows Map Art in place of the tabs until **Done**, and the dialog's Preview, OK and Cancel apply to the maps with the +other settings ([Map artwork to a 3D object](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=189), +[the same section in the 2010 help](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=274)). +Rotate (Classic) and the other 3D effects take no map. The command is `threeD.mapArt` ([mcp.md](mcp.md#map-art)). + +- **Surface**: the first, previous, next and last buttons and a number field pick the surface, with the count beside + them. A light gray mark shows that the surface faces the viewer and a dark gray mark that it is hidden. With Preview + on, the surface is outlined in red on the artboard. +- **Symbol**: None or one of the document's symbols. Each surface keeps one symbol. +- The surface is shown laid out flat with the box of the mapped art on it. A drag inside the box moves the art, a + drag of a side or corner handle scales it about its center, and a drag just outside the box turns it. X, Y, + Horizontal Scale, Vertical Scale and Rotation give the same values as numbers. +- **Scale to Fit** centers the art and scales it to fill the surface. **Clear** removes the surface's map, as None + does, and **Clear All** removes every map. +- **Shade Artwork** gives the mapped art the tone and highlight of the face it lies on. **Invisible Geometry** + draws the mapped art and leaves out the solid's faces. + +Extrude & Bevel (Classic) numbers its surfaces through the object's solids in the order they are built (the top fill's +solid, then each stroke's): each solid's front cap and back cap, then each side wall from corner to corner of the +outline, then the bevel above each wall. An extruded square has six surfaces. A hollow solid has no caps to number. +A side wall is laid out at its own length, which a bevel added around the shape makes longer than the outline. A bevel +is laid out at the length of the wall below it, so mapped art on a bevel is stretched or squeezed along its edge +nearer the cap. Revolve (Classic) has one surface, its swept side, unrolled around the axis as Revolve's graphics are; on a group it is +the side of the member with the longest profile, and Invisible Geometry leaves out every member's faces. The numbering +is VectorCraft's own. + +- A map's X and Y place the center of the art from the center of the surface laid out flat, so a map follows the + center when the surface changes size. A map past the object's surface count draws nothing and stays in the effect. +- Mapped art is drawn on the parts of its surface that face the viewer, clipped to the surface, and over a wall, a + bevel or Revolve's side it bends with the facets. The Wireframe surface draws no mapped art. +- The canvas, exports, printing and **Object › Expand Appearance** draw the mapped art the same way. Renaming a symbol + renames it in the maps, copying the object to another document brings the symbols its maps use, and Select All + Unused counts a symbol a map uses as used. +- A map's art follows the rules and limits of a graphic's art ([Graphics](#graphics)). An object takes up to 64 maps, + and its maps share the 400,000 path elements of one 3D effect's graphics; past that limit the object draws without + its mapped art. The limits and the shading of the mapped art are VectorCraft's own. + ## Parameters (`effect.apply`, `effect.setParams`) `threeD.extrude`: `depth`, `twist`, `taper` (%), `cap`, `bevel` (`none`, `classic`, `rounded`, `cove`, `step`, @@ -634,7 +674,8 @@ out, perspective). No Adobe software, assets, presets or bevel shapes were used. the faces are shaded with it is VectorCraft's own. The Black Overprint shading color keeps each face's paint and draws the shading over it as overprinting black, without the highlight. The shading is on the black plate in Separations Preview and PDF output. Their Rotation tab has the track cube - ([Track cube](#track-cube)). Map art, Turntable and 3D export are separate, unbuilt items. + ([Track cube](#track-cube)). Extrude & Bevel (Classic) and Revolve (Classic) take Map Art + ([Map Art](#map-art)). Turntable and 3D export are separate, unbuilt items. Release measurements and a repeatable CLI scene are in [3D lighting performance](3d-lighting-performance.md).