From b409e139249aefd6bd3a1ad09595ad025adf397d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 19:34:49 -0800 Subject: [PATCH] Map Art: art left out frees its allowance, and the dialog draws the art in its box's proportions - Mapped art that goes past a limit is left out together with the paint copies and points it would have taken, so a later solid's or appearance item's map still draws. - The surface list collects every surface's outline in one pass over the facets. - The Map Art dialog draws the mapped symbol stretched to its box, as its map scales it, and renders it at most 1,024 pixels on a side. Symbol thumbnails are bounded the same way. - The params text and docs/mcp.md say that a hollow solid (cap false) has no caps, so its numbering starts at its first side wall. --- crates/effects/src/catalog.rs | 2 +- crates/effects/src/solids.rs | 57 ++++++---- crates/effects/src/solids/classic.rs | 11 +- crates/effects/src/solids/map_art.rs | 2 +- crates/effects/src/solids/tests_map_art.rs | 38 +++++++ crates/engine/src/cmd/effectcmd/graphics.rs | 2 +- crates/ui-egui/src/dialogs/three_d_classic.rs | 3 +- crates/ui-egui/src/panels/symbols.rs | 102 +++++++++++++++++- docs/mcp.md | 3 +- 9 files changed, 193 insertions(+), 27 deletions(-) diff --git a/crates/effects/src/catalog.rs b/crates/effects/src/catalog.rs index bf4a5c1cd3..21484b6831 100644 --- a/crates/effects/src/catalog.rs +++ b/crates/effects/src/catalog.rs @@ -210,7 +210,7 @@ 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), 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, 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.", + "{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( diff --git a/crates/effects/src/solids.rs b/crates/effects/src/solids.rs index 57b9e01ac6..c2b56632ff 100644 --- a/crates/effects/src/solids.rs +++ b/crates/effects/src/solids.rs @@ -2320,26 +2320,48 @@ pub fn map_surfaces_at(doc: Option<&Document>, n: &Node, item: Option, in 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 local surface `k` of `surfaces`: 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], k: usize| -> Vec<[Point; 2]> { - let Some(surface) = surfaces.get(k) else { return vec![] }; - let flat = match surface.kind { - SurfaceKind::Side => Rect::new(-surface.width / 2.0, -surface.height / 2.0, surface.width / 2.0, surface.height / 2.0), - _ => Rect::new(0.0, 0.0, surface.width, surface.height), - }; - let near = (surface.width.max(surface.height) * 1e-6).max(1e-9); - let mut edges = vec![]; + // 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 (SurfaceKind::End(end), Some(at)) = (surface.kind, f.end) { - if end == at { - for c in &f.contours { - edges.extend(c.iter().zip(c.iter().cycle().skip(1)).take(c.len()).map(|(a, b)| [*a, *b])); + 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(cell) = f.cell.as_deref().filter(|c| c.surface == k && c.uv.len() == c.page.len()) else { 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; @@ -2347,15 +2369,14 @@ pub fn map_surfaces_at(doc: Option<&Document>, n: &Node, item: Option, in 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)) { - edges.push([*from, *to]); + out.push([*from, *to]); } } } edges }; let listed = |surfaces: &[vectorcraft_three_d::SolidSurface], facets: &[Facet], out: &mut Vec| { - for (k, s) in surfaces.iter().enumerate() { - let outline = seen(surfaces, facets, k); + 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 }); } }; diff --git a/crates/effects/src/solids/classic.rs b/crates/effects/src/solids/classic.rs index 659f184d84..54401fd189 100644 --- a/crates/effects/src/solids/classic.rs +++ b/crates/effects/src/solids/classic.rs @@ -301,15 +301,20 @@ pub(crate) fn surface( 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. + // 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) }; - match m.art.parts(n.id, &facets, m.layout, &shaded_as, m.budget, m.copies) { - Some(parts) => (parts, m.art.invisible), + 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), } } diff --git a/crates/effects/src/solids/map_art.rs b/crates/effects/src/solids/map_art.rs index 74627bd61c..56159f4233 100644 --- a/crates/effects/src/solids/map_art.rs +++ b/crates/effects/src/solids/map_art.rs @@ -208,7 +208,7 @@ pub(crate) struct SolidLayout { } /// What the mapped art of one object has drawn so far, against the limits its maps share. -#[derive(Default)] +#[derive(Clone, Debug, Default, PartialEq)] pub(crate) struct MapBudget { elements: usize, /// The points of the maps' symbols cut into straight pieces, against [`MAX_ELEMENTS`]. diff --git a/crates/effects/src/solids/tests_map_art.rs b/crates/effects/src/solids/tests_map_art.rs index eaaa3cb840..0bbe54a5b1 100644 --- a/crates/effects/src/solids/tests_map_art.rs +++ b/crates/effects/src/solids/tests_map_art.rs @@ -246,6 +246,44 @@ fn the_points_drawn_on_earlier_surfaces_leave_the_next_symbol_its_own_allowance( 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) } diff --git a/crates/engine/src/cmd/effectcmd/graphics.rs b/crates/engine/src/cmd/effectcmd/graphics.rs index 03ea522e03..72df4ea04e 100644 --- a/crates/engine/src/cmd/effectcmd/graphics.rs +++ b/crates/engine/src/cmd/effectcmd/graphics.rs @@ -37,7 +37,7 @@ pub(super) fn specs() -> Vec { "Map Art", [], None, - "{surface?: integer (1..the object's surface count: Extrude & Bevel (Classic) numbers 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; Revolve (Classic)'s swept side is surface 1), 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]}", + "{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), 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 ), diff --git a/crates/ui-egui/src/dialogs/three_d_classic.rs b/crates/ui-egui/src/dialogs/three_d_classic.rs index 534389642d..b3f1ebd3d9 100644 --- a/crates/ui-egui/src/dialogs/three_d_classic.rs +++ b/crates/ui-egui/src/dialogs/three_d_classic.rs @@ -352,7 +352,8 @@ fn flat_view( 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())); - crate::panels::symbols::chip(&inner, &st.doc, &keys, egui::Rect::from_center_size(center, half * 2.0), &m.symbol); + 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() diff --git a/crates/ui-egui/src/panels/symbols.rs b/crates/ui-egui/src/panels/symbols.rs index 6e933d44cd..bedece96f4 100644 --- a/crates/ui-egui/src/panels/symbols.rs +++ b/crates/ui-egui/src/panels/symbols.rs @@ -23,6 +23,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 { @@ -30,7 +40,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); @@ -133,6 +143,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) +} + fn current(app: &mut VectorcraftApp) -> Option { app.run("symbol.list", json!({})).ok().and_then(|v| v["current"].as_str().map(str::to_string)) } @@ -728,6 +799,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/docs/mcp.md b/docs/mcp.md index a759f13bb4..8902d57732 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4498,7 +4498,8 @@ 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. Revolve (Classic) has one surface, its swept + 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. Revolve (Classic) has one surface, its swept side. 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`,