Merge pull request #7819 from dotCooCoo/feat/textures-map-art-and-shading

Export 3D Object: mapped graphics export as textures of their faces
This commit is contained in:
BFlat
2026-11-18 03:23:34 +07:00
committed by GitHub
20 changed files with 1099 additions and 92 deletions
+7 -7
View File
@@ -94,13 +94,13 @@ pub use revolve::{
CLASSIC_REVOLVE, REVOLVE, has_revolve, is_revolve, revolve_art, revolve_art_in, revolve_options, validate_revolve, validate_revolve_in,
};
pub use solids::{
CLASSIC_EXTRUDE, CLASSIC_ROTATE, EXTRUDE, GRAPHICS, GraphicFrame, INFLATE, MAX_GRAPHICS, MappedGraphic, RENDER, RENDER_MODES, ROTATE,
ROTATE_SURFACES, ROTATION_PRESETS, SHADING_COLORS, SOLIDS, SolidMesh, THREE_D_TYPES, classic_extrude_options, classic_shading, extrude_options,
graphic_bounds, graphic_frame, graphic_symbols, has_solid, inflate_options, is_classic_three_d, is_three_d, mapped_graphics, missing_symbol,
names_graphic_symbol, rename_graphic_symbol, rename_graphic_symbol_in, renders_wireframe, solid_art, solid_art_in, takes_graphics,
three_d_meshes, three_d_meshes_in, three_d_meshes_of, three_d_meshes_of_in, three_d_params_as, three_d_wireframe_in, validate_solid,
validate_solid_in, validate_three_d, validate_three_d_at, validate_three_d_at_in, validate_three_d_in, validate_three_d_params, view_options,
with_graphic,
CLASSIC_EXTRUDE, CLASSIC_ROTATE, EXTRUDE, GRAPHICS, GraphicFrame, INFLATE, MAX_GRAPHICS, MappedGraphic, MeshGraphics, RENDER, RENDER_MODES,
ROTATE, ROTATE_SURFACES, ROTATION_PRESETS, SHADING_COLORS, SOLIDS, SolidMesh, THREE_D_TYPES, classic_extrude_options, classic_shading,
extrude_options, graphic_bounds, graphic_frame, graphic_symbols, has_solid, inflate_options, is_classic_three_d, is_three_d, mapped_graphics,
mesh_graphics_art, missing_symbol, names_graphic_symbol, rename_graphic_symbol, rename_graphic_symbol_in, renders_wireframe, solid_art,
solid_art_in, takes_graphics, three_d_meshes, three_d_meshes_in, three_d_meshes_of, three_d_meshes_of_in, three_d_params_as,
three_d_wireframe_in, validate_solid, validate_solid_in, validate_three_d, validate_three_d_at, validate_three_d_at_in, validate_three_d_in,
validate_three_d_params, view_options, with_graphic,
};
pub use solids::{
GRAPHIC_MAX_OFFSET, GRAPHIC_SCALE_RANGE, GRAPHICS_NOT_TAKEN, appearance_graphic_symbols, exports_three_d, graphic_frame_at,
+2 -2
View File
@@ -801,7 +801,7 @@ pub(crate) fn revolve_meshes(n: &Node, total: &mut usize, limit: usize) -> Resul
let b = path.bounds().ok_or("Revolve requires a shape with at least two anchors")?;
let (paint, opacity, _) = paint_of(item);
let mesh = vectorcraft_three_d::revolve_mesh(path, rule, b, fx_options(fx))?;
Ok(crate::SolidMesh { mesh, color: crate::solids::mesh_color(&paint, opacity) })
Ok(crate::SolidMesh::plain(mesh, crate::solids::mesh_color(&paint, opacity)))
};
if let Some(index) = n.appearance.effects.iter().position(|e| e.visible && is_revolve(&e.id)) {
let before = n.appearance.effects.get(..index).unwrap_or_default();
@@ -924,7 +924,7 @@ fn group_meshes(n: &Node, total: &mut usize, limit: usize) -> Result<Vec<crate::
let Some(item) = surface_item(&s.items) else { continue };
let (paint, opacity, _) = paint_of(item);
let mesh = vectorcraft_three_d::revolve_mesh(&s.path, s.rule, b, options)?;
crate::solids::keep_mesh(&mut out, total, crate::SolidMesh { mesh, color: crate::solids::mesh_color(&paint, opacity * s.opacity) }, limit)?;
crate::solids::keep_mesh(&mut out, total, crate::SolidMesh::plain(mesh, crate::solids::mesh_color(&paint, opacity * s.opacity)), limit)?;
}
Ok(out)
}
+78 -5
View File
@@ -25,8 +25,8 @@ pub(crate) use source::{resolve, resolve_for};
pub(crate) mod graphics;
pub use graphics::{
GRAPHICS, GraphicFrame, MAX_GRAPHICS, MappedGraphic, graphic_symbols, mapped_graphics, missing_symbol, names_graphic_symbol,
rename_graphic_symbol, rename_graphic_symbol_in, takes_graphics, with_graphic,
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,
};
pub use graphics::{
MAX_OFFSET as GRAPHIC_MAX_OFFSET, NOT_TAKEN as GRAPHICS_NOT_TAKEN, SCALE_RANGE as GRAPHIC_SCALE_RANGE, appearance_graphic_symbols,
@@ -2322,6 +2322,71 @@ pub struct SolidMesh {
/// The paint's display color (sRGB, 0..1) and its opacity: a gradient's stops averaged, gray
/// for a pattern.
pub color: [f32; 4],
/// The graphics mapped onto the mesh when it is the part of a solid's planar face that carries
/// some ([`split_graphics`]); `None` otherwise.
pub graphics: Option<MeshGraphics>,
}
impl SolidMesh {
/// A mesh painted `color`, with no graphics.
pub fn plain(mesh: Mesh, color: [f32; 4]) -> Self {
Self { mesh, color, graphics: None }
}
}
/// The parts of `mesh`, a solid that 3D effect `id` with parameters `p` built about `bounds`, painted
/// `color` from a fill or stroke at `opacity`: for each planar face that carries graphics (Extrude &
/// Bevel's caps, the plane), the triangles on it as a mesh of their own with the art point of each
/// corner ([`MeshGraphics`]), then the rest. Revolve's side, whose graphics are not mapped onto its
/// mesh, stays plain.
fn split_graphics(id: &str, p: &Value, bounds: Rect, mesh: Mesh, (color, opacity): ([f32; 4], f32)) -> Vec<SolidMesh> {
let list = graphics::mapped_graphics(p);
if list.is_empty() || !takes_graphics(id) || id == crate::REVOLVE {
return vec![SolidMesh::plain(mesh, color)];
}
let view = view_options(p);
let mut rest = mesh;
let mut out = vec![];
for face in PlanarFace::ALL {
if !list.iter().any(|g| g.face == face) {
continue;
}
let on_mesh = if id == ROTATE {
vectorcraft_three_d::plane_mesh_face(bounds, view)
} else {
vectorcraft_three_d::extrude_mesh_face(bounds, extrude_options(p), view, face)
};
let Some(on_mesh) = on_mesh else { continue };
let (mut taken, mut left, mut art) = (Mesh::default(), Mesh::default(), vec![]);
for t in &rest.triangles {
let corner = |i: u32| rest.positions.get(i as usize).copied().zip(rest.normals.get(i as usize).copied());
let Some(corners) = t.iter().map(|&i| corner(i)).collect::<Option<Vec<_>>>() else { continue };
let points: Option<Vec<Point>> = corners.iter().map(|(m, n)| on_mesh.art_point(*m, *n)).collect();
let into = match points {
Some(points) => {
art.extend(points);
&mut taken
}
None => &mut left,
};
let base = into.positions.len() as u32;
for (m, n) in corners {
into.positions.push(m);
into.normals.push(n);
}
into.triangles.push([base, base + 1, base + 2]);
}
rest = left;
if !taken.is_empty() {
let graphics = list.iter().filter(|g| g.face == face).cloned().collect();
let graphics = MeshGraphics { face, graphics, center: bounds.center(), art, opacity, object: 1.0 };
out.push(SolidMesh { mesh: taken, color, graphics: Some(graphics) });
}
}
if !rest.is_empty() {
out.insert(0, SolidMesh::plain(rest, color));
}
out
}
/// The color a mesh of `paint` at `opacity` takes ([`SolidMesh::color`]).
@@ -2363,13 +2428,18 @@ fn meshes_for(fx: &Effect, shapes: &[Profile], total: &mut usize, limit: usize)
let p = crate::merged_params(&fx.id, &fx.params);
let view = view_options(&p);
let mut out = vec![];
let mut keep = |out: &mut Vec<SolidMesh>, mesh: Mesh, color: [f32; 4]| keep_mesh(out, total, SolidMesh { mesh, color }, limit);
// A solid's parts with and without graphics count together against the limit.
let mut keep = |out: &mut Vec<SolidMesh>, mesh: Mesh, (paint, opacity): (&Paint, f32), bounds: Rect| {
split_graphics(&fx.id, &p, bounds, mesh, (mesh_color(paint, opacity), opacity))
.into_iter()
.try_for_each(|part| keep_mesh(out, total, part, limit))
};
if is_plane(&fx.id) {
for s in shapes {
for item in &s.items {
let (paint, opacity, _) = paint_of(item, s.opacity);
let (area, rule) = region(&s.path, s.rule, item);
keep(&mut out, vectorcraft_three_d::plane_mesh(&area, rule, b, view)?, mesh_color(&paint, opacity))?;
keep(&mut out, vectorcraft_three_d::plane_mesh(&area, rule, b, view)?, (&paint, opacity), b)?;
}
}
return Ok(out);
@@ -2406,7 +2476,7 @@ fn meshes_for(fx: &Effect, shapes: &[Profile], total: &mut usize, limit: usize)
match solid.mesh() {
Ok(mesh) => {
let (paint, opacity, _) = paint_of(item, *member);
keep(&mut out, mesh, mesh_color(&paint, opacity))?;
keep(&mut out, mesh, (&paint, opacity), bounds)?;
}
Err(_) if matches!(item, AppearanceItem::Stroke(_)) => {}
Err(e) => return Err(e),
@@ -2494,6 +2564,9 @@ fn meshes_within(doc: Option<&Document>, n: &Node, total: &mut usize, limit: usi
.filter(|m| !m.mesh.is_empty())
.map(|mut m| {
m.color[3] *= n.opacity.clamp(0.0, 1.0);
if let Some(g) = &mut m.graphics {
g.object *= n.opacity.clamp(0.0, 1.0);
}
m
})
.collect();
+65
View File
@@ -519,6 +519,71 @@ pub(super) fn face_art(
Some(Node::new(id, NodeKind::Group { children: vec![Arc::new(clip), Arc::new(Node::group(id, children))], clip: true }))
}
/// The graphics on one planar face of a solid's mesh ([`super::SolidMesh`]): those mapped onto
/// `face`, placed about `center` (the center of the bounds the solids were built with), and the
/// point of the art's plane that each corner of the mesh shows (document coordinates of the art
/// before its 3D effect, y down).
#[derive(Clone, Debug, PartialEq)]
pub struct MeshGraphics {
pub face: PlanarFace,
pub graphics: Vec<MappedGraphic>,
pub center: Point,
/// One for each position of the mesh.
pub art: Vec<Point>,
/// The opacity of the fill or stroke the face is painted with, which the graphics take too, as
/// the canvas draws them; neither a gradient's stops nor the object's own opacity is in it.
pub opacity: f32,
/// The opacity of the object the face belongs to, which applies to the face and its graphics
/// together.
pub object: f32,
}
impl MeshGraphics {
/// The bounds of the art points of the mesh's corners; `None` without corners.
pub fn art_bounds(&self) -> Option<Rect> {
let first = *self.art.first()?;
Some(self.art.iter().fold(Rect::from_points(first, first), |r, p| r.union_pt(*p)))
}
}
/// The art `graphics` draws on its face, flat in the art's plane, unshaded and unclipped: each
/// graphic's fills and stroke outlines at its place ([`MappedGraphic`]), back to front, as one
/// group of objects with id `id`. A graphic whose symbol `doc` does not have, or whose art is past
/// the limits of [`pieces_of`], is left out, as the canvas leaves it out. `Ok(None)` when nothing
/// is drawn; an error when the graphics' art draws more than [`MAX_ELEMENTS`] path elements
/// together.
pub fn mesh_graphics_art(doc: &Document, id: NodeId, graphics: &MeshGraphics) -> Result<Option<Node>, String> {
let mut children = vec![];
let mut elements = 0usize;
for g in graphics.graphics.iter().filter(|g| g.face == graphics.face) {
let Some(symbol) = doc.symbols.iter().find(|s| s.name == g.symbol) else { continue };
let Ok(pieces) = pieces_of(doc, symbol) else { continue };
let Some(bounds) = pieces.iter().filter_map(|p| p.path.bounds()).reduce(|a, b| a.union(b)) else { continue };
let place = g.placement(bounds, graphics.center);
for piece in pieces {
elements = elements.saturating_add(drawn_elements(&piece.path, 1));
if elements > MAX_ELEMENTS {
return Err("The graphics are too complex: simplify the symbols' art".into());
}
let mut paint = piece.paint;
if let Paint::Pattern { xf, .. } = &mut paint {
*xf = place * *xf;
}
let mut fill = FillLayer::new(paint);
fill.opacity = piece.opacity;
fill.blend = piece.blend;
let mut appearance = Appearance { items: vec![AppearanceItem::Fill(fill)], ..Default::default() };
appearance.transform_gradients(place);
let mut node = Node::path(id, piece.path.transformed(place), appearance);
if let NodeKind::Path { rule, .. } = &mut node.kind {
*rule = piece.rule;
}
children.push(Arc::new(node));
}
}
Ok((!children.is_empty()).then(|| Node::group(id, children)))
}
/// One area of a graphic placed on Revolve's unrolled side surface, cut into straight pieces.
struct Unrolled {
polygons: Vec<Vec<Point>>,
@@ -86,6 +86,48 @@ fn a_graphic_is_drawn_on_the_front_cap_at_its_offset_size_and_turn() {
assert!((b.width() - 10.0 * 2f64.sqrt()).abs() < 1e-6);
}
#[test]
fn a_mesh_carries_its_caps_graphics_flat_in_the_arts_plane() {
let d = document();
let graphics =
json!([{"symbol": "Mark", "x": 20.0, "y": -10.0, "scale": 200.0}, {"symbol": "Mark", "face": "back", "x": 20.0, "y": -10.0, "scale": 200.0}]);
// Turned, so the caps' corners in the mesh are not the art's.
let n = object(EXTRUDE, json!({"rotationX": -20.0, "rotationY": 35.0, "rotationZ": 10.0, "graphics": graphics}));
let parts = super::super::three_d_meshes_in(Some(&d), &n).unwrap();
// The walls first, then the front cap and the back cap, each two triangles.
assert_eq!(
parts.iter().map(|p| p.graphics.as_ref().map(|g| g.face)).collect::<Vec<_>>(),
[None, Some(PlanarFace::Front), Some(PlanarFace::Back)]
);
let total: usize = parts.iter().map(|p| p.mesh.triangles.len()).sum();
let plain = super::super::three_d_meshes_in(Some(&d), &object(EXTRUDE, json!({"rotationX": -20.0, "rotationY": 35.0, "rotationZ": 10.0})));
assert_eq!(total, plain.as_ref().map_or(0, |p| p.iter().map(|p| p.mesh.triangles.len()).sum()), "no triangle is lost or doubled");
assert!(plain.unwrap().iter().all(|p| p.graphics.is_none()));
// The art points of each cap's corners are the art's own square; the graphic is drawn flat at
// its place, mirrored on the back so it reads from behind.
for (part, drawn) in parts[1..].iter().zip([Rect::new(60.0, 30.0, 80.0, 50.0), Rect::new(20.0, 30.0, 40.0, 50.0)]) {
let Some(g) = &part.graphics else { panic!("no graphics") };
assert_eq!(g.art.len(), part.mesh.positions.len());
assert!(close(g.art_bounds().unwrap(), Rect::new(0.0, 0.0, 100.0, 100.0)), "{:?}", g.art_bounds());
assert_eq!(g.graphics.len(), 1);
let art = mesh_graphics_art(&d, NodeId(9), g).unwrap().unwrap();
let paths: Vec<(PathData, Paint)> = art
.children()
.into_iter()
.flatten()
.filter_map(|c| Some((c.path_data()?.clone(), c.appearance.items.first()?.paint().clone())))
.collect();
assert!(close(bounds_of(&paths), drawn), "{:?}: {:?}", g.face, bounds_of(&paths));
assert_eq!(paths[0].1, Paint::solid(red()), "unshaded");
}
// A plane is all one face; a graphic whose symbol is gone draws nothing.
let n = object(ROTATE, json!({"rotationY": 35.0, "graphics": [{"symbol": "Gone"}]}));
let parts = super::super::three_d_meshes_in(Some(&d), &n).unwrap();
assert_eq!(parts.len(), 1);
let Some(g) = &parts[0].graphics else { panic!("no graphics") };
assert_eq!(mesh_graphics_art(&d, NodeId(9), g), Ok(None));
}
#[test]
fn without_the_document_or_its_symbol_nothing_is_drawn() {
let n = object(EXTRUDE, json!({"graphics": [{"symbol": "Mark"}]}));
@@ -563,6 +605,15 @@ fn art_nested_too_deep_is_refused_and_not_drawn() {
// A loaded file draws its other graphics.
let both = object(EXTRUDE, json!({"graphics": [{"symbol": "Deep"}, {"symbol": "Mark"}]}));
assert_eq!(graphics_in(&solid_art_in(Some(&d), &both).unwrap()).len(), 1);
// A mesh's graphics leave it out as well and draw the others.
let parts = super::super::three_d_meshes_in(Some(&d), &both).unwrap();
let Some(g) = parts.iter().find_map(|p| p.graphics.as_ref()) else { panic!("no graphics") };
let art = mesh_graphics_art(&d, NodeId(9), g).unwrap().unwrap();
assert_eq!(art.children().map_or(0, |c| c.len()), 1);
let deep = object(EXTRUDE, json!({"graphics": [{"symbol": "Deep"}]}));
let parts = super::super::three_d_meshes_in(Some(&d), &deep).unwrap();
let Some(g) = parts.iter().find_map(|p| p.graphics.as_ref()) else { panic!("no graphics") };
assert_eq!(mesh_graphics_art(&d, NodeId(9), g), Ok(None));
}
#[test]
+1 -1
View File
@@ -238,7 +238,7 @@ fn meshes_built_apart(fx: &Effect, shapes: &[Profile], total: &mut usize, limit:
match mesh {
Ok(mesh) => {
let (paint, opacity, _) = paint_of(item, *opacity);
keep_mesh(&mut out, total, SolidMesh { mesh, color: mesh_color(&paint, opacity) }, limit)?;
keep_mesh(&mut out, total, SolidMesh::plain(mesh, mesh_color(&paint, opacity)), limit)?;
}
Err(_) if matches!(item, AppearanceItem::Stroke(_)) => {}
Err(e) => return Err(e),
+24 -5
View File
@@ -10,8 +10,8 @@ use vectorcraft_doc::{ExportAsset, NodeId};
use super::edit::{refuse_symbol_part, roots_of, selected_roots};
use super::fileio::{
DEFAULT_FORMAT_3D, FORMATS_3D, SCREEN_SETTINGS_KEYS, check_screen_settings, create_dir, export_crop, export_screens, mesh_file_names, mesh_files,
safe_file_name, store_screen_settings, with_screen_export_preset, write_file,
DEFAULT_FORMAT_3D, FORMATS_3D, SCREEN_SETTINGS_KEYS, TEXTURE_SIZE, TEXTURE_SIZES, check_screen_settings, create_dir, export_crop, export_screens,
image_maps, mesh_file_names, mesh_files, safe_file_name, store_screen_settings, textures, with_screen_export_preset, write_file,
};
use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, checked_ids_param, cmd, has_doc, ok, str_param, switch_or, text_param};
@@ -80,7 +80,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Export 3D Assets",
[],
None,
"{assets?: [asset id…] (default every 3D asset), folder?, zip?} each 3D asset's object as a mesh file in its format (assets.set3DFormat), named after the asset: USDA or USDZ, glTF 2.0 (one .gltf, its buffer embedded) or OBJ with its .mtl (whitespace and # in an OBJ's name become _). Every solid of the object (the fill's, each stroke's, a group's members') is a mesh with a material in the color it is painted; faces turned away from the viewer are included, at the object's 3D rotation, y up, about the point it turns about, in points (glTF: meters). Files that would share a name get -2, -3…; an object with a hole that crosses its face's outline or another hole, or with more than 2,000,000 triangles, is refused → {files: [path…]} (no folder: {files: [{name, dataBase64}]}, or with zip one zip as {name, dataBase64, files})",
"{assets?: [asset id…] (default every 3D asset), folder?, zip?, textureSize?: 128…4096 (default 1024: the pixels along the longer side of each face's texture)} each 3D asset's object as a mesh file in its format (assets.set3DFormat), named after the asset: USDA or USDZ, glTF 2.0 (one .gltf, its buffer embedded) or OBJ with its .mtl (whitespace and # in an OBJ's name become _). Every solid of the object (the fill's, each stroke's, a group's members') is a mesh with a material in the color it is painted; faces turned away from the viewer are included, at the object's 3D rotation, y up, about the point it turns about, in points (glTF: meters). The graphics mapped onto a plane or onto Extrude & Bevel's front or back cap (threeD.mapGraphic) are a PNG texture of that face: its color with the graphics drawn over it, flat and unlit, on a mesh of the face's own with texture coordinates; glTF embeds it, USDZ stores it after the layer, and OBJ and USDA write it beside them as <name>-texture-1.png… (whitespace, # and @ become _); a face that is not opaque keeps its opacity in the texture's alpha, and an OBJ also gets <name>-texture-1-opacity.png…, the alpha as gray levels for its map_d. Graphics on Revolve's side are not exported. Files that would share a name get -2, -3…; an object with a hole that crosses its face's outline or another hole, or with more than 2,000,000 triangles, or textures of more than 67,108,864 pixels in one export, is refused → {files: [path…]} (no folder: {files: [{name, dataBase64}]}, or with zip one zip as {name, dataBase64, files})",
has_doc,
export_3d
),
@@ -299,6 +299,8 @@ fn export_3d(s: &mut Session, p: &Value) -> Result<Value> {
}
let folder = text_param(p, "folder", C)?.filter(|f| !f.is_empty());
let zip = switch_or(p, "zip", false, C)?;
let size = texture_size_param(p, C)?;
let mut pixels = 0u64;
// Every file's name, compared without case: a later file that would take one gets -2, -3…
let mut taken: HashSet<String> = HashSet::new();
let mut files: Vec<(String, Vec<u8>)> = vec![];
@@ -311,18 +313,20 @@ fn export_3d(s: &mut Session, p: &Value) -> Result<Value> {
let what = &a.name;
let parts =
vectorcraft_render::effects::three_d_meshes_of_in(Some(d), nodes).map_err(|e| bad(C, format!("{what} can't be exported in 3D: {e}")))?;
let pictures = textures(d, &parts, size, &mut pixels).map_err(|e| bad(C, format!("{what} can't be exported in 3D: {e}")))?;
let images = image_maps(&pictures);
let base = Some(safe_file_name(&a.name)).filter(|b| !b.is_empty()).unwrap_or_else(|| "Asset".into());
let mut stem = base.clone();
let mut k = 1;
loop {
let names = mesh_file_names(&stem, format).map_err(|e| bad(C, e))?;
let names = mesh_file_names(&stem, format, &images).map_err(|e| bad(C, e))?;
if names.iter().all(|n| !taken.contains(&n.to_lowercase())) {
break;
}
k += 1;
stem = format!("{base}-{k}");
}
let made = mesh_files(&stem, format, &parts).map_err(|e| bad(C, e))?;
let made = mesh_files(&stem, format, &parts, &pictures).map_err(|e| bad(C, e))?;
taken.extend(made.iter().map(|(n, _)| n.to_lowercase()));
files.extend(made);
}
@@ -360,6 +364,21 @@ fn export_3d(s: &mut Session, p: &Value) -> Result<Value> {
}
}
/// Param `textureSize` of command `cmd`: the pixels along the longer side of each face's texture,
/// [`TEXTURE_SIZE`] when it is not given.
fn texture_size_param(p: &Value, cmd: &str) -> Result<u32> {
let key = "textureSize";
let (lo, hi) = TEXTURE_SIZES;
match p.get(key) {
None | Some(Value::Null) => Ok(TEXTURE_SIZE),
Some(v) => v
.as_u64()
.and_then(|n| u32::try_from(n).ok())
.filter(|n| (lo..=hi).contains(n))
.ok_or_else(|| bad(cmd, format!("`{key}` must be a whole number of pixels from {lo} to {hi}"))),
}
}
/// The asset ids of param `key`.
fn asset_ids(p: &Value, key: &str, cmd: &str) -> Result<Vec<u64>> {
let ids = p.get(key).and_then(Value::as_array).ok_or_else(|| bad(cmd, format!("`{key}` must be an array of asset ids (see assets.list)")))?;
+4 -2
View File
@@ -87,8 +87,10 @@ pub use load::{
};
pub(crate) use load::{check_files_not_lossy_overwrite, check_not_lossy_overwrite, lossy_source};
pub use load::{losses_summary, overwrite_losses};
pub use mesh3d::{DEFAULT_FORMAT_3D, FORMATS_3D, format_3d_label};
pub(crate) use mesh3d::{mesh_file_names, mesh_files};
#[cfg(test)]
pub(crate) use mesh3d::MAX_TEXTURE_PIXELS;
pub use mesh3d::{DEFAULT_FORMAT_3D, FORMATS_3D, draws_textures, format_3d_label};
pub(crate) use mesh3d::{TEXTURE_SIZE, TEXTURE_SIZES, image_maps, mesh_file_names, mesh_files, textures};
pub use naming::{NameParts as FileNameParts, parse_date as parse_file_date, render as render_file_name};
pub(crate) use native::preview_png;
pub use native::with_compression_pref;
+378 -47
View File
@@ -9,13 +9,24 @@
//! as their specifications ask; MTL colors are the display colors. Materials are two-sided, since
//! an open solid or a turned plane is seen from both sides.
//!
//! The graphics mapped onto a face of a solid ([`textures`]) are a PNG picture of that face: its
//! color with the graphics drawn over it, flat and unshaded, which the face's own mesh shows through
//! texture coordinates and a material of its own. glTF embeds each PNG as a data URI, USDZ stores it
//! after the layer, and OBJ and USDA name PNG files written beside them (`<name>-texture-1.png`…).
//!
//! Formats: glTF 2.0 <https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html>, USD
//! <https://openusd.org/release/index.html> (USDZ: <https://openusd.org/release/spec_usdz.html>).
//! <https://openusd.org/release/index.html> (USDZ: <https://openusd.org/release/spec_usdz.html>;
//! textures: <https://openusd.org/release/spec_usdpreviewsurface.html>), OBJ and MTL
//! <https://www.loc.gov/preservation/digital/formats/fdd/fdd000508.shtml>.
use std::fmt::Write as _;
use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_render::effects::SolidMesh;
use vectorcraft_doc::color::{Color, Paint};
use vectorcraft_doc::{Appearance, Document, Node, NodeId};
use vectorcraft_geom::{Affine, Rect};
use vectorcraft_render::effects::{MeshGraphics, SolidMesh};
/// The formats a 3D asset exports to, as `assets.set3DFormat` names them: USDA first, the default.
pub const FORMATS_3D: [&str; 4] = ["usda", "usdz", "gltf", "obj"];
@@ -23,6 +34,12 @@ pub const FORMATS_3D: [&str; 4] = ["usda", "usdz", "gltf", "obj"];
pub const DEFAULT_FORMAT_3D: &str = "usda";
/// The meters in a point (1/72 inch).
const METERS_PER_POINT: f64 = 0.0254 / 72.0;
/// The pixels along the longer side of a face's texture, unless `assets.export3D` is given another
/// size, and the sizes it takes.
pub(crate) const TEXTURE_SIZE: u32 = 1024;
pub(crate) const TEXTURE_SIZES: (u32, u32) = (128, 4096);
/// The most texture pixels one export draws, all its assets together.
pub(crate) const MAX_TEXTURE_PIXELS: u64 = 4 * 4096 * 4096;
/// The label of `format` for menus: `USDA`, `USDZ`, `glTF`, `OBJ`.
pub fn format_3d_label(format: &str) -> &'static str {
@@ -40,14 +57,44 @@ fn obj_stem(stem: &str) -> String {
stem.chars().map(|c| if c.is_whitespace() || c == '#' { '_' } else { c }).collect()
}
/// The names of the files [`mesh_files`] writes for `stem` in `format`.
pub(crate) fn mesh_file_names(stem: &str, format: &str) -> Result<Vec<String>, String> {
/// The name of texture `k` (from 0) of the object named `stem`: whitespace, `#` and `@` become `_`,
/// so an MTL `map_Kd` line and a USD asset path name it as one word.
fn texture_name(stem: &str, k: usize) -> String {
format!("{}-texture-{}.png", texture_stem(stem), k + 1)
}
/// The name of the opacity map of texture `k` (from 0) of the object named `stem`, as
/// [`texture_name`] names the texture.
fn opacity_name(stem: &str, k: usize) -> String {
format!("{}-texture-{}-opacity.png", texture_stem(stem), k + 1)
}
/// `stem` with whitespace, `#` and `@` turned into `_`, for the names of its textures.
fn texture_stem(stem: &str) -> String {
stem.chars().map(|c| if c.is_whitespace() || c == '#' || c == '@' { '_' } else { c }).collect()
}
/// The names of the files [`mesh_files`] writes for `stem` in `format` with the textures `images`
/// ([`image_maps`]: for each, whether it has an opacity map): OBJ and USDA name a PNG file for each
/// texture after them, and OBJ also one for each opacity map, after its texture; glTF and USDZ hold
/// theirs.
pub(crate) fn mesh_file_names(stem: &str, format: &str, images: &[bool]) -> Result<Vec<String>, String> {
let beside = |mut names: Vec<String>, stem: &str, maps: bool| {
for (k, map) in images.iter().enumerate() {
names.push(texture_name(stem, k));
if maps && *map {
names.push(opacity_name(stem, k));
}
}
names
};
match format {
"obj" => {
let stem = obj_stem(stem);
Ok(vec![format!("{stem}.obj"), format!("{stem}.mtl")])
Ok(beside(vec![format!("{stem}.obj"), format!("{stem}.mtl")], &stem, true))
}
"gltf" | "usda" | "usdz" => Ok(vec![format!("{stem}.{format}")]),
"usda" => Ok(beside(vec![format!("{stem}.usda")], stem, false)),
"gltf" | "usdz" => Ok(vec![format!("{stem}.{format}")]),
_ => {
let key = "format";
Err(format!("`{key}` must be one of {}", FORMATS_3D.join(", ")))
@@ -55,35 +102,109 @@ pub(crate) fn mesh_file_names(stem: &str, format: &str) -> Result<Vec<String>, S
}
}
/// A picture painted on one part of a 3D object ([`SolidMesh`]): a PNG, and for each corner of the
/// part's mesh where it falls on the picture (0 to 1 across from the left, 0 to 1 down from the
/// top). `opacity` is a grayscale PNG of the picture's alpha when some of it is not opaque.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct Texture {
pub png: Arc<Vec<u8>>,
pub opacity: Option<Arc<Vec<u8>>>,
pub uv: Vec<[f64; 2]>,
}
/// A distinct picture of a 3D object: the PNG and its opacity map.
type Picture = (Arc<Vec<u8>>, Option<Arc<Vec<u8>>>);
/// The distinct pictures of `textures` in order of first use, and the index among them of each
/// part's (`None` for a part without one).
fn images(parts: usize, textures: &[Option<Texture>]) -> (Vec<Picture>, Vec<Option<usize>>) {
let mut out: Vec<Picture> = vec![];
let index = (0..parts)
.map(|k| {
let t = textures.get(k)?.as_ref()?;
Some(out.iter().position(|(p, _)| Arc::ptr_eq(p, &t.png) || p == &t.png).unwrap_or_else(|| {
out.push((t.png.clone(), t.opacity.clone()));
out.len() - 1
}))
})
.collect();
(out, index)
}
/// For each distinct picture of `textures`, whether it has an opacity map ([`mesh_file_names`]).
pub(crate) fn image_maps(textures: &[Option<Texture>]) -> Vec<bool> {
images(textures.len(), textures).0.iter().map(|(_, map)| map.is_some()).collect()
}
/// The files of a 3D object named `stem` in `format` ([`FORMATS_3D`]): `(file name, bytes)`, the
/// OBJ with its MTL after it.
pub(crate) fn mesh_files(stem: &str, format: &str, parts: &[SolidMesh]) -> Result<Vec<(String, Vec<u8>)>, String> {
let names = mesh_file_names(stem, format)?;
let bytes = match format {
/// OBJ with its MTL after it and the PNG files of `textures` last (an OBJ's opacity maps each after
/// its texture). `textures` holds the picture of each part that has one, in the order of `parts`.
pub(crate) fn mesh_files(stem: &str, format: &str, parts: &[SolidMesh], textures: &[Option<Texture>]) -> Result<Vec<(String, Vec<u8>)>, String> {
let (images, image) = images(parts.len(), textures);
let maps: Vec<bool> = images.iter().map(|(_, map)| map.is_some()).collect();
let names = mesh_file_names(stem, format, &maps)?;
let pictures: Vec<Arc<Vec<u8>>> = images.iter().map(|(p, _)| p.clone()).collect();
let scene = Scene { parts, textures, image: &image, pictures: &pictures, maps: &maps };
let pngs = || pictures.iter().map(|p| p.as_ref().clone());
let bytes: Vec<Vec<u8>> = match format {
"obj" => {
let (obj, mtl) = obj(&obj_stem(stem), parts);
vec![obj.into_bytes(), mtl.into_bytes()]
let stem = obj_stem(stem);
let (obj, mtl) = obj(&stem, &scene);
let with_maps = images.iter().flat_map(|(p, map)| std::iter::once(p.as_ref().clone()).chain(map.as_ref().map(|m| m.as_ref().clone())));
[obj.into_bytes(), mtl.into_bytes()].into_iter().chain(with_maps).collect()
}
"gltf" => vec![gltf(stem, &scene).into_bytes()],
"usda" => std::iter::once(usda(stem, &scene).into_bytes()).chain(pngs()).collect(),
_ => {
let mut members = vec![(format!("{stem}.usda"), usda(stem, &scene).into_bytes())];
members.extend(pngs().enumerate().map(|(k, png)| (texture_name(stem, k), png)));
vec![super::zip::store_aligned(&members, 64)?]
}
"gltf" => vec![gltf(stem, parts).into_bytes()],
"usda" => vec![usda(stem, parts).into_bytes()],
_ => vec![super::zip::store_aligned(&[(format!("{stem}.usda"), usda(stem, parts).into_bytes())], 64)?],
};
Ok(names.into_iter().zip(bytes).collect())
}
/// The distinct colors of `parts` in order, and each part's index among them.
fn materials(parts: &[SolidMesh]) -> (Vec<[f32; 4]>, Vec<usize>) {
let mut colors: Vec<[f32; 4]> = vec![];
let index = parts
/// The parts of an object with their pictures: `image` is each part's index among `pictures`, and
/// `maps` says for each picture whether it has an opacity map.
struct Scene<'a> {
parts: &'a [SolidMesh],
textures: &'a [Option<Texture>],
image: &'a [Option<usize>],
pictures: &'a [Arc<Vec<u8>>],
maps: &'a [bool],
}
impl Scene<'_> {
/// Part `k`'s texture coordinates and picture, when it has a picture.
fn texture(&self, k: usize) -> Option<(&[[f64; 2]], usize)> {
let t = self.textures.get(k)?.as_ref()?;
Some((t.uv.as_slice(), (*self.image.get(k)?)?))
}
}
/// A material: a color, with a picture that replaces its red, green and blue.
#[derive(Clone, Copy, PartialEq)]
struct Material {
color: [f32; 4],
image: Option<usize>,
}
/// The distinct materials of `scene`'s parts in order, and each part's index among them.
fn materials(scene: &Scene) -> (Vec<Material>, Vec<usize>) {
let mut out: Vec<Material> = vec![];
let index = scene
.parts
.iter()
.map(|p| {
colors.iter().position(|c| *c == p.color).unwrap_or_else(|| {
colors.push(p.color);
colors.len() - 1
.enumerate()
.map(|(k, p)| {
let m = Material { color: p.color, image: scene.texture(k).map(|(_, i)| i) };
out.iter().position(|c| *c == m).unwrap_or_else(|| {
out.push(m);
out.len() - 1
})
})
.collect();
(colors, index)
(out, index)
}
/// An sRGB channel (0..1) as linear light.
@@ -96,8 +217,9 @@ fn num(v: f64) -> String {
format!("{v}")
}
fn obj(stem: &str, parts: &[SolidMesh]) -> (String, String) {
let (colors, material) = materials(parts);
fn obj(stem: &str, scene: &Scene) -> (String, String) {
let parts = scene.parts;
let (materials, material) = materials(scene);
let mut o = String::new();
let _ = writeln!(o, "mtllib {stem}.mtl");
let _ = writeln!(o, "o {stem}");
@@ -106,33 +228,64 @@ fn obj(stem: &str, parts: &[SolidMesh]) -> (String, String) {
let _ = writeln!(o, "v {} {} {}", num(v[0]), num(v[1]), num(v[2]));
}
}
// OBJ's texture coordinates run up from the picture's bottom.
for k in 0..parts.len() {
for uv in scene.texture(k).map(|(uv, _)| uv).unwrap_or_default() {
let _ = writeln!(o, "vt {} {}", num(uv[0]), num(1.0 - uv[1]));
}
}
for p in parts {
for n in &p.mesh.normals {
let _ = writeln!(o, "vn {} {} {}", num(n[0]), num(n[1]), num(n[2]));
}
}
let mut base = 1usize;
let (mut base, mut uv_base) = (1usize, 1usize);
for (k, p) in parts.iter().enumerate() {
let _ = writeln!(o, "g Solid_{}", k + 1);
let _ = writeln!(o, "usemtl Material_{}", material.get(k).copied().unwrap_or(0) + 1);
let textured = scene.texture(k).filter(|(uv, _)| uv.len() == p.mesh.positions.len()).is_some();
for t in &p.mesh.triangles {
let [a, b, c] = t.map(|i| i as usize + base);
let _ = writeln!(o, "f {a}//{a} {b}//{b} {c}//{c}");
if textured {
let [a, b, c] = t.map(|i| i as usize);
let corner = |i: usize| format!("{}/{}/{}", i + base, i + uv_base, i + base);
let _ = writeln!(o, "f {} {} {}", corner(a), corner(b), corner(c));
} else {
let [a, b, c] = t.map(|i| i as usize + base);
let _ = writeln!(o, "f {a}//{a} {b}//{b} {c}//{c}");
}
}
base += p.mesh.positions.len();
uv_base += scene.texture(k).map_or(0, |(uv, _)| uv.len());
}
let mut m = String::new();
for (k, c) in colors.iter().enumerate() {
for (k, mat) in materials.iter().enumerate() {
let c = mat.color;
let _ = writeln!(m, "newmtl Material_{}", k + 1);
let _ = writeln!(m, "Kd {} {} {}", num(f64::from(c[0])), num(f64::from(c[1])), num(f64::from(c[2])));
let _ = writeln!(m, "d {}", num(f64::from(c[3])));
match mat.image {
// The picture holds the color; Kd multiplies it.
Some(_) => {
let _ = writeln!(m, "Kd 1 1 1");
}
None => {
let _ = writeln!(m, "Kd {} {} {}", num(f64::from(c[0])), num(f64::from(c[1])), num(f64::from(c[2])));
}
}
// A picture's opacity map holds the opacity, as gray levels.
let _ = writeln!(m, "d {}", if mat.image.is_some() { "1".to_string() } else { num(f64::from(c[3])) });
let _ = writeln!(m, "illum 1");
if let Some(i) = mat.image {
let _ = writeln!(m, "map_Kd -clamp on {}", texture_name(stem, i));
if scene.maps.get(i).copied().unwrap_or(false) {
let _ = writeln!(m, "map_d -clamp on {}", opacity_name(stem, i));
}
}
}
(o, m)
}
fn gltf(stem: &str, parts: &[SolidMesh]) -> String {
let (colors, material) = materials(parts);
fn gltf(stem: &str, scene: &Scene) -> String {
let parts = scene.parts;
let (materials, material) = materials(scene);
let mut buffer: Vec<u8> = vec![];
let (mut views, mut accessors, mut primitives) = (vec![], vec![], vec![]);
let mut view = |buffer: &mut Vec<u8>, bytes: Vec<u8>, target: u32| -> usize {
@@ -154,16 +307,25 @@ fn gltf(stem: &str, parts: &[SolidMesh]) -> String {
}));
accessors.push(json!({ "bufferView": normals, "componentType": 5126, "count": count, "type": "VEC3" }));
accessors.push(json!({ "bufferView": indices, "componentType": 5125, "count": p.mesh.triangles.len() * 3, "type": "SCALAR" }));
primitives.push(json!({
let mut primitive = json!({
"attributes": { "POSITION": at, "NORMAL": at + 1 },
"indices": at + 2,
"material": material.get(k).copied().unwrap_or(0),
}));
});
// glTF's texture coordinates run down from the picture's top, as the picture's own do.
if let Some((uv, _)) = scene.texture(k).filter(|(uv, _)| uv.len() == count) {
let bytes = uv.iter().flatten().flat_map(|x| (*x as f32).to_le_bytes()).collect();
let coords = view(&mut buffer, bytes, 34962);
primitive["attributes"]["TEXCOORD_0"] = json!(accessors.len());
accessors.push(json!({ "bufferView": coords, "componentType": 5126, "count": count, "type": "VEC2" }));
}
primitives.push(primitive);
}
let materials: Vec<Value> = colors
let materials: Vec<Value> = materials
.iter()
.enumerate()
.map(|(k, c)| {
.map(|(k, mat)| {
let c = mat.color;
let mut m = json!({
"name": format!("Material_{}", k + 1),
"pbrMetallicRoughness": {
@@ -173,13 +335,18 @@ fn gltf(stem: &str, parts: &[SolidMesh]) -> String {
},
"doubleSided": true,
});
if let Some(i) = mat.image {
// The picture holds the color and the opacity; the factor multiplies them.
m["pbrMetallicRoughness"]["baseColorFactor"] = json!([1.0, 1.0, 1.0, 1.0]);
m["pbrMetallicRoughness"]["baseColorTexture"] = json!({ "index": i });
}
if c[3] < 1.0 {
m["alphaMode"] = json!("BLEND");
}
m
})
.collect();
let doc = json!({
let mut doc = json!({
"asset": { "version": "2.0", "generator": "VectorCraft" },
"scene": 0,
"scenes": [{ "nodes": [0] }],
@@ -193,6 +360,14 @@ fn gltf(stem: &str, parts: &[SolidMesh]) -> String {
"bufferViews": views,
"accessors": accessors,
});
if !scene.pictures.is_empty() {
// Linear filtering, mipmaps, and coordinates held at the picture's edge.
doc["samplers"] = json!([{ "magFilter": 9729, "minFilter": 9987, "wrapS": 33071, "wrapT": 33071 }]);
doc["textures"] = Value::Array((0..scene.pictures.len()).map(|i| json!({ "sampler": 0, "source": i })).collect());
doc["images"] = Value::Array(
scene.pictures.iter().map(|p| json!({ "uri": format!("data:image/png;base64,{}", vectorcraft_format::base64_encode(p)) })).collect(),
);
}
serde_json::to_string_pretty(&doc).unwrap_or_default()
}
@@ -205,8 +380,9 @@ fn prim_name(name: &str) -> String {
out
}
fn usda(stem: &str, parts: &[SolidMesh]) -> String {
let (colors, material) = materials(parts);
fn usda(stem: &str, scene: &Scene) -> String {
let parts = scene.parts;
let (materials, material) = materials(scene);
let root = prim_name(stem);
let triple = |v: [f64; 3]| format!("({}, {}, {})", num(v[0]), num(v[1]), num(v[2]));
let list = |items: Vec<String>| items.join(", ");
@@ -238,23 +414,178 @@ fn usda(stem: &str, parts: &[SolidMesh]) -> String {
linear(c[2])
);
let _ = writeln!(u, " float[] primvars:displayOpacity = [{}] (\n interpolation = \"constant\"\n )", c[3]);
// USD's texture coordinates run up from the picture's bottom.
if let Some((uv, _)) = scene.texture(k).filter(|(uv, _)| uv.len() == p.mesh.positions.len()) {
let st = list(uv.iter().map(|t| format!("({}, {})", num(t[0]), num(1.0 - t[1]))).collect());
let _ = writeln!(u, " texCoord2f[] primvars:st = [{st}] (\n interpolation = \"vertex\"\n )");
}
let _ = writeln!(u, " uniform token subdivisionScheme = \"none\"\n }}\n");
}
let _ = writeln!(u, " def Scope \"Materials\"\n {{");
for (k, c) in colors.iter().enumerate() {
let m = k + 1;
for (k, mat) in materials.iter().enumerate() {
let (m, c) = (k + 1, mat.color);
let at = format!("/{root}/Materials/Material_{m}");
let _ = writeln!(u, " def Material \"Material_{m}\"\n {{");
let _ = writeln!(u, " token outputs:surface.connect = </{root}/Materials/Material_{m}/Surface.outputs:surface>\n");
let _ = writeln!(u, " token outputs:surface.connect = <{at}/Surface.outputs:surface>\n");
let _ = writeln!(u, " def Shader \"Surface\"\n {{");
let _ = writeln!(u, " uniform token info:id = \"UsdPreviewSurface\"");
let _ = writeln!(u, " color3f inputs:diffuseColor = ({}, {}, {})", linear(c[0]), linear(c[1]), linear(c[2]));
let _ = writeln!(u, " float inputs:opacity = {}", c[3]);
match mat.image {
// The picture holds the color, and the opacity when the face is not opaque.
Some(_) => {
let _ = writeln!(u, " color3f inputs:diffuseColor.connect = <{at}/Texture.outputs:rgb>");
if c[3] < 1.0 {
let _ = writeln!(u, " float inputs:opacity.connect = <{at}/Texture.outputs:a>");
} else {
let _ = writeln!(u, " float inputs:opacity = 1");
}
}
None => {
let _ = writeln!(u, " color3f inputs:diffuseColor = ({}, {}, {})", linear(c[0]), linear(c[1]), linear(c[2]));
let _ = writeln!(u, " float inputs:opacity = {}", c[3]);
}
}
let _ = writeln!(u, " float inputs:roughness = 1");
let _ = writeln!(u, " token outputs:surface\n }}\n }}");
let _ = writeln!(u, " token outputs:surface\n }}");
if let Some(i) = mat.image {
let _ = writeln!(u, "\n def Shader \"Texture\"\n {{");
let _ = writeln!(u, " uniform token info:id = \"UsdUVTexture\"");
let _ = writeln!(u, " asset inputs:file = @{}@", texture_name(stem, i));
let _ = writeln!(u, " float2 inputs:st.connect = <{at}/Coordinates.outputs:result>");
let _ = writeln!(u, " token inputs:sourceColorSpace = \"sRGB\"");
let _ = writeln!(u, " token inputs:wrapS = \"clamp\"");
let _ = writeln!(u, " token inputs:wrapT = \"clamp\"");
let _ = writeln!(u, " float3 outputs:rgb");
if c[3] < 1.0 {
let _ = writeln!(u, " float outputs:a");
}
let _ = writeln!(u, " }}");
let _ = writeln!(u, "\n def Shader \"Coordinates\"\n {{");
let _ = writeln!(u, " uniform token info:id = \"UsdPrimvarReader_float2\"");
let _ = writeln!(u, " string inputs:varname = \"st\"");
let _ = writeln!(u, " float2 outputs:result\n }}");
}
let _ = writeln!(u, " }}");
}
let _ = writeln!(u, " }}\n}}");
u
}
/// The pictures of the graphics on `parts` ([`SolidMesh::graphics`]), one for each part in order
/// (`None` for a part without graphics, or whose graphics draw nothing): the part's color with its
/// graphics drawn over it, flat and unshaded ([`vectorcraft_render::effects::mesh_graphics_art`]),
/// over the bounds of the art points of its corners, `size` pixels along the longer side. Parts with
/// the same color, face, graphics and bounds share one picture. `pixels` counts the pixels drawn so
/// far, and every call of one export shares it: an error when it passes [`MAX_TEXTURE_PIXELS`].
pub(crate) fn textures(doc: &Document, parts: &[SolidMesh], size: u32, pixels: &mut u64) -> Result<Vec<Option<Texture>>, String> {
let mut renderer: Option<vectorcraft_render::Renderer> = None;
// Each picture drawn: the part it was drawn for, its bounds, and the PNG with its opacity map
// (`None`: nothing drawn).
let mut drawn: Vec<Drawn> = vec![];
let mut out = vec![];
for part in parts {
let Some(g) = &part.graphics else {
out.push(None);
continue;
};
let Some(frame) = texture_frame(g) else {
out.push(None);
continue;
};
let scale = f64::from(size) / frame.width().max(frame.height());
let fit = |side: f64| ((side * scale).ceil() as u32).clamp(1, size);
let (w, h) = (fit(frame.width()), fit(frame.height()));
let same = |(p, r, _): &&Drawn| p.color == part.color && *r == frame && p.graphics.as_ref().is_some_and(|o| same_graphics(o, g));
let png = match drawn.iter().find(same) {
Some((_, _, png)) => png.clone(),
None => {
let png = match vectorcraft_render::effects::mesh_graphics_art(doc, NodeId(0), g)? {
None => None,
Some(art) => {
*pixels = pixels.saturating_add(u64::from(w) * u64::from(h));
if *pixels > MAX_TEXTURE_PIXELS {
return Err(format!(
"the graphics need more than {MAX_TEXTURE_PIXELS} pixels of textures: lower textureSize (now {size})"
));
}
let renderer = renderer.get_or_insert_with(vectorcraft_render::Renderer::new);
Some(picture(doc, renderer, (part.color, g.opacity, g.object), art, (frame, scale), (w, h))?)
}
};
drawn.push((part, frame, png.clone()));
png
}
};
out.push(png.map(|(png, opacity)| {
let uv = g.art.iter().map(|p| [(p.x - frame.x0) * scale / f64::from(w), (p.y - frame.y0) * scale / f64::from(h)]).collect();
Texture { png, opacity, uv }
}));
}
Ok(out)
}
/// Does [`textures`] draw a picture for one of `parts`: a part with graphics whose corners span an
/// area and whose graphics draw something? Nothing is rendered.
pub fn draws_textures(doc: &Document, parts: &[SolidMesh]) -> bool {
parts.iter().any(|p| {
p.graphics
.as_ref()
.is_some_and(|g| texture_frame(g).is_some() && matches!(vectorcraft_render::effects::mesh_graphics_art(doc, NodeId(0), g), Ok(Some(_))))
})
}
/// The part of the art's plane a picture of `g` covers: the bounds of its corners' art points, when
/// they span an area.
fn texture_frame(g: &MeshGraphics) -> Option<Rect> {
g.art_bounds().filter(|r| r.width() > 1e-9 && r.height() > 1e-9 && r.width().is_finite() && r.height().is_finite())
}
/// A picture [`textures`] drew: the part, the bounds and the PNG with its opacity map.
type Drawn<'a> = (&'a SolidMesh, Rect, Option<Picture>);
/// Do `a` and `b` draw the same graphics on their face?
fn same_graphics(a: &MeshGraphics, b: &MeshGraphics) -> bool {
a.face == b.face && a.center == b.center && a.graphics == b.graphics && a.opacity == b.opacity && a.object == b.object
}
/// `art` drawn over `color` as a PNG of `w` × `h` pixels whose top left is `frame`'s top left, at
/// `scale` pixels a point, with a grayscale PNG of its alpha when some of it is not opaque. As on
/// the canvas, the art is drawn at `face` (the opacity of the face's fill or stroke), the color at
/// its own opacity without `object`'s, and `object` (the object's opacity) applies to the whole
/// picture.
fn picture(
doc: &Document,
renderer: &mut vectorcraft_render::Renderer,
(color, face, object): ([f32; 4], f32, f32),
mut art: Node,
(frame, scale): (Rect, f64),
(w, h): (u32, u32),
) -> Result<Picture, String> {
// The color reaches two pixels past the frame, so the picture's edge pixels are covered.
let reach = 2.0 / scale;
let back = Rect::new(frame.x0 - reach, frame.y0 - reach, frame.x0 + f64::from(w) / scale + reach, frame.y0 + f64::from(h) / scale + reach);
let fill = Paint::solid(Color::rgb(color[0], color[1], color[2]));
let mut ground = Node::path(NodeId(0), vectorcraft_geom::shapes::rectangle(back), Appearance::basic(fill, Paint::None, 0.0));
let unit = |v: f32| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 };
let object = unit(object);
ground.opacity = if object > 0.0 { unit(color[3] / object) } else { 0.0 };
art.opacity *= unit(face);
let mut group = Node::group(NodeId(0), vec![Arc::new(ground), Arc::new(art)]);
group.opacity = object;
let group = Arc::new(group);
let (pw, ph) = (u16::try_from(w).map_err(|_| "texture too large")?, u16::try_from(h).map_err(|_| "texture too large")?);
let view = Affine::scale(scale) * Affine::translate((-frame.x0, -frame.y0));
let drawn = renderer.render_node(doc, &group, pw, ph, view).ok_or_else(|| "the graphics could not be drawn".to_string())?;
let alpha: Vec<u8> = drawn.pixels.iter().skip(3).step_by(4).copied().collect();
let opacity = if alpha.iter().all(|a| *a == 255) {
None
} else {
let gray = image::GrayImage::from_raw(w, h, alpha).ok_or("the texture's opacity could not be drawn")?;
let mut png = vec![];
gray.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).map_err(|e| format!("PNG encoding failed: {e}"))?;
Some(Arc::new(png))
};
Ok((Arc::new(drawn.to_png()?), opacity))
}
#[cfg(test)]
mod tests;
+133 -14
View File
@@ -7,7 +7,7 @@ use super::*;
fn square(color: [f32; 4]) -> SolidMesh {
let [a, b, c, d] = [[-5.0, -5.0, 0.0], [5.0, -5.0, 0.0], [5.0, 5.0, 0.0], [-5.0, 5.0, 0.0]];
let mesh = Mesh { positions: vec![a, b, c, a, c, d], normals: vec![[0.0, 0.0, 1.0]; 6], triangles: vec![[0, 1, 2], [3, 4, 5]] };
SolidMesh { mesh, color }
SolidMesh::plain(mesh, color)
}
const RED: [f32; 4] = [1.0, 0.0, 0.0, 1.0];
@@ -18,9 +18,14 @@ fn text(files: &[(String, Vec<u8>)], name: &str) -> String {
String::from_utf8(bytes.clone()).unwrap()
}
/// [`mesh_files`] without textures.
fn plain_files(stem: &str, format: &str, parts: &[SolidMesh]) -> Result<Vec<(String, Vec<u8>)>, String> {
mesh_files(stem, format, parts, &[])
}
#[test]
fn obj_numbers_corners_across_solids_and_names_its_materials() {
let files = mesh_files("Box", "obj", &[square(RED), square(BLUE), square(RED)]).unwrap();
let files = plain_files("Box", "obj", &[square(RED), square(BLUE), square(RED)]).unwrap();
assert_eq!(files.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), ["Box.obj", "Box.mtl"]);
let obj = text(&files, "Box.obj");
assert!(obj.starts_with("mtllib Box.mtl\no Box\n"));
@@ -36,7 +41,7 @@ fn obj_numbers_corners_across_solids_and_names_its_materials() {
#[test]
fn gltf_holds_its_buffer_and_every_accessor_fits_it() {
let files = mesh_files("Box", "gltf", &[square(RED), square(BLUE)]).unwrap();
let files = plain_files("Box", "gltf", &[square(RED), square(BLUE)]).unwrap();
let g: Value = serde_json::from_str(&text(&files, "Box.gltf")).unwrap();
assert_eq!(g["asset"]["version"], "2.0");
let uri = g["buffers"][0]["uri"].as_str().unwrap();
@@ -59,11 +64,13 @@ fn gltf_holds_its_buffer_and_every_accessor_fits_it() {
assert_eq!(g["materials"][1]["alphaMode"], "BLEND");
assert!(g["materials"][0].get("alphaMode").is_none());
assert_eq!(g["materials"][0]["doubleSided"], true);
// Without graphics there are no textures.
assert!(g.get("images").is_none() && g.get("textures").is_none() && prims[0]["attributes"].get("TEXCOORD_0").is_none());
}
#[test]
fn usda_is_y_up_in_points_with_a_material_for_each_color() {
let files = mesh_files("My Box", "usda", &[square(RED), square([0.5, 0.5, 0.5, 1.0])]).unwrap();
let files = plain_files("My Box", "usda", &[square(RED), square([0.5, 0.5, 0.5, 1.0])]).unwrap();
let u = text(&files, "My Box.usda");
assert!(u.starts_with("#usda 1.0\n"));
assert!(u.contains("defaultPrim = \"My_Box\"") && u.contains("upAxis = \"Y\"") && u.contains("def Xform \"My_Box\""), "{u}");
@@ -75,11 +82,12 @@ fn usda_is_y_up_in_points_with_a_material_for_each_color() {
// sRGB 0.5 is about 0.214 linear.
assert!(u.contains("color3f inputs:diffuseColor = (0.21404"), "{u}");
assert_eq!(u.matches('{').count(), u.matches('}').count());
assert!(!u.contains("primvars:st") && !u.contains("UsdUVTexture"));
}
#[test]
fn usdz_stores_the_layer_uncompressed_on_a_64_byte_boundary() {
let files = mesh_files("Box", "usdz", &[square(RED)]).unwrap();
let files = plain_files("Box", "usdz", &[square(RED)]).unwrap();
let (name, zip) = &files[0];
assert_eq!(name, "Box.usdz");
// The local header: 30 bytes, the name, then the extra field.
@@ -88,7 +96,7 @@ fn usdz_stores_the_layer_uncompressed_on_a_64_byte_boundary() {
assert_eq!(u16_at(8), 0, "stored, not deflated");
let start = 30 + u16_at(26) + u16_at(28);
assert_eq!(start % 64, 0);
let layer = mesh_files("Box", "usda", &[square(RED)]).unwrap().remove(0).1;
let layer = plain_files("Box", "usda", &[square(RED)]).unwrap().remove(0).1;
assert_eq!(&zip[start..start + layer.len()], layer.as_slice());
let archive = super::super::zip::Archive::open(zip, 8).unwrap();
assert_eq!(archive.read("Box.usda", usize::MAX).unwrap(), Some(layer));
@@ -96,11 +104,11 @@ fn usdz_stores_the_layer_uncompressed_on_a_64_byte_boundary() {
#[test]
fn an_obj_names_its_mtl_file_without_spaces_or_comment_marks() {
let files = mesh_files("Box #1", "obj", &[square(RED)]).unwrap();
let files = plain_files("Box #1", "obj", &[square(RED)]).unwrap();
assert_eq!(files.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), ["Box__1.obj", "Box__1.mtl"]);
assert!(text(&files, "Box__1.obj").starts_with("mtllib Box__1.mtl\n"));
assert_eq!(mesh_file_names("Box #1", "obj").unwrap(), ["Box__1.obj", "Box__1.mtl"]);
assert_eq!(mesh_file_names("Box #1", "usda").unwrap(), ["Box #1.usda"]);
assert_eq!(mesh_file_names("Box #1", "obj", &[]).unwrap(), ["Box__1.obj", "Box__1.mtl"]);
assert_eq!(mesh_file_names("Box #1", "usda", &[]).unwrap(), ["Box #1.usda"]);
}
#[test]
@@ -108,17 +116,17 @@ fn obj_and_usda_keep_coordinates_a_32_bit_float_would_merge() {
let mut part = square(RED);
part.mesh.positions[0] = [20_000_000.0, 0.0, 0.0];
part.mesh.positions[1] = [20_000_001.0, 0.0, 0.0];
let obj = text(&mesh_files("Box", "obj", std::slice::from_ref(&part)).unwrap(), "Box.obj");
let obj = text(&plain_files("Box", "obj", std::slice::from_ref(&part)).unwrap(), "Box.obj");
assert!(obj.contains("v 20000000 0 0\nv 20000001 0 0\n"), "{obj}");
let usda = text(&mesh_files("Box", "usda", &[part]).unwrap(), "Box.usda");
let usda = text(&plain_files("Box", "usda", &[part]).unwrap(), "Box.usda");
assert!(usda.contains("(20000001, 0, 0)"));
}
#[test]
fn an_unknown_format_is_refused() {
assert!(mesh_files("Box", "fbx", &[square(RED)]).is_err());
assert!(mesh_file_names("Box", "").is_err());
assert_eq!(mesh_file_names("Box", "obj").unwrap(), ["Box.obj", "Box.mtl"]);
assert!(plain_files("Box", "fbx", &[square(RED)]).is_err());
assert!(mesh_file_names("Box", "", &[]).is_err());
assert_eq!(mesh_file_names("Box", "obj", &[]).unwrap(), ["Box.obj", "Box.mtl"]);
}
#[test]
@@ -128,3 +136,114 @@ fn prim_names_are_usd_identifiers() {
assert_eq!(prim_name(""), "_");
assert_eq!(prim_name("é/x"), "__x");
}
/// A red square, then a blue one whose corners show picture `png` (u to the right, v down).
fn textured(png: &[u8]) -> (Vec<SolidMesh>, Vec<Option<Texture>>) {
let uv = vec![[0.0, 1.0], [1.0, 1.0], [1.0, 0.0], [0.0, 1.0], [1.0, 0.0], [0.0, 0.0]];
let texture = Texture { png: Arc::new(png.to_vec()), opacity: None, uv };
(vec![square(RED), square(BLUE)], vec![None, Some(texture)])
}
#[test]
fn each_format_carries_a_textured_part_with_its_coordinates_and_picture() {
let png = b"\x89PNG picture".to_vec();
let (parts, pictures) = textured(&png);
// OBJ: vt runs up from the picture's bottom, the textured faces name it, and map_Kd the PNG
// written beside it, with its name in one word.
let files = mesh_files("My Box", "obj", &parts, &pictures).unwrap();
assert_eq!(files.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), ["My_Box.obj", "My_Box.mtl", "My_Box-texture-1.png"]);
assert_eq!(files[2].1, png);
let obj = text(&files, "My_Box.obj");
assert_eq!(obj.lines().filter(|l| l.starts_with("vt ")).collect::<Vec<_>>(), ["vt 0 0", "vt 1 0", "vt 1 1", "vt 0 0", "vt 1 1", "vt 0 1"]);
assert_eq!(obj.lines().rfind(|l| l.starts_with("f ")), Some("f 10/4/10 11/5/11 12/6/12"));
assert!(obj.contains("f 1//1 2//2 3//3"), "the plain part keeps no texture coordinates");
let mtl = text(&files, "My_Box.mtl");
assert!(mtl.contains("newmtl Material_2\nKd 1 1 1\nd 1\nillum 1\nmap_Kd -clamp on My_Box-texture-1.png\n"), "{mtl}");
assert_eq!(mtl.matches("map_Kd").count(), 1);
// glTF: TEXCOORD_0 down from the top, and the picture embedded as a data URI.
let g: Value = serde_json::from_str(&text(&mesh_files("Box", "gltf", &parts, &pictures).unwrap(), "Box.gltf")).unwrap();
let prims = g["meshes"][0]["primitives"].as_array().unwrap();
assert!(prims[0]["attributes"].get("TEXCOORD_0").is_none());
let uv = &g["accessors"][prims[1]["attributes"]["TEXCOORD_0"].as_u64().unwrap() as usize];
assert_eq!((uv["type"].as_str(), uv["count"].as_u64(), uv["componentType"].as_u64()), (Some("VEC2"), Some(6), Some(5126)));
let view = &g["bufferViews"][uv["bufferView"].as_u64().unwrap() as usize];
let data = vectorcraft_format::base64_decode(g["buffers"][0]["uri"].as_str().unwrap().split(',').nth(1).unwrap()).unwrap();
let at = view["byteOffset"].as_u64().unwrap() as usize;
let first: Vec<f32> = (0..2).map(|k| f32::from_le_bytes(data[at + 4 * k..at + 4 * k + 4].try_into().unwrap())).collect();
assert_eq!(first, [0.0, 1.0]);
let material = &g["materials"][prims[1]["material"].as_u64().unwrap() as usize];
assert_eq!(material["pbrMetallicRoughness"]["baseColorTexture"]["index"], 0);
assert_eq!(material["pbrMetallicRoughness"]["baseColorFactor"], serde_json::json!([1.0, 1.0, 1.0, 1.0]));
assert_eq!(g["textures"][0]["source"], 0);
assert_eq!(g["samplers"][0]["wrapS"], 33071);
let image = g["images"][0]["uri"].as_str().unwrap().strip_prefix("data:image/png;base64,").unwrap();
assert_eq!(vectorcraft_format::base64_decode(image).unwrap(), png);
// USDA: st up from the bottom, read by a primvar reader into a UV texture of the PNG beside it.
let files = mesh_files("Box", "usda", &parts, &pictures).unwrap();
assert_eq!(files.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), ["Box.usda", "Box-texture-1.png"]);
let u = text(&files, "Box.usda");
assert_eq!(u.matches("primvars:st").count(), 1);
assert!(u.contains("texCoord2f[] primvars:st = [(0, 0), (1, 0), (1, 1), (0, 0), (1, 1), (0, 1)]"), "{u}");
assert!(u.contains("color3f inputs:diffuseColor.connect = </Box/Materials/Material_2/Texture.outputs:rgb>"), "{u}");
assert!(u.contains("asset inputs:file = @Box-texture-1.png@") && u.contains("uniform token info:id = \"UsdUVTexture\""));
assert!(u.contains("float2 inputs:st.connect = </Box/Materials/Material_2/Coordinates.outputs:result>"));
assert!(u.contains("string inputs:varname = \"st\""));
assert_eq!(u.matches('{').count(), u.matches('}').count());
// USDZ: the layer first, then the picture, each on a 64-byte boundary.
let zip = mesh_files("Box", "usdz", &parts, &pictures).unwrap().remove(0).1;
let archive = super::super::zip::Archive::open(&zip, 8).unwrap();
assert_eq!(archive.read("Box.usda", usize::MAX).unwrap().map(String::from_utf8), Some(Ok(u)));
assert_eq!(archive.read("Box-texture-1.png", usize::MAX).unwrap(), Some(png.clone()));
let u16_at = |at: usize| u16::from_le_bytes([zip[at], zip[at + 1]]) as usize;
let u32_at = |at: usize| u32::from_le_bytes([zip[at], zip[at + 1], zip[at + 2], zip[at + 3]]) as usize;
let first = 30 + u16_at(26) + u16_at(28);
let second = first + u32_at(18);
assert_eq!(&zip[second..second + 4], &[0x50, 0x4b, 0x03, 0x04], "the picture comes second");
let data = second + 30 + u16_at(second + 26) + u16_at(second + 28);
assert_eq!((first % 64, data % 64), (0, 0));
assert_eq!(&zip[data..data + png.len()], png.as_slice());
}
#[test]
fn a_textured_face_that_is_not_opaque_takes_its_opacity_from_the_picture() {
let (parts, mut pictures) = textured(b"picture");
if let Some(t) = pictures[1].as_mut() {
t.opacity = Some(Arc::new(b"gray".to_vec()));
}
// OBJ: the opacity map, written after its texture, is the MTL's map_d.
let files = mesh_files("My Box", "obj", &parts, &pictures).unwrap();
let names: Vec<&str> = files.iter().map(|(n, _)| n.as_str()).collect();
assert_eq!(names, ["My_Box.obj", "My_Box.mtl", "My_Box-texture-1.png", "My_Box-texture-1-opacity.png"]);
assert_eq!(files[3].1, b"gray");
assert_eq!(mesh_file_names("My Box", "obj", &image_maps(&pictures)).unwrap(), names);
let mtl = text(&files, "My_Box.mtl");
assert!(mtl.contains("d 1\nillum 1\nmap_Kd -clamp on My_Box-texture-1.png\nmap_d -clamp on My_Box-texture-1-opacity.png\n"), "{mtl}");
let g: Value = serde_json::from_str(&text(&mesh_files("Box", "gltf", &parts, &pictures).unwrap(), "Box.gltf")).unwrap();
let material = &g["materials"][1];
assert_eq!((material["pbrMetallicRoughness"]["baseColorFactor"][3].as_f64(), material["alphaMode"].as_str()), (Some(1.0), Some("BLEND")));
let usda = mesh_files("Box", "usda", &parts, &pictures).unwrap();
assert_eq!(usda.len(), 2, "USD reads the opacity from the texture's alpha");
let u = text(&usda, "Box.usda");
assert!(u.contains("float inputs:opacity.connect = </Box/Materials/Material_2/Texture.outputs:a>") && u.contains("float outputs:a"), "{u}");
// An opaque textured face reads no opacity from its picture.
let (_, plain) = textured(b"picture");
let opaque = vec![square(RED), square([0.0, 0.0, 1.0, 1.0])];
let u = text(&mesh_files("Box", "usda", &opaque, &plain).unwrap(), "Box.usda");
assert!(!u.contains("outputs:a") && u.contains("float inputs:opacity = 1"), "{u}");
let mtl = text(&mesh_files("Box", "obj", &opaque, &plain).unwrap(), "Box.mtl");
assert!(!mtl.contains("map_d") && mtl.contains("Kd 1 1 1\nd 1\n"), "{mtl}");
}
#[test]
fn parts_sharing_a_picture_write_it_once() {
let (mut parts, mut pictures) = textured(b"one");
parts.push(square(BLUE));
pictures.push(pictures[1].clone());
assert_eq!(image_maps(&pictures), [false]);
let files = mesh_files("Box", "obj", &parts, &pictures).unwrap();
assert_eq!(files.len(), 3);
assert_eq!(text(&files, "Box.mtl").matches("newmtl").count(), 2, "the blue parts share the textured material");
assert_eq!(mesh_file_names("Box", "usda", &[false, true]).unwrap(), ["Box.usda", "Box-texture-1.png", "Box-texture-2.png"]);
assert_eq!(mesh_file_names("A @b", "gltf", &[false, false]).unwrap(), ["A @b.gltf"]);
assert_eq!(texture_name("A @b#c", 0), "A__b_c-texture-1.png");
}
+157
View File
@@ -246,6 +246,163 @@ fn export_3d_writes_into_a_folder_or_one_zip() {
let _ = std::fs::remove_dir_all(&dir);
}
/// A blue 100 × 100 square extruded straight on, with a red 10 × 20 graphic "Mark" mapped onto its
/// front at its center and onto its back 30 pt to the right (as the back is seen from behind),
/// collected as a 3D asset in `format`.
fn mapped(format: &str) -> (Session, u64) {
let mut s = session();
let mark = run(&mut s, "path.create", json!({"d": "M300 300L310 300L310 320L300 320Z"}))["id"].clone();
run(&mut s, "paint.setFill", json!({"color": "#ff0000"}));
run(&mut s, "threeD.addGraphic", json!({"name": "Mark", "ids": [mark]}));
let id = run(&mut s, "path.create", json!({"d": "M100 100L200 100L200 200L100 200Z"}))["id"].as_u64().unwrap();
run(&mut s, "paint.setFill", json!({"color": "#0000ff"}));
run(&mut s, "effect.apply", json!({"effect": "threeD.extrude", "params": {"rotationX": 0.0, "rotationY": 0.0, "rotationZ": 0.0, "depth": 20.0}}));
run(&mut s, "threeD.mapGraphic", json!({"symbol": "Mark", "ids": [id]}));
run(&mut s, "threeD.mapGraphic", json!({"symbol": "Mark", "face": "back", "x": 30.0, "ids": [id]}));
run(&mut s, "layer.setProps", json!({"id": id, "name": "Box"}));
let asset = run(&mut s, "assets.add3D", json!({"ids": [id], "format": format}))["assets"][0].as_u64().unwrap();
(s, asset)
}
/// The color of pixel `(x, y)` of PNG `png`.
fn pixel(png: &[u8], x: u32, y: u32) -> [u8; 4] {
image::load_from_memory(png).unwrap().to_rgba8().get_pixel(x, y).0
}
fn is_red(p: [u8; 4]) -> bool {
p[0] > 200 && p[1] < 50 && p[2] < 50 && p[3] == 255
}
fn is_blue(p: [u8; 4]) -> bool {
p[0] < 50 && p[1] < 50 && p[2] > 200 && p[3] == 255
}
#[test]
fn export_3d_paints_mapped_graphics_on_their_caps_in_every_format() {
for (format, names) in [
("usda", vec!["Box.usda", "Box-texture-1.png", "Box-texture-2.png"]),
("usdz", vec!["Box.usdz"]),
("gltf", vec!["Box.gltf"]),
("obj", vec!["Box.obj", "Box.mtl", "Box-texture-1.png", "Box-texture-2.png"]),
] {
let (mut s, _) = mapped(format);
let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128})));
assert_eq!(out.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), names, "{format}");
}
// The front's picture: the cap's 100 pt across 128 pixels, blue with the red graphic at the
// middle; the back's: the graphic 30 pt to the right as seen from behind, which is to the left
// in the art's plane.
let (mut s, _) = mapped("usda");
let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128})));
let (front, back) = (&out[1].1, &out[2].1);
assert_eq!(image::load_from_memory(front).unwrap().to_rgba8().dimensions(), (128, 128));
assert!(is_red(pixel(front, 64, 64)) && is_blue(pixel(front, 2, 2)) && is_blue(pixel(front, 64, 10)));
let at = |pt: f64| (pt * 1.28) as u32;
assert!(is_red(pixel(back, at(20.0), 64)) && is_blue(pixel(back, 64, 64)), "{:?}", pixel(back, 64, 64));
// The USDA's front cap shows the front picture through st, up from the picture's bottom.
let usda = String::from_utf8(out[0].1.clone()).unwrap();
assert_eq!(usda.matches("primvars:st").count(), 2);
assert_eq!(usda.matches("def Mesh").count(), 3, "the walls, the front cap and the back cap");
// glTF holds both pictures, and a cap's coordinates stay inside its picture.
let (mut s, _) = mapped("gltf");
let out = files(&run(&mut s, "assets.export3D", json!({})));
let g: Value = serde_json::from_slice(&out[0].1).unwrap();
assert_eq!(g["images"].as_array().map(Vec::len), Some(2));
let png = vectorcraft_format::base64_decode(g["images"][0]["uri"].as_str().unwrap().split(',').nth(1).unwrap()).unwrap();
assert_eq!(image::load_from_memory(&png).unwrap().to_rgba8().dimensions(), (1024, 1024), "1024 pixels by default");
}
#[test]
fn a_texture_takes_the_opacity_of_the_fill_and_of_the_object_as_the_canvas_draws_them() {
let half = |a: u8| (120..=135).contains(&a);
// A half-opaque fill: the face and the graphic over it are each drawn at half opacity, so the
// graphic covers three quarters.
let (mut s, asset) = mapped("usda");
let doc = &s.active().unwrap().doc;
let id = doc.asset(asset).unwrap().nodes[0];
let fill = doc.node(id).unwrap().appearance.items.iter().position(|i| matches!(i, vectorcraft_doc::AppearanceItem::Fill(_))).unwrap();
run(&mut s, "select.set", json!({"ids": [id.0]}));
run(&mut s, "transparency.set", json!({"item": fill, "opacity": 50}));
let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128})));
let (on, around) = (pixel(&out[1].1, 64, 64), pixel(&out[1].1, 2, 2));
assert!(on[0] > on[2] && (185..=197).contains(&on[3]), "{on:?}");
assert!(around[2] > 200 && half(around[3]), "{around:?}");
let usda = String::from_utf8(out[0].1.clone()).unwrap();
assert!(usda.contains("float inputs:opacity.connect"), "the texture's alpha is the opacity");
// An OBJ's opacity map has the alpha as gray levels.
run(&mut s, "assets.set3DFormat", json!({"assets": [asset], "format": "obj"}));
let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128})));
assert_eq!(out[3].0, "Box-texture-1-opacity.png");
let gray = image::load_from_memory(&out[3].1).unwrap().to_luma8();
let (g_on, g_around) = (gray.get_pixel(64, 64).0[0], gray.get_pixel(2, 2).0[0]);
assert!((185..=197).contains(&g_on) && half(g_around), "{g_on} {g_around}");
// A half-opaque object: the face and the graphic are drawn opaque, and the whole picture at
// half opacity.
let (mut s, asset) = mapped("usda");
let id = s.active().unwrap().doc.asset(asset).unwrap().nodes[0];
run(&mut s, "transparency.set", json!({"ids": [id.0], "opacity": 50}));
let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128})));
let (on, around) = (pixel(&out[1].1, 64, 64), pixel(&out[1].1, 2, 2));
assert!(on[0] > 200 && on[2] < 50 && half(on[3]), "{on:?}");
assert!(around[2] > 200 && around[0] < 50 && half(around[3]), "{around:?}");
// A gradient whose stops are clear: the face is clear, and the graphic keeps its opacity.
let (mut s, asset) = mapped("usda");
let id = s.active().unwrap().doc.asset(asset).unwrap().nodes[0];
run(&mut s, "select.set", json!({"ids": [id.0]}));
let clear = json!({"stops": [{"offset": 0, "color": "#0000ff", "opacity": 0}, {"offset": 1, "color": "#0000ff", "opacity": 0}]});
run(&mut s, "paint.setFill", json!({"gradient": clear}));
let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128})));
let (on, around) = (pixel(&out[1].1, 64, 64), pixel(&out[1].1, 2, 2));
assert!(is_red(on), "{on:?}");
assert_eq!(around[3], 0, "{around:?}");
}
#[test]
fn export_3d_keeps_flat_colors_without_graphics_and_refuses_bad_texture_sizes() {
let (mut s, asset) = mapped("obj");
for bad in [json!(64), json!(5000), json!(512.5), json!("512"), json!(-1)] {
assert!(s.execute("assets.export3D", &json!({"textureSize": bad})).is_err(), "{bad}");
}
// Without its graphics the box is one plain mesh, as before.
let id = s.doc().unwrap().doc.asset(asset).unwrap().nodes[0].0;
run(&mut s, "select.set", json!({"ids": [id]}));
run(&mut s, "effect.setParams", json!({"index": 0, "params": {"graphics": []}}));
let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128})));
assert_eq!(out.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), ["Box.obj", "Box.mtl"]);
let obj = String::from_utf8(out[0].1.clone()).unwrap();
assert!(!obj.contains("vt ") && obj.lines().filter(|l| l.starts_with("g ")).count() == 1);
}
#[test]
fn texture_pixels_are_counted_across_one_export() {
let (s, asset) = mapped("gltf");
let d = &s.doc().unwrap().doc;
let node = d.node(d.asset(asset).unwrap().nodes[0]).unwrap();
let parts = vectorcraft_render::effects::three_d_meshes_in(Some(d), node).unwrap();
let mut pixels = 0;
let made = crate::cmd::fileio::textures(d, &parts, 128, &mut pixels).unwrap();
assert_eq!((made.iter().flatten().count(), pixels), (2, 2 * 128 * 128));
let mut pixels = crate::cmd::fileio::MAX_TEXTURE_PIXELS - 128 * 128;
let e = crate::cmd::fileio::textures(d, &parts, 128, &mut pixels).unwrap_err();
assert!(e.contains("textureSize"), "{e}");
}
#[test]
fn only_graphics_that_draw_count_as_textures() {
let parts_of = |s: &Session, asset: u64| {
let d = &s.doc().unwrap().doc;
let node = d.node(d.asset(asset).unwrap().nodes[0]).unwrap();
vectorcraft_render::effects::three_d_meshes_in(Some(d), node).unwrap()
};
let (mut s, asset) = mapped("obj");
assert!(crate::cmd::fileio::draws_textures(&s.doc().unwrap().doc, &parts_of(&s, asset)));
// With its symbol gone the graphic draws nothing, so the export writes no texture.
run(&mut s, "symbol.delete", json!({"name": "Mark"}));
assert!(!crate::cmd::fileio::draws_textures(&s.doc().unwrap().doc, &parts_of(&s, asset)));
let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128})));
assert_eq!(out.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), ["Box.obj", "Box.mtl"]);
}
#[test]
fn three_d_assets_round_trip_through_the_native_format() {
let mut s = session();
+2 -2
View File
@@ -12,8 +12,8 @@ pub mod fold;
mod solid;
mod visibility;
pub use solid::{
Bevel, BevelShape, DepthPlane, Extrude, FaceMap, Facet, Inflate, PlanarFace, TOO_COMPLEX_SOLID, View, extrude, extrude_face_map, inflate,
inflate_each, inflate_together, plane, plane_face_map,
Bevel, BevelShape, DepthPlane, Extrude, FaceMap, Facet, Inflate, MeshFace, PlanarFace, TOO_COMPLEX_SOLID, View, extrude, extrude_face_map,
extrude_mesh_face, inflate, inflate_each, inflate_together, plane, plane_face_map, plane_mesh_face,
};
pub use visibility::{VisibleFace, visible_faces};
mod shading;
+1 -1
View File
@@ -28,7 +28,7 @@ pub(crate) use build::PLANES;
use build::{Camera, cuts, edge_distance, newell, section};
pub(crate) use build::{Face3, Keep, extrude_faces, plane_faces};
pub use build::{extrude, plane};
pub use face_map::{FaceMap, extrude_face_map, plane_face_map};
pub use face_map::{FaceMap, MeshFace, extrude_face_map, extrude_mesh_face, plane_face_map, plane_mesh_face};
#[cfg(test)]
use inflate::GRID_WORK;
pub(crate) use inflate::inflate_faces;
+89
View File
@@ -174,6 +174,95 @@ pub fn plane_face_map(bounds: Rect, view: View) -> Option<FaceMap> {
Some(FaceMap::new(&camera, &placing, true))
}
/// A planar face in its solid's mesh ([`crate::Mesh`]): where the points of the art's plane lie
/// before projection, in the mesh's coordinates (y up), and the face's outward normal there.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct MeshFace {
/// An art point `p` lies at `x · (p.x - centre.x) + y · (p.y - centre.y) + at`, with the art's
/// center at `at`.
x: V3,
y: V3,
centre: Point,
at: V3,
normal: V3,
/// A plane's mesh turns its normal toward the viewer, so its triangles face either way.
either_side: bool,
}
/// From the effects' view space (y down) to the mesh's (y up).
fn mesh_space(v: V3) -> V3 {
V3(v.0, -v.1, v.2)
}
impl MeshFace {
fn new(camera: &Camera, placing: &Placing, centre: Point, side: f64, either_side: bool) -> Self {
let (x, y, _) = placing.frame();
let at = mesh_space(placing.place(centre));
let normal = mesh_space(camera.rotate(V3(0.0, 0.0, side))).unit();
Self { x: mesh_space(x), y: mesh_space(y), centre, at, normal, either_side }
}
/// The art point that mesh point `m` shows, when `m` lies on the face's plane and a triangle
/// with unit normal `n` there belongs to the face. `None` otherwise, and when the face has no
/// area (a taper of 0 at the back).
pub fn art_point(&self, m: [f64; 3], n: [f64; 3]) -> Option<Point> {
let facing = self.normal.dot(V3(n[0], n[1], n[2]));
let facing = if self.either_side { facing.abs() } else { facing };
// A NaN normal faces no way.
let faces = facing > 1.0 - 1e-6;
if !faces {
return None;
}
// Measured from the art's center, so the tolerance follows the solid's size and not where
// the art lies on the page.
let d = V3(m[0], m[1], m[2]).sub(self.at);
let (xx, xy, yy) = (self.x.dot(self.x), self.x.dot(self.y), self.y.dot(self.y));
let det = xx * yy - xy * xy;
let spans = xx > 1e-24 && yy > 1e-24 && det >= 1e-12 * xx * yy;
if !spans {
return None;
}
let (bx, by) = (self.x.dot(d), self.y.dot(d));
let (px, py) = ((bx * yy - by * xy) / det, (xx * by - xy * bx) / det);
let on = V3(self.x.0 * px + self.y.0 * py, self.x.1 * px + self.y.1 * py, self.x.2 * px + self.y.2 * py);
let off = d.sub(on);
let size = 1.0 + d.dot(d).sqrt();
let p = Point::new(self.centre.x + px, self.centre.y + py);
(p.x.is_finite() && p.y.is_finite() && off.dot(off).sqrt() <= 1e-6 * size).then_some(p)
}
}
/// Extrude & Bevel's cap `face` in the solid's mesh ([`MeshFace`]), for a solid built with
/// `bounds`, `options` and `view`, as [`extrude_face_map`] maps it on the page. With a depth of 0
/// the art is a plane ([`plane_mesh_face`]). `None` for a hollow solid, for the back of a plane,
/// and for invalid bounds.
pub fn extrude_mesh_face(bounds: Rect, options: Extrude, view: View, face: PlanarFace) -> Option<MeshFace> {
check_bounds(bounds).ok()?;
let o = options.sanitized();
if o.depth <= 0.0 {
return (face == PlanarFace::Front).then(|| plane_mesh_face(bounds, view)).flatten();
}
if !o.cap {
return None;
}
let camera = Camera::new(view, bounds, o.depth);
let (t, side) = match face {
PlanarFace::Front => (0.0, 1.0),
PlanarFace::Back => (1.0, -1.0),
};
let placing = Placing::new(&camera, bounds.center(), Turn::new(bounds, o.twist, o.taper, t), o.depth / 2.0 - o.depth * t);
Some(MeshFace::new(&camera, &placing, bounds.center(), side, false))
}
/// The plane [`super::plane`] turns art with `bounds` into, with `view`, in its mesh
/// ([`MeshFace`]).
pub fn plane_mesh_face(bounds: Rect, view: View) -> Option<MeshFace> {
check_bounds(bounds).ok()?;
let camera = Camera::new(view, bounds, 0.0);
let placing = Placing::new(&camera, bounds.center(), Turn::new(bounds, 0.0, 1.0, 0.0), 0.0);
Some(MeshFace::new(&camera, &placing, bounds.center(), 1.0, true))
}
#[cfg(test)]
#[path = "tests_face_map.rs"]
mod tests;
+65 -1
View File
@@ -1,7 +1,7 @@
use vectorcraft_geom::{BezPath, FillRule, PathData, Point, Rect};
use super::super::{Extrude, Facet, PlanarFace, View, extrude, plane};
use super::{FaceMap, NEAREST, extrude_face_map, plane_face_map};
use super::{FaceMap, MeshFace, NEAREST, extrude_face_map, extrude_mesh_face, plane_face_map, plane_mesh_face};
fn square() -> (PathData, Rect) {
let mut b = BezPath::new();
@@ -143,6 +143,70 @@ fn a_page_point_nearer_the_eye_than_the_page_map_allows_has_no_art_point() {
assert_eq!(map.to_art(q), None, "the inverse map takes {q:?} back to an art point the page map has no point for");
}
/// The art point of every corner of each triangle of `mesh` that `face` takes, and how many
/// triangles it takes.
fn mesh_art(mesh: &crate::Mesh, face: &MeshFace) -> (Vec<Point>, usize) {
let (mut points, mut taken) = (vec![], 0);
for t in &mesh.triangles {
let corners: Option<Vec<Point>> = t.iter().map(|&i| face.art_point(mesh.positions[i as usize], mesh.normals[i as usize])).collect();
if let Some(c) = corners {
points.extend(c);
taken += 1;
}
}
(points, taken)
}
#[test]
fn a_caps_mesh_corners_go_back_to_the_art_they_were_made_from() {
let (path, bounds) = square();
let bevel = crate::Bevel { width: 4.0, height: 4.0, ..Default::default() };
let options = Extrude { twist: 30.0, taper: 0.5, bevel: Some(bevel), ..Extrude::default() };
let view = turned(40.0);
let mesh = crate::extrude_mesh(&path, FillRule::NonZero, bounds, options, view).unwrap();
// The bevel's width sets the walls, and the back cap, out from the front's outline.
let outset = bounds.inflate(4.0, 4.0);
for (face, cap) in [(PlanarFace::Front, bounds), (PlanarFace::Back, outset)] {
let mesh_face = extrude_mesh_face(bounds, options, view, face).unwrap();
let (points, taken) = mesh_art(&mesh, &mesh_face);
// A square cap is two triangles, and none of the bevel's or the walls' triangles are
// taken. The art points undo the back's twist and taper.
assert_eq!(taken, 2, "{face:?}");
for p in points {
let near = corners(cap).iter().map(|c| c.distance(p)).fold(f64::INFINITY, f64::min);
assert!(near < 1e-6, "{face:?}: {p:?} is {near} from the cap's corners");
}
}
// A hollow solid has no caps, and a plane's mesh has only the front, facing either way.
assert_eq!(extrude_mesh_face(bounds, Extrude { cap: false, ..options }, view, PlanarFace::Front), None);
let plane = crate::plane_mesh(&path, FillRule::NonZero, bounds, view).unwrap();
let (points, taken) = mesh_art(&plane, &plane_mesh_face(bounds, view).unwrap());
assert_eq!(taken, plane.triangles.len());
assert!(points.iter().all(|p| corners(bounds).iter().any(|c| c.distance(*p) < 1e-6)), "{points:?}");
assert_eq!(extrude_mesh_face(bounds, Extrude { depth: 0.0, ..options }, view, PlanarFace::Back), None);
}
#[test]
fn a_cap_far_from_the_page_origin_takes_none_of_a_step_bevels_treads() {
let (path, bounds) = square();
let far = vectorcraft_geom::kurbo::Affine::translate((1e7, 1e7));
let path = PathData::from_bezpath(&(far * path.to_bezpath()));
let bounds = far.transform_rect_bbox(bounds);
let bevel = crate::Bevel { width: 4.0, height: 4.0, shape: crate::BevelShape::Step, ..Default::default() };
let options = Extrude { bevel: Some(bevel), ..Extrude::default() };
let view = turned(0.0);
let mesh = crate::extrude_mesh(&path, FillRule::NonZero, bounds, options, view).unwrap();
let mesh_face = extrude_mesh_face(bounds, options, view, PlanarFace::Front).unwrap();
let (points, taken) = mesh_art(&mesh, &mesh_face);
// The treads face the same way as the cap, a few points behind it: only the cap's two
// triangles are taken, wherever the art lies on the page.
assert_eq!(taken, 2);
for p in points {
let near = corners(bounds).iter().map(|c| c.distance(p)).fold(f64::INFINITY, f64::min);
assert!(near < 1e-6, "{p:?} is {near} from the cap's corners");
}
}
#[test]
fn the_mapped_part_of_a_rectangle_stops_before_the_eye() {
let (_, bounds) = square();
+22 -2
View File
@@ -230,6 +230,17 @@ fn collect(app: &mut VectorcraftApp, ctx: &egui::Context, ids: Option<Vec<NodeId
}
}
/// Does the export of 3D asset `asset` draw a texture for the graphics mapped onto its faces
/// ([`vectorcraft_engine::cmd::fileio::draws_textures`])? Only objects whose 3D effects map graphics
/// are built to find out.
fn writes_textures(doc: &vectorcraft_doc::Document, asset: &ExportAsset) -> bool {
let maps = |e: &vectorcraft_doc::Effect| e.visible && !vectorcraft_render::effects::mapped_graphics(&e.params).is_empty();
let nodes: Vec<&Node> = asset.nodes.iter().filter_map(|id| doc.node(*id)).collect();
nodes.iter().any(|n| n.appearance.effects.iter().chain(n.appearance.items.iter().flat_map(|i| i.effects())).any(maps))
&& vectorcraft_render::effects::three_d_meshes_of_in(Some(doc), nodes.iter().copied())
.is_ok_and(|parts| vectorcraft_engine::cmd::fileio::draws_textures(doc, &parts))
}
/// Export assets `ids` (`files_each`: the files one asset makes) into a picked folder (without a
/// folder picker: the last folder Export for Screens used, else the Desktop); the web downloads
/// them, several as one zip.
@@ -240,11 +251,20 @@ fn export(app: &mut VectorcraftApp, ids: Vec<u64>, files_each: usize) {
fn export_now(app: &mut VectorcraftApp, ids: Vec<u64>, files_each: usize) {
// 3D assets are written as mesh files (`assets.export3D`), the others as pictures.
let web = io::is_web(app);
let Some(st) = app.session.active() else { return };
let format = |id: &u64| st.doc.asset(*id).and_then(|a| a.format_3d.clone());
let (three_d, ids): (Vec<u64>, Vec<u64>) = ids.into_iter().partition(|id| format(id).is_some());
// An OBJ is two files.
let mesh_files: usize = three_d.iter().map(|id| if format(id).as_deref() == Some("obj") { 2 } else { 1 }).sum();
// An OBJ is two files, and an OBJ or a USDA whose graphics draw a texture writes it beside
// them. Only the web, which zips several files, needs the count.
let mesh_files: usize = three_d
.iter()
.map(|id| {
let format = format(id);
let textures = web && matches!(format.as_deref(), Some("obj" | "usda")) && st.doc.asset(*id).is_some_and(|a| writes_textures(&st.doc, a));
usize::from(format.as_deref() == Some("obj")) + 1 + usize::from(textures)
})
.sum();
// Create Sub-folders as the panel menu checks it: on by default, and remembered folders (per
// row, format or item) are used as Export for Screens uses them (a remembered `subfolders`
// false beside them would alone put every file in the folder itself).
+1 -1
View File
@@ -183,7 +183,7 @@ VectorCraft choices; an original approximation, never compared with another appl
| 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 Revolve's side ([three-d.md](three-d.md#graphics)); no base materials, graphics on Inflate or on Extrude & Bevel's walls and bevels, 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 |
| 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`); no textures, map art or shading ([3D export help](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/export-3d-vector-artwork.html)) |
| 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,
+2 -1
View File
@@ -704,7 +704,8 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi
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, textures, map art and shading in 3D export.
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).
- **Impact:** specialist; Materials is the one menu stub left.
- **Estimate:** 25–45 h; plan in `plan/` before coding.
+16 -1
View File
@@ -9109,13 +9109,28 @@ default), `usdz`, `gltf` or `obj`; the panel shows a Format row for the 3D asset
`assets.set3DFormat {assets, format}` sets it (an undo step only when the format changes). `assets.list` gives each
asset's `format3D` (null for a picture asset).
`assets.export3D {assets?, folder?, zip?}` writes each 3D asset (default: all of them) as a mesh file named after it:
`assets.export3D {assets?, folder?, zip?, textureSize?}` writes each 3D asset (default: all of them) as a mesh file named after it:
`.usda`, `.usdz`, `.gltf` (glTF 2.0, its buffer embedded) or `.obj` with its `.mtl` (whitespace and `#` in an OBJ's
name become `_`). Every solid of the object (the
fill's, each stroke's, a group's members') is its own mesh, with a two-sided material in the color it is painted
(a gradient's stops averaged, a pattern gray). The mesh holds the solid's faces before they are projected onto the
page, those turned away from the viewer included, at the object's 3D rotation, y up, about the point the object turns
about: in points (USD's layer gives `metersPerUnit`), in meters in glTF. Files that would share a name get `-2`, `-3` and so on.
Graphics mapped onto a plane or onto Extrude & Bevel's front or back cap (`threeD.mapGraphic`) are exported as a PNG
texture of that face: the face's color with its graphics drawn over it, flat and unlit, on a mesh of the face's own
triangles with texture coordinates and a material that shows the texture. A face that is not opaque keeps its opacity
in the texture's alpha: as on the canvas, the graphics take the opacity of the face's fill or stroke, and the object's
opacity applies to the face and its graphics together. glTF embeds the PNG as a data URI
(`TEXCOORD_0`, `baseColorTexture`), USDZ stores it after the layer, USDA reads it through `primvars:st`, a
`UsdPrimvarReader_float2` and a `UsdUVTexture` connected to the surface's `diffuseColor`, and OBJ gives `vt` coordinates
and an MTL `map_Kd`; OBJ and USDA write the PNG beside them as `<name>-texture-1.png`, `-texture-2.png` and so on
(whitespace, `#` and `@` become `_`). USD reads a face's opacity from the texture's alpha (`outputs:a`), and an OBJ
whose face is not opaque also gets `<name>-texture-1-opacity.png`, the alpha as gray levels, for the MTL's `map_d`.
Faces with the same color, graphics and bounds share one texture. `textureSize` (128 to
4096, default 1024, VectorCraft's own values) is the number of pixels along the longer side of each texture; one export
draws at most 67,108,864 texture pixels in all, and past that it is refused. Graphics on Revolve's side are not
exported yet. The layouts follow glTF 2.0, UsdPreviewSurface (<https://openusd.org/release/spec_usdpreviewsurface.html>)
and OBJ/MTL (<https://www.loc.gov/preservation/digital/formats/fdd/fdd000508.shtml>).
With `zip`, the files go into one ZIP named after the document with `-3D` added (`Untitled-1-3D.zip`), or
`3D Assets.zip` when the document's title gives no file name.
An object whose face has a hole that crosses the face's outline or another hole is refused, by `assets.add3D` and
+1
View File
@@ -1469,6 +1469,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- Extrude & Bevel (both kinds) and Rotate keep the art's curves in the faces they draw, export and expand: caps and the edges of walls and bevels where they meet a cap are cubics with smooth anchors where the art's are, fitted within 0.001 pt in perspective and within the sampling tolerance on a bevel's inset. An edge of a twisted wall that is cut into pieces, a piece of curve that does not fit after 8 halvings, and the curves past 1,048,576 for one solid stay straight (VectorCraft's own values; [three-d.md](three-d.md#what-differs-from-the-public-documentation)). Tests `solid::tests::a_cap_keeps_the_curves_of_the_art`, `a_cap_in_perspective_fits_the_projected_curves`, `a_beveled_cap_and_its_walls_share_their_curves`, `twisted_beveled_tiny_and_degenerate_caps_keep_their_curves`.
- Export 3D Object (Asset Export's menu): an object with Extrude & Bevel, Revolve, Inflate or Rotate becomes a 3D asset whose Format is USDA (the default), USDZ, glTF or OBJ, and Export writes each of its solids as a mesh with a material in its paint's color (`assets.add3D`, `assets.set3DFormat`, `assets.export3D`; [export 3D vector artwork](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/export-3d-vector-artwork.html)).
- Export 3D Object builds each Extrude & Bevel (both kinds) and Inflate solid once: the same build gives the faces that count toward the object's limit and the faces of its mesh, and the meshes match those of a separate build bit for bit. Tests `mesh::tests::a_meshed_solid_is_built_once`, `an_extruded_solid_and_its_mesh_match_the_two_built_apart`, `inflated_solids_and_their_meshes_match_the_two_built_apart`, `solids::tests_mesh::one_build_exports_the_meshes_built_apart`, `a_stroke_past_the_limits_is_left_out_of_the_export`.
- Export 3D Object writes the graphics mapped onto a plane or onto Extrude & Bevel's front and back caps as a PNG texture of each face, the face's color with its graphics drawn flat and unlit over it, on a mesh of that face with texture coordinates, in all four formats (glTF embeds it, USDZ packs it after the layer, OBJ and USDA write `<name>-texture-1.png` beside them; `assets.export3D` `textureSize`, 128 to 4096 pixels, default 1024, VectorCraft's own values; [the help page](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/map-artwork-on-3d-objects.html)). Graphics on Revolve's side, materials and lighting are not exported. Tests `a_caps_mesh_corners_go_back_to_the_art_they_were_made_from`, `a_mesh_carries_its_caps_graphics_flat_in_the_arts_plane`, `each_format_carries_a_textured_part_with_its_coordinates_and_picture`, `export_3d_paints_mapped_graphics_on_their_caps_in_every_format`.
- Checking an Extrude & Bevel (both kinds) or Inflate effect builds each solid the effect draws once, about the bounds the effect draws it about; a shape with no fill still has its profile built on its own. Tests `solids::tests::the_check_builds_each_drawn_solid_once`, `the_check_builds_the_profile_of_a_shape_with_no_fill`.
- Initial live Revolve (#605, #846): a portable geometry and shading crate (`three-d`), editable path and compound profiles, compact options with artboard rotation and light gizmos, SVG/PDF vector output and Expand Appearance that can trim covered faces. Open ends have continuous caps by default, shading is smooth with one to ten colored lights, and intersecting surfaces' visibility is approximate ([revolve.md](revolve.md)).
- Revolve takes graphics on its swept side, shaded with the object's light ([the archived reference, page 185](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=185)). By VectorCraft's own rule a graphic wraps around the axis at its own size at every distance from it, narrows toward the silhouette, follows the profile along its length and is hidden where the side faces away (`threeD.mapGraphic`; `revolve::tests_graphics`, `tests::side_faces_lie_on_the_unrolled_surface_and_caps_do_not`, `map_graphic_puts_a_graphic_on_the_side_of_a_revolve`).