//! File formats. Designs use JSON or versioned containers (`.sc`; `.solidcraft` still opens); the authoritative //! document rebuilds on load and optional display caches remain provisional. Bodies export //! as STL (binary or ASCII), OBJ, STEP and 3MF, and assemblies as URDF ([`urdf()`]); STEP, IGES, //! FreeCAD and Rhino files import as a base feature (see [`step_import_feature`]), 3MF and //! STL files as mesh bodies (see [`mesh_import_feature`]), PLY, PCD and XYZ files as point //! clouds (see [`read_point_cloud`]), and KiCad boards as a mesh substrate with referenced STEP //! component models. #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] #![forbid(unsafe_code)] mod airfoil; pub mod catalog; mod design; pub mod design_lock; mod design_metadata; mod dxf; mod dxf_out; mod excellon; pub mod formats; mod gerber; mod gerber_area; mod gerber_set; mod glb; pub use design::{ DesignCompression, DesignContainerReader, DesignPreview, FileKind, ImportCache, OpenPgpSignature, OpenPgpSigner, ProvenanceChain, ProvenanceRecord, ProvenanceReport, ProvenanceSave, ProvenanceSigner, ProvenanceStatus, ProvenanceSummary, SignatureSource, Signer, THUMBNAIL_SIZE, file_kind, has_design_provenance, is_design_container, read_design_file, read_design_geometry, read_design_preview, read_design_provenance, read_design_provenance_chain, read_design_provenance_chain_file, read_design_provenance_file, read_design_provenance_file_checked, read_design_provenance_summary_file, read_design_thumbnail, read_design_thumbnail_file, read_drawing, read_drawing_file, write_design_container, write_design_container_with_cache, write_design_container_with_compression, write_design_container_with_preview, write_design_container_with_provenance, write_design_container_with_thumbnail, write_drawing_container, }; pub use glb::{DEFAULT_COLOR as GLB_DEFAULT_COLOR, MAX_GLB_BYTES, export_glb}; mod legacy_dir; pub mod library_files; pub mod limits; #[cfg(test)] mod mutate; mod native_cad; pub use native_cad::{ CadmpegOptions, DecalPlan, Hidden, NATIVE_CAD_EXTS, NativeDesign, OpticsPlan, SurfaceMap, SurfacePlan, USD_EXTS, cadmpeg_export, cadmpeg_step_records, detects_freecad, is_freecad_path, is_native_cad_path, is_usd_path, native_cad_design, native_cad_records, native_cad_to_step, read_usd, usd_from_design, usd_records, }; pub mod paper; mod pat; mod pcd; mod ply; mod ply_complex; pub use ply::{ply_counts, read_ply_mesh}; mod point_cloud; pub use point_cloud::{CloudFile, DEFAULT_MAX_POINTS, MAX_POINT_CLOUD_BYTES, is_ply_path, is_point_cloud_path, read_point_cloud}; pub mod safe_write; pub mod safe_zip; pub mod sdf; mod sketch2d; mod svg; /// Explicit development-test seams; absent from ordinary production builds. #[cfg(any(test, feature = "dxf-legacy-baseline-tests"))] pub mod test_support { pub use crate::dxf_out::{DxfEntity, DxfLayer, legacy_dxf_baseline}; } mod threemf; pub mod urdf; pub mod vfs; pub use airfoil::{Airfoil, AirfoilFormat, MAX_AIRFOIL_BYTES, MAX_AIRFOIL_POINTS, read_airfoil}; pub use dxf::{DxfReadProfile, DxfWriteOptions, read_dxf, read_dxf_file, read_dxf_file_with_profile, write_dxf, write_dxf_entities, write_dxf_opts}; pub use dxf_out::{ DxfEntity, DxfEntityWeight, DxfFile, DxfFileEntity, DxfFileLayer, DxfGeometryBounds, DxfLayer, DxfLayerId, DxfLinetype, DxfPath, DxfPathStyle, DxfShape, DxfSourceBlock, DxfStandardWeight, DxfTextHorizontalAlignment, DxfTextRecordKind, DxfTextSource, DxfTextVerticalAlignment, DxfVertex, admit_path, loop_lwpolyline, loop_lwpolyline_scaled, path_shapes, write_dxf_drawing_units, write_dxf_file, write_dxf_file_with_text_bounds, }; pub use excellon::{DrillArc, DrillHit, DrillSlot, Drills, read_excellon}; pub use gerber::{GerberLayer, GerberOutline, read_gerber_layer, read_gerber_outline}; pub use gerber_set::{ BOARD_EXTENSIONS, BoardJob, GerberSet, MAX_SET_FILES, SetFile, SetRole, classify_set, is_zip_path, read_gerber_set, zip_entries, }; pub use legacy_dir::{APP_ID, PREVIOUS_APP_IDS, adopt_legacy_dir, legacy_flatpak_paths}; pub use pat::{PatImportOptions, PatUnits, read_pat}; pub use safe_write::{backup_path, write_atomic}; pub use sketch2d::{Geom2, MAX_DRAWING_BYTES}; pub use svg::{CurveWarning, SvgDrawing, decode_svg, read_svg, read_svg_drawing, svg_nothing_to_import, svg_sheet}; mod gltf_in; pub use gltf_in::{GltfImport, Loader, MeshPlan, PlanPlace, glb_container, is_gltf_path, read_gltf}; mod kicad_in; pub use kicad_in::{ DEFAULT_BOARD_COLOR, KicadBoard, KicadCopper, KicadDrill, KicadFootprint, KicadImport, KicadLoader, KicadModel, KicadModelFile, KicadOptions, KicadPad, KicadRepresentation, KicadStroke, KicadText, KicadVia, KicadZone, MAX_KICAD_BYTES, is_kicad_path, kicad_board_mesh, kicad_board_path, kicad_board_thickness, parse_kicad_board, parse_kicad_board_with, read_kicad, }; mod obj; pub use obj::read_obj; pub use sdf::{SdfDecal, SdfOptions, SdfPackage, sdf_model}; pub use threemf::{ MAX_3MF_BYTES, MeshObject, model_xml, model_xml_parts, model_xml_with, read_3mf, weld, write_3mf, write_3mf_parts, write_3mf_with, }; pub use urdf::{UrdfOptions, UrdfPackage, urdf}; mod vrml_in; pub use vrml_in::{MAX_VRML_BYTES, VrmlMesh, is_vrml_path, read_vrml}; use solidcore_record::Vec3; use solidcraft_doc::{Document, Metadata, ModelState}; use solidcraft_geom::prelude::*; use solidcraft_geom::{MassProperties, Mesh}; /// Source commit of the checkout at build time, or `"unknown"` without Git. /// Identifies committed source; uncommitted changes are not marked. pub const SOURCE_COMMIT: &str = env!("SOLIDCRAFT_SOURCE_COMMIT"); /// Design file extension: new designs, autosaves and recovery files are written as `.sc`. pub const DESIGN_EXT: &str = "sc"; /// The design extensions of earlier releases, newest first. Compatibility shim /// (docs/compatibility.md): such files still open everywhere a design opens, and Save keeps /// writing an opened file under its own name; new designs are saved as [`DESIGN_EXT`]. pub const LEGACY_DESIGN_EXTS: [&str; 1] = ["solidcraft"]; /// Every extension a design file may have, current first. pub const DESIGN_EXTS: [&str; 2] = [DESIGN_EXT, LEGACY_DESIGN_EXTS[0]]; /// Is this extension (without the dot) one a design file may have (`sc` or a legacy one), any case? pub fn is_design_ext(ext: &str) -> bool { DESIGN_EXTS.iter().any(|x| ext.eq_ignore_ascii_case(x)) } /// Is this a design file name (`.sc`, a legacy extension, or plain `.json`), any case? pub fn is_design_path(path: &str) -> bool { std::path::Path::new(path).extension().and_then(|e| e.to_str()).is_some_and(|e| is_design_ext(e) || e.eq_ignore_ascii_case("json")) } /// Is this a design container file (`.sc` or a legacy extension, not plain JSON), any case? pub fn is_design_container_path(path: &std::path::Path) -> bool { path.extension().and_then(|e| e.to_str()).is_some_and(is_design_ext) } /// Drawing file extension: a drawing is a file of its own beside the designs it draws. Short and /// plain, as the browsers' file pickers take only ASCII letters, digits, `+` and `.`, up to 16 long. pub const DRAWING_EXT: &str = "scdwg"; /// Is this a drawing file name (`.scdwg`, any case)? pub fn is_drawing_path(path: &str) -> bool { std::path::Path::new(path).extension().and_then(|e| e.to_str()).is_some_and(|e| e.eq_ignore_ascii_case(DRAWING_EXT)) } /// Largest design file read by default; the desktop app may raise it ([`limits`], #4086). pub const MAX_DESIGN_BYTES: usize = 256 << 20; #[derive(Debug, thiserror::Error)] pub enum IoError { #[error("unsupported format `{0}` (use stl, obj, step, 3mf, glb, urdf or sc)")] Format(String), #[error("nothing to export: the design has no bodies")] Empty, #[error("{0}")] Invalid(String), #[error(transparent)] Kernel(#[from] solidcraft_kernel::KernelError), #[error(transparent)] Doc(#[from] solidcraft_doc::DocError), } pub type Result = std::result::Result; /// Largest STEP (or import) file read by default; the desktop app may raise it ([`limits`], #4086). pub const MAX_STEP_BYTES: usize = 512 << 20; /// Is this a CAD file read as an Import base feature: STEP (`.step` / `.stp`), IGES /// (`.igs` / `.iges`) or a format read through cadmpeg ([`is_native_cad_path`]), any case? pub fn is_step_path(path: &str) -> bool { std::path::Path::new(path) .extension() .and_then(|e| e.to_str()) .is_some_and(|e| ["step", "stp", "igs", "iges"].iter().any(|x| e.eq_ignore_ascii_case(x))) || is_native_cad_path(path) } /// Is this an IGES file name (`.igs` / `.iges`, any case)? pub fn is_iges_path(path: &str) -> bool { std::path::Path::new(path).extension().and_then(|e| e.to_str()).is_some_and(|e| e.eq_ignore_ascii_case("igs") || e.eq_ignore_ascii_case("iges")) } /// What the bodies of an imported STEP file are named after. Files from different CAD systems /// fill the solid's own name with different things (the part's name, the last feature's name, /// nothing), so the caller chooses. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub enum StepNames { /// Keep meaningful solid names; replace placeholders with the nearest named product. #[default] Auto, /// The solid's own name in the file, else the name of the product that holds it. Solid, /// The name of the product (part) that holds the body, else the solid's name. Product, /// The name of the assembly occurrence (instance) that holds the body, else the product's /// name (a body of a root part has no occurrence), else the solid's. Instance, } impl StepNames { /// `auto`, `solid`, `product` or `instance` (any case); `None` for anything else. pub fn parse(s: &str) -> Option { match s.trim().to_ascii_lowercase().as_str() { "auto" => Some(StepNames::Auto), "solid" => Some(StepNames::Solid), "product" => Some(StepNames::Product), "instance" => Some(StepNames::Instance), _ => None, } } } /// A name that says nothing about its body: empty, or the placeholder a file or the importer /// gives to something it has no name for. fn generic_name(n: &str) -> bool { let n = n.trim(); n.is_empty() || n.starts_with('(') || n.eq_ignore_ascii_case("import") || n.eq_ignore_ascii_case("unnamed") || ["body", "solid", "shell"].iter().any(|prefix| { n.get(..prefix.len()).is_some_and(|s| s.eq_ignore_ascii_case(prefix)) && n.get(prefix.len()..) .is_some_and(|s| s.chars().all(|c| c.is_ascii_digit() || c.is_ascii_whitespace() || matches!(c, '_' | '-' | '(' | ')'))) }) } /// The name an imported body gets under the `names` choice; the solid's name when the chosen /// one is missing or says nothing. fn body_name(b: &solidcraft_kernel::ImportedBody, names: StepNames) -> String { let usable = |n: &&String| !generic_name(n); let chosen = match names { StepNames::Auto if !generic_name(&b.name) => Some(&b.name), StepNames::Auto => b.path.iter().rev().find(usable).or_else(|| b.instance.as_ref().filter(usable)), StepNames::Solid => None, StepNames::Product => b.path.last().filter(usable), StepNames::Instance => b.instance.as_ref().filter(usable).or(b.path.last().filter(usable)), }; chosen.cloned().unwrap_or_else(|| b.name.clone()) } /// A name a flattened body should not keep: one [`generic_name`] gives up on, a name an exporting /// translator makes up for a shape it has no name for (Open CASCADE writes `Open CASCADE STEP /// translator 7.5 2.1.1` for each sub-shape), or a bare number (a library model's id). fn placeholder_name(n: &str) -> bool { let n = n.trim(); let lower = n.to_ascii_lowercase(); generic_name(n) || lower.contains("step translator") || lower.contains("step processor") || n.chars().all(|c| c.is_ascii_digit() || matches!(c, '.' | '-' | '_' | ' ')) } /// The names of a STEP file's bodies brought in flat (`file.insert_step`'s `flatten`), where no /// component says which part a body belongs to any more. `chosen` holds the names the `names` /// option chose, by body. Each body is named after the outermost named product it sits in below /// the file's root (`R63: Terminal`): a body whose chosen name is a placeholder takes the nearest /// named product's name instead (`Terminal`), and a body that is that product itself only its /// name (`R63`). A body in no named product keeps its name, or its nearest product's. Names are /// not made unique here: the Import feature numbers repeats, as for any import. pub fn flat_body_names(imp: &solidcraft_kernel::StepImport, chosen: &[String]) -> Vec { // One root product is the import itself (its component); several are parts of it. let below_root = usize::from(imp.tree.len() == 1); imp.bodies .iter() .enumerate() .map(|(k, b)| { let named = |n: &&String| !placeholder_name(n); let own = chosen .get(k) .filter(named) .or_else(|| b.path.iter().rev().find(named)) .or_else(|| b.instance.as_ref().filter(named)) .or_else(|| chosen.get(k).filter(|n| !n.trim().is_empty())) .unwrap_or(&b.name) .trim(); match b.path.iter().skip(below_root).find(named).map(|top| top.trim()) { Some(top) if top != own && !placeholder_name(own) => format!("{top}: {own}"), Some(top) => top.to_string(), None => own.to_string(), } }) .collect() } /// A STEP file read as an import feature. pub struct StepFeature { /// Timeline name: the root product's name, else the file name. pub name: String, pub kind: solidcraft_doc::FeatureKind, /// Body names from the file, as [`StepNames`] chose them (automatic by default). pub body_names: Vec, /// By body, whether the file marks it invisible: the design starts with it hidden. pub invisible: Vec, pub warnings: Vec, /// The file as read. Hold it until the feature has been evaluated: the timeline then reuses /// it instead of reading the file again (it is freed with the last holder). pub import: std::sync::Arc, } /// Bytes the encoding detector sees at most: the lines with 8-bit bytes, which in a STEP or IGES /// file are the names and descriptions. const ENCODING_SAMPLE_BYTES: usize = 64 << 10; /// STEP or IGES bytes as text. UTF-8 stays as it is. Some exporters write names in the system's /// legacy encoding instead of Part 21 escapes (GBK from Chinese vendors, Shift_JIS from Japanese /// ones): that encoding is detected from the lines holding 8-bit bytes and the file decoded with /// it, so a name reads `圆角` rather than U+FFFD noise (#2344). The syntax itself is ASCII in every /// such encoding. fn step_text(bytes: &[u8]) -> String { if let Ok(text) = std::str::from_utf8(bytes) { return text.to_owned(); } let mut detector = chardetng::EncodingDetector::new(); let mut fed = 0; for line in bytes.split(|b| *b == b'\n').filter(|line| !line.is_ascii()) { if fed >= ENCODING_SAMPLE_BYTES { break; } let line = line.get(..line.len().min(ENCODING_SAMPLE_BYTES - fed)).unwrap_or_default(); detector.feed(line, false); detector.feed(b"\n", false); fed += line.len() + 1; } detector.feed(&[], true); let encoding = detector.guess(None, false); encoding.decode_without_bom_handling(bytes).0.into_owned() } /// Read STEP bytes (`file` is the source file name) into an Import base feature. The file is /// read once here to fail early and collect names; the feature holds the STEP text. pub fn step_import_feature(bytes: &[u8], file: &str) -> Result { step_import_feature_named(bytes, file, StepNames::default()) } /// Which reader turns a file's solids into SolidCraft's bodies. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub enum StepReader { /// SolidCraft's own STEP reader (solidcore's), which keeps the STEP text. A FreeCAD or Rhino /// file is decoded by cadmpeg and restated as STEP by cadmpeg's STEP writer first, as before /// the records route. #[default] SolidCraft, /// cadmpeg's neutral model read straight into B-rep records, with no STEP text in between: a /// FreeCAD or Rhino file's solids, or a STEP file decoded by cadmpeg's STEP decoder (to /// compare with SolidCraft's reader). IGES is always SolidCraft's. The Preferences switch /// "Import with cadmpeg" (off by default) chooses it in the window. Cadmpeg, } impl StepReader { /// `solidcraft` or `cadmpeg` (any case); `None` for anything else. pub fn parse(s: &str) -> Option { match s.trim().to_ascii_lowercase().as_str() { "solidcraft" => Some(StepReader::SolidCraft), "cadmpeg" => Some(StepReader::Cadmpeg), _ => None, } } } /// [`step_import_feature`], with the bodies named after `names`. pub fn step_import_feature_named(bytes: &[u8], file: &str, names: StepNames) -> Result { step_import_feature_read(bytes, file, names, StepReader::SolidCraft) } /// [`step_import_feature_named`], a STEP, FreeCAD or Rhino file read by `reader`. pub fn step_import_feature_read(bytes: &[u8], file: &str, names: StepNames, reader: StepReader) -> Result { let _span = solidcraft_profile::span("import", "step_import_feature_named"); limits::check(limits::Kind::Step, bytes.len() as u64).map_err(IoError::Invalid)?; if reader == StepReader::Cadmpeg && is_step_path(file) && !is_iges_path(file) && !is_native_cad_path(file) { return records_import_feature(cadmpeg_step_records(bytes, file).map_err(IoError::Invalid)?, file, names); } if reader == StepReader::Cadmpeg && is_native_cad_path(file) { return records_import_feature(native_cad_records(bytes, file).map_err(IoError::Invalid)?, file, names); } // STEP is 7-bit text with escapes; tolerate stray 8-bit bytes. IGES and the cadmpeg formats // are restated as STEP (the feature keeps that STEP text). let (text, iges_warnings) = if is_native_cad_path(file) { native_cad_to_step(bytes, file).map_err(IoError::Invalid)? } else { let text = step_text(bytes); if is_iges_path(file) { solidcraft_kernel::iges_to_step(&text).map_err(IoError::Invalid)? } else { (text, Vec::new()) } }; // The limit of a file being imported is the limit of its format, not the design file's // (#2721): the restated text is checked against the import limit, and the design file // limit applies to the design that is saved, which refuses it there. design::check_step_importable(&text)?; let imp = solidcraft_kernel::step_import_shared(&text)?; let stem = std::path::Path::new(file) .file_stem() .map(|s| s.to_string_lossy().to_string()) .filter(|s| !s.trim().is_empty()) .unwrap_or_else(|| "Import".into()); let body_names: Vec = imp.bodies.iter().map(|b| body_name(b, names)).collect(); // A FreeCAD body's hidden intermediate shapes are not built (unless nothing else is). let hidden = native_cad::hidden_items(file, bytes, &text); let skip: Vec = imp.bodies.iter().zip(0u64..).filter(|(b, _)| hidden.contains(&b.source_item)).map(|(_, i)| i).collect(); let skip = if skip.len() == imp.bodies.len() { Vec::new() } else { skip }; // A body the STEP file itself marks invisible is still built, and starts hidden. let invisible: Vec = imp.bodies.iter().map(|b| b.hidden).collect(); // The root product's name; else the only body's name; else the file name. let name = match (imp.tree.as_slice(), body_names.as_slice()) { ([root], _) if !generic_name(&root.name) => root.name.clone(), (_, [only]) if !generic_name(only) => only.clone(), _ => stem, }; let file_name = std::path::Path::new(file).file_name().map(|s| s.to_string_lossy().to_string()).unwrap_or_else(|| file.to_string()); Ok(StepFeature { name, body_names, invisible, kind: solidcraft_doc::FeatureKind::Import { file: file_name, step: text.into(), components: imp.tree.clone(), skip, records: None }, warnings: iges_warnings.into_iter().chain(imp.warnings.iter().cloned()).collect(), import: imp, }) } /// What an OpenUSD file's import brings in. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub enum UsdGeometry { /// Its meshes, as mesh bodies ([`read_usd`]): how OpenUSD files have always been read, and /// what most of them hold. A B-rep with no mesh is left out. #[default] Meshes, /// Its exact geometry where it has it ([`usd_records`]): each B-rep (a `BrepArray`'s solids /// and shells) a B-rep body of an Import feature, and each mesh with /// no B-rep beside it a mesh body of that feature. Exact, } impl UsdGeometry { /// `meshes` or `exact` (any case); `None` for anything else. pub fn parse(s: &str) -> Option { match s.trim().to_ascii_lowercase().as_str() { "meshes" => Some(UsdGeometry::Meshes), "exact" => Some(UsdGeometry::Exact), _ => None, } } } /// An OpenUSD file (`file` is its name) read for its exact geometry ([`UsdGeometry::Exact`]) into /// an Import feature keeping records, as a FreeCAD or Rhino file read by cadmpeg is, with the /// bodies named after `names`; and whether the file says Y is up. pub fn usd_import_feature(bytes: &[u8], file: &str, names: StepNames) -> Result<(StepFeature, bool)> { let _span = solidcraft_profile::span("import", "usd_import_feature"); limits::check(limits::Kind::Step, bytes.len() as u64).map_err(IoError::Invalid)?; let (records, warnings, y_up) = usd_records(bytes, file).map_err(IoError::Invalid)?; Ok((records_import_feature((records, warnings, false), file, names)?, y_up)) } /// A file read with [`StepReader::Cadmpeg`] (FreeCAD, Rhino or STEP) into an Import feature that /// keeps the B-rep records cadmpeg's neutral model was read into (no STEP text). A FreeCAD body's /// hidden intermediate shapes (each pad and pocket, the tool shapes, sketch faces, which FreeCAD /// shows only through its body's own shape) are not built, unless nothing else is; a Rhino file's /// hidden objects are its user's own choice, so they are built and start hidden. The format is /// the one cadmpeg detects in the contents, not the file's name. fn records_import_feature(read: (solidcraft_kernel::ImportRecords, Vec, bool), file: &str, names: StepNames) -> Result { let (records, decode_warnings, freecad) = read; let text = solidcraft_kernel::records_text(&records)?; design::check_step_importable(&text)?; let imp = solidcraft_kernel::records_import_shared(&records)?; // Not one body made of the records: no feature, as a STEP file with no solids is refused. if imp.bodies.is_empty() { let why = imp.warnings.last().map(|w| format!(" ({w})")).unwrap_or_default(); return Err(IoError::Invalid(format!("{file}: no bodies could be made of this file{why}"))); } let stem = std::path::Path::new(file) .file_stem() .map(|s| s.to_string_lossy().to_string()) .filter(|s| !s.trim().is_empty()) .unwrap_or_else(|| "Import".into()); let body_names: Vec = imp.bodies.iter().map(|b| body_name(b, names)).collect(); let skip: Vec = if freecad { imp.bodies.iter().zip(0u64..).filter(|(b, _)| b.hidden).map(|(_, i)| i).collect() } else { Vec::new() }; let skip = if skip.len() == imp.bodies.len() { Vec::new() } else { skip }; let invisible: Vec = imp.bodies.iter().map(|b| b.hidden).collect(); // As a STEP import's: the root product's name; else the only body's name; else the file name. let name = match (imp.tree.as_slice(), body_names.as_slice()) { ([root], _) if !generic_name(&root.name) => root.name.clone(), (_, [only]) if !generic_name(only) => only.clone(), _ => stem, }; let file_name = std::path::Path::new(file).file_name().map(|s| s.to_string_lossy().to_string()).unwrap_or_else(|| file.to_string()); Ok(StepFeature { name, body_names, invisible, kind: solidcraft_doc::FeatureKind::Import { file: file_name, step: "".into(), components: imp.tree.clone(), skip, records: Some(std::sync::Arc::new(records)), }, warnings: decode_warnings.into_iter().chain(imp.warnings.iter().cloned()).collect(), import: imp, }) } /// Is this a mesh file we import (`.3mf`, `.stl`, `.obj`, `.glb`, `.gltf`, or OpenUSD's `.usd`, /// `.usda`, `.usdc` and `.usdz`, any case)? pub fn is_mesh_path(path: &str) -> bool { std::path::Path::new(path) .extension() .and_then(|e| e.to_str()) .is_some_and(|e| ["3mf", "stl", "obj", "glb", "gltf"].iter().any(|x| e.eq_ignore_ascii_case(x))) || is_usd_path(path) } /// A 3MF, STL, OBJ, glTF or OpenUSD file read as a mesh import feature. pub struct MeshFeature { /// Timeline name: the only mesh's name, else the file name. pub name: String, pub kind: solidcraft_doc::FeatureKind, pub body_names: Vec, pub warnings: Vec, } /// Read 3MF, STL, OBJ, PLY or glTF bytes (the format from `file`'s extension) into a MeshImport /// feature. A glTF file's bodies are all built where they are (see [`read_gltf`] for its node /// tree), and it can't read buffers in other files. pub fn mesh_import_feature(bytes: &[u8], file: &str) -> Result { mesh_import_feature_in(bytes, file, 1.0) } /// [`mesh_import_feature`] for a file whose coordinates are in a unit of `mm_per_unit` /// millimetres (25.4 for inches). The scaling is made once, as the file is read: the feature /// keeps the millimetre mesh and nothing of the unit. Only STL, OBJ and PLY files take a unit /// other than millimetres; a 3MF or glTF file says its own. pub fn mesh_import_feature_in(bytes: &[u8], file: &str, mm_per_unit: f64) -> Result { let _span = solidcraft_profile::span("import", "mesh_import_feature"); if !mm_per_unit.is_finite() || mm_per_unit <= 0.0 { return Err(IoError::Invalid("the unit must be a positive number of millimetres".into())); } let own_units = |what: &str| { if mm_per_unit == 1.0 { Ok(()) } else { Err(IoError::Invalid(format!("a {what} file states its own units; a unit applies to STL, OBJ and PLY files"))) } }; if is_gltf_path(file) { own_units("glTF")?; let mut no_files = |name: &str| Err(format!("`{name}` can't be read here")); let mut g = read_gltf(bytes, file, &mut no_files)?; g.flatten(); return Ok(g.feature); } if is_usd_path(file) { own_units("OpenUSD")?; let (mut g, _) = read_usd(bytes, file)?; g.flatten(); return Ok(g.feature); } // A mesh file is read up to the limit for STEP and import files, which Preferences raise // (#17446, #14548). limits::check(limits::Kind::Step, bytes.len() as u64).map_err(IoError::Invalid)?; let path = std::path::Path::new(file); let stem = path.file_stem().map(|s| s.to_string_lossy().to_string()).filter(|s| !s.trim().is_empty()).unwrap_or_else(|| "Mesh".into()); let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("").to_ascii_lowercase(); let (mut objects, warnings) = if ext == "obj" { obj::read_obj(bytes, &stem)? } else if ext == "ply" { ply::read_ply_mesh(bytes, &stem)? } else if ext == "stl" { let tris = read_stl(bytes)?; if tris.is_empty() { return Err(IoError::Invalid("STL has no triangles".into())); } let positions: Vec = tris.iter().flatten().map(|v| Vec3::new(v[0] as f64, v[1] as f64, v[2] as f64)).collect(); let n = u32::try_from(tris.len()).map_err(|_| IoError::Invalid("STL too large".into()))?; let triangles = (0..n).map(|i| [i * 3, i * 3 + 1, i * 3 + 2]).collect(); (vec![MeshObject { name: stem.clone(), positions, triangles, ..Default::default() }], Vec::new()) } else { own_units("3MF")?; read_3mf(bytes)? }; if mm_per_unit != 1.0 { let limit = solidcraft_doc::point_cloud::MAX_COORD; for o in &mut objects { for p in &mut o.positions { *p = *p * mm_per_unit; if ![p.x, p.y, p.z].iter().all(|v| v.is_finite() && v.abs() <= limit) { return Err(IoError::Invalid(format!("mesh `{}` is out of range at this unit", o.name))); } } } } // Check every mesh now, so the command fails rather than the timeline. let mut meshes = Vec::with_capacity(objects.len()); for o in &objects { solidcraft_kernel::mesh_body_with_normals(&o.positions, &o.triangles, &o.corner_normals) .map_err(|e| IoError::Invalid(format!("mesh `{}`: {e}", o.name)))?; meshes.push(solidcraft_doc::MeshData { name: o.name.clone(), positions: o.positions.iter().flat_map(|p| [p.x, p.y, p.z]).collect(), triangles: o.triangles.iter().flatten().copied().collect(), color: o.color, corner_normals: o.corner_normals.iter().flatten().flat_map(|n| [n.x, n.y, n.z]).collect(), }); } let name = match objects.as_slice() { [only] if !only.name.trim().is_empty() => only.name.clone(), _ => stem, }; let file_name = path.file_name().map(|s| s.to_string_lossy().to_string()).unwrap_or_else(|| file.to_string()); Ok(MeshFeature { name, body_names: objects.iter().map(|o| o.name.clone()).collect(), kind: solidcraft_doc::FeatureKind::MeshImport { file: file_name, meshes }, warnings, }) } /// Export formats. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Format { StlBinary, StlAscii, Obj, Step, Iges, ThreeMf, /// 3MF whose triangles carry their B-rep face, at full precision, for meshing and analysis /// tools (docs/formats/3mf-face-tags.md). Chosen by name only; a /// `.3mf` path alone means [`Format::ThreeMf`]. ThreeMfTagged, Design, /// A robot description of the assembly with its mesh files ([`urdf()`]); written by the /// engine, since it is several files. Urdf, /// Binary glTF with the bodies' looks ([`export_glb`]); written from the document, which /// holds the looks. Glb, /// A Gazebo model folder of the design ([`sdf_model`]): `model.config`, `model.sdf`, meshes /// and decal images; written by the engine, since it is several files. Sdf, /// OpenUSD: `.usda` text, `.usdc` (or `.usd`) binary, or a `.usdz` package, chosen by the /// file's extension ([`usd_from_design`]); written from the design, which holds the /// components and looks. Usd, /// Rhino `.3dm`, written by cadmpeg from the design ([`cadmpeg_export`]): each body's exact /// shape where cadmpeg's Rhino writer can write it, else its mesh. Rhino, /// FreeCAD `.FCStd`: named so that `file.export` can say why it is not written yet (cadmpeg /// cannot write a new FreeCAD file; [`cadmpeg_export`] refuses it). FreeCad, } impl Format { /// From a file name or extension (`part.stl`, `step`, `stp`…). pub fn from_name(name: &str) -> Result { let ext = name.rsplit('.').next().unwrap_or(name).to_ascii_lowercase(); Ok(match ext.as_str() { "stl" => Format::StlBinary, "stla" | "stl-ascii" => Format::StlAscii, "obj" => Format::Obj, "step" | "stp" => Format::Step, "igs" | "iges" => Format::Iges, "3mf" => Format::ThreeMf, "3mf-tagged" => Format::ThreeMfTagged, "urdf" => Format::Urdf, "glb" => Format::Glb, "sdf" => Format::Sdf, "usd" | "usda" | "usdc" | "usdz" => Format::Usd, "3dm" => Format::Rhino, "fcstd" => Format::FreeCad, e if e == "json" || is_design_ext(e) => Format::Design, _ => return Err(IoError::Format(ext)), }) } } /// How closely an exported mesh follows curved faces: its chord tolerance as a share of each /// body's size. Standard is what every mesh export used; Fine and Finest give the small round /// features of a large part more sides (#4747). #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub enum MeshQuality { #[default] Standard, Fine, Finest, } impl MeshQuality { /// By the name commands take: `standard`, `fine` or `finest`. pub fn from_name(name: &str) -> Option { match name.trim().to_ascii_lowercase().as_str() { "standard" => Some(Self::Standard), "fine" => Some(Self::Fine), "finest" => Some(Self::Finest), _ => None, } } /// The chord tolerance as a share of the body's size. fn share(self) -> f64 { match self { Self::Standard => 2e-4, Self::Fine => 5e-5, Self::Finest => 1e-5, } } /// The chord tolerance for a body of size `size` (its box diagonal): [`MeshQuality::share`] /// of it, never finer than 1 µm. fn chord(self, size: f64) -> f64 { (size * self.share()).max(1e-3) } /// The mesh path's spec for a body of size `size`: this quality's chord /// ([`MeshQuality::chord`]), no size asked (the mesh path's default, a fifth of the body's /// extent, less where a face's curvature asks for less) and the default smallest angle /// ([`solidcraft_kernel::MESH_MIN_ANGLE`]). pub fn spec(self, size: f64) -> solidcraft_kernel::MeshSpec { solidcraft_kernel::MeshSpec::chord(self.chord(size)) } } /// The export mesh of a body at standard quality ([`export_mesh_at`]). pub fn export_mesh(b: &solidcraft_kernel::Body) -> Result { export_mesh_at(b, MeshQuality::Standard) } /// The export mesh of a body at `quality` ([`export_mesh_noted`]), its notes logged as warnings. /// The exports themselves take [`export_mesh_noted`] and report the notes. pub fn export_mesh_at(b: &solidcraft_kernel::Body, quality: MeshQuality) -> Result { let (mesh, notes) = export_mesh_noted(b, quality)?; for n in notes { log::warn!("export mesh: {n}"); } Ok(mesh) } /// The export mesh of a body at `quality`: the mesh path ([`solidcraft_kernel::Body::export_mesh`], /// to [`MeshQuality::spec`]), never the display's. Strict: a face it cannot mesh fails the /// export, naming the face. With it, a note for each face left short of the smallest angle or /// the chord tolerance (and each edge whose sampling stopped off it), for the export's warnings. pub fn export_mesh_noted(b: &solidcraft_kernel::Body, quality: MeshQuality) -> Result<(Mesh, Vec)> { export_mesh_sized(b, b.size(), quality) } /// [`export_mesh_noted`] with the chord taken from `size` rather than the body's own: placements /// of one part ([`shared_placements`]) all take their first placement's, so they ask for the one /// mesh (a rotated copy's box, and so its own size, is not the part's). fn export_mesh_sized(b: &solidcraft_kernel::Body, size: f64, quality: MeshQuality) -> Result<(Mesh, Vec)> { let spec = quality.spec(size); let (mesh, stats) = b.export_mesh(&spec)?; Ok((mesh, mesh_notes(&stats, &spec))) } /// A line for each face the mesh path left short of its shape or its tolerance, and each edge /// whose sampling stopped off its chord tolerance: what an export reports as warnings, so a /// mesh that falls short of its spec is never written silently. `spec` is the spec it was /// meshed to. fn mesh_notes(stats: &solidcraft_kernel::PlanStats, spec: &solidcraft_kernel::MeshSpec) -> Vec { let mut notes = Vec::new(); for u in &stats.unshaped { let limits = if u.limits.is_empty() { String::from("nothing stopped it") } else { u.limits.iter().map(|l| format!("{l:?}")).collect::>().join(", ") }; // A bound can stop the shaping (too many points, a side kept whole) after every // triangle already keeps the angle: that face is not short of it. notes.push(if u.smallest_angle < spec.min_angle { format!("face {}: smallest angle {:.2}°, short of the {}° asked (stopped by: {limits})", u.face, u.smallest_angle, spec.min_angle) } else { format!( "face {}: its shaping stopped at a bound ({limits}) with the {}° asked reached (smallest angle {:.2}°)", u.face, spec.min_angle, u.smallest_angle ) }); } for o in &stats.over_tolerance { let reason = if o.caps.is_empty() { String::from("its shared boundary was kept") } else { let caps = o.caps.iter().map(|c| format!("{c:?}")).collect::>().join(", "); format!("its refinement stopped at a bound ({caps})") }; let how = if o.within { "still within it" } else if o.sag > o.tol { "past it" } else { "within it where measured" }; notes.push(format!( "face {}: {reason}. Its triangles lie up to {:.3e} mm off the surface, {how} (chord tolerance {:.3e} mm{})", o.face, o.sag, o.tol, if o.unmeasured > 0 { format!(", {} middles unmeasured", o.unmeasured) } else { String::new() } )); } for e in stats.edges_capped.iter().filter(|e| !e.within) { notes.push(format!( "edge {}: its sampling stopped at a bound ({:?}); its chords lie up to {:.3e} mm off the curve, past the {:.3e} mm chord tolerance", e.edge, e.cap, e.sag, e.tol )); } notes } /// The display mesh of a body at `quality`'s chord ([`solidcraft_kernel::Body::mesh`]): for the /// GLB export, a format for viewing, and the mass properties. pub(crate) fn display_mesh_at(b: &solidcraft_kernel::Body, quality: MeshQuality) -> Result { Ok(b.mesh(&solidcraft_kernel::MeshTolerance::chord(quality.chord(b.size())))?) } /// Distance within which an exported mesh's vertices are welded (STL, 3MF and OBJ alike). fn weld_eps(b: &solidcraft_kernel::Body) -> f64 { weld_distance(b.size()) } /// [`weld_eps`] for a body of characteristic size (bounding box diagonal) `size`. fn weld_distance(size: f64) -> f64 { (size * 1e-6).max(1e-7) } /// Unit-density [`MassProperties`] of a body from its welded display mesh at standard quality, /// the mesh URDF links take their inertia from; `None` when that mesh does not close (an open /// surface). pub fn mass_properties(b: &solidcraft_kernel::Body) -> Result> { let m = display_mesh_at(b, MeshQuality::Standard)?; let (positions, triangles) = weld(&m.positions, &m.triangles, weld_eps(b)); Ok(Mesh { positions, triangles, ..Mesh::default() }.mass_properties()) } /// Binary STL of several meshes (one solid). pub fn stl_binary(meshes: &[Mesh], name: &str) -> Vec { let n: usize = meshes.iter().map(|m| m.triangles.len()).sum(); let mut out = Vec::with_capacity(84 + n * 50); let mut header = format!("SolidCraft STL {name}").into_bytes(); header.resize(80, b' '); out.extend_from_slice(&header); out.extend_from_slice(&u32::try_from(n).unwrap_or(u32::MAX).to_le_bytes()); for m in meshes { for t in &m.triangles { let Some([a, b, c]) = m.tri(t) else { continue }; let nrm = (b - a).cross(c - a).normalized().unwrap_or_default(); for v in [nrm, a, b, c] { for x in v.to_f32() { out.extend_from_slice(&x.to_le_bytes()); } } out.extend_from_slice(&[0, 0]); } } out } /// ASCII STL. pub fn stl_ascii(meshes: &[Mesh], name: &str) -> String { use std::fmt::Write as _; let name: String = name.chars().filter(|c| c.is_ascii_graphic()).collect(); let mut s = format!("solid {name}\n"); for m in meshes { for t in &m.triangles { let Some([a, b, c]) = m.tri(t) else { continue }; let n = (b - a).cross(c - a).normalized().unwrap_or_default(); // Written into the text rather than formatted apart and appended: the same bytes, // without a string made and dropped per line. let _ = write!(s, " facet normal {:e} {:e} {:e}\n outer loop\n", n.x, n.y, n.z); for v in [a, b, c] { let _ = writeln!(s, " vertex {:e} {:e} {:e}", v.x, v.y, v.z); } s += " endloop\n endfacet\n"; } } s += &format!("endsolid {name}\n"); s } /// A body in an OBJ export: the name it is written with, its mesh and the colour it is shown /// in. pub struct ObjBody<'a> { /// The body's name, written in the `o` line. pub name: &'a str, /// The body's mesh. pub mesh: &'a Mesh, /// The colour of the body, when the design gives it one. The colours of its faces and its /// transparency are not carried. pub color: Option<[f32; 3]>, } /// The files of an OBJ export: the mesh file and the material library that goes with it. pub struct ObjFiles { /// The mesh file. pub obj: String, /// The material library; empty when no body has a colour. pub mtl: String, /// [`export_obj`] only: what meshing the bodies reported ([`export_mesh_noted`]), each line /// led by its body's name. pub warnings: Vec, } /// Wavefront OBJ, one object per body, without materials. pub fn obj(meshes: &[(String, Mesh)]) -> String { let bodies: Vec> = meshes.iter().map(|(name, mesh)| ObjBody { name: name.as_str(), mesh, color: None }).collect(); obj_files(&bodies, "").obj } /// Wavefront OBJ with the colours of the bodies: the mesh file and the material library that /// goes with it. `mtl_name` is the name the `mtllib` line writes (the library's file name /// beside the mesh file); an empty name writes no materials at all, as there is no library to /// name. /// /// Only the colour of the body travels: the colours of single faces and the transparency of a /// body are left out, as a face colour needs material groups inside one object. /// /// Positions and normals are each written once per distinct value, so a face's vertices are /// shared while the normals keep edges between faces sharp. Names are written as they are (OBJ /// takes the rest of the line); the material of a body takes its name with the characters a /// material name cannot hold replaced by an underscore. pub fn obj_files(bodies: &[ObjBody<'_>], mtl_name: &str) -> ObjFiles { let materials = material_names(bodies); let mut obj = String::from("# SolidCraft OBJ export (mm)\n"); let mut mtl = String::new(); if materials.iter().any(|m| m.is_some()) { obj += &format!("mtllib {mtl_name}\n"); mtl = String::from("# SolidCraft material library\n"); } let (mut vbase, mut nbase) = (1usize, 1usize); for (i, b) in bodies.iter().enumerate() { let name: String = b.name.chars().map(|c| if c.is_control() { ' ' } else { c }).collect(); obj += &format!("o {name}\n"); if let (Some(material), Some(color)) = (materials.get(i).and_then(|m| m.as_deref()), b.color) { obj += &format!("usemtl {material}\n"); mtl += &format!("newmtl {material}\nKd {}\n", kd(color)); } let (text, vb, nb) = mesh_text(b.mesh, vbase, nbase); obj += &text; vbase = vb; nbase = nb; } ObjFiles { obj, mtl, warnings: Vec::new() } } /// The mesh of a body, welded as STL and 3MF are ([`weld`]: vertices closer than /// [`weld_distance`] merged, and sides split where another face's vertex lies on them), so /// neighbouring faces share their edge points and the file opens again as a closed solid /// (#9074). Each corner keeps the normal it had ([`corner_normals`]), so edges between faces /// stay sharp. Vertices and normals are each written once per distinct value. Returns the text /// and the bases the next body carries on from. fn mesh_text(mesh: &Mesh, vbase: usize, nbase: usize) -> (String, usize, usize) { use std::collections::HashMap; use std::fmt::Write as _; let mut bounds = solidcraft_geom::Aabb3::EMPTY; for p in &mesh.positions { bounds.add(*p); } let eps = weld_distance(bounds.diagonal()); // Each welded triangle is tagged with the triangle it came from, for its normals. let source: Vec = (0..mesh.triangles.len()).map(|k| u32::try_from(k).unwrap_or(u32::MAX)).collect(); let (positions, triangles, from) = threemf::weld_tagged(&mesh.positions, &mesh.triangles, &source, eps); let mut s = String::new(); for p in &positions { let _ = writeln!(s, "v {} {} {}", p.x, p.y, p.z); } // `+ 0.0` turns -0 into 0, so both merge. let key = |n: Vec3| [n.x + 0.0, n.y + 0.0, n.z + 0.0].map(f64::to_bits); let mut nmap: HashMap<[u64; 3], usize> = HashMap::new(); let mut faces = String::new(); for (t, k) in triangles.iter().zip(&from) { let (a, b, c) = (t[0] as usize + vbase, t[1] as usize + vbase, t[2] as usize + vbase); let at = t.map(|i| positions.get(i as usize).copied()); let normals = match (mesh.triangles.get(*k as usize), at) { (Some(o), [Some(pa), Some(pb), Some(pc)]) => corner_normals(mesh, *o, [pa, pb, pc], eps), _ => None, }; let Some(normals) = normals else { let _ = writeln!(faces, "f {a} {b} {c}"); continue; }; let [na, nb, nc] = normals.map(|n| { let next = nmap.len(); nbase + *nmap.entry(key(n)).or_insert_with(|| { let _ = writeln!(s, "vn {} {} {}", n.x, n.y, n.z); next }) }); let _ = writeln!(faces, "f {a}//{na} {b}//{nb} {c}//{nc}"); } s += &faces; (s, vbase + positions.len(), nbase + nmap.len()) } /// The normals at the corners `at` of a welded piece of triangle `t` of `mesh` (the whole /// triangle, or a piece of it split where another face's vertex lies on a side): a corner /// within `eps` of one of `t`'s own corners takes that corner's normal; a point a side was split /// at takes the normal between the side's ends. `None` when the mesh has no normals there. fn corner_normals(mesh: &Mesh, t: [u32; 3], at: [Vec3; 3], eps: f64) -> Option<[Vec3; 3]> { let p = t.map(|i| mesh.positions.get(i as usize).copied()); let n = t.map(|i| mesh.normals.get(i as usize).copied()); let ([Some(p0), Some(p1), Some(p2)], [Some(n0), Some(n1), Some(n2)]) = (p, n) else { return None }; let (p, n) = ([p0, p1, p2], [n0, n1, n2]); Some(at.map(|q| p.iter().zip(n).find(|(c, _)| c.dist(q) <= eps).map_or_else(|| normal_at(p, n, q), |(_, n)| n))) } /// The normal at `q` on the triangle with corners `p` and corner normals `n`: the corners' /// normals weighted by where `q` lies (barycentric), of unit length. The first corner's when /// the triangle has no area. fn normal_at(p: [Vec3; 3], n: [Vec3; 3], q: Vec3) -> Vec3 { let [p0, p1, p2] = p; let [n0, n1, n2] = n; let (e1, e2, d) = (p1 - p0, p2 - p0, q - p0); let (d11, d12, d22, d1, d2) = (e1.dot(e1), e1.dot(e2), e2.dot(e2), d.dot(e1), d.dot(e2)); let den = d11 * d22 - d12 * d12; if !(den.abs() > 0.0) { return n0; } let (v, w) = ((d22 * d1 - d12 * d2) / den, (d11 * d2 - d12 * d1) / den); (n0 * (1.0 - v - w) + n1 * v + n2 * w).normalized().unwrap_or(n0) } /// The material of each body: its name, safe to write in a material library and unique among /// the bodies. A body without a colour has no material. fn material_names(bodies: &[ObjBody<'_>]) -> Vec> { let mut taken: std::collections::HashSet = std::collections::HashSet::new(); let mut out: Vec> = Vec::with_capacity(bodies.len()); for b in bodies { if b.color.is_none() { out.push(None); continue; } let base = safe_name(b.name); let base = if base.is_empty() { String::from("body") } else { base }; let mut name = base.clone(); let mut n = 2; while !taken.insert(name.clone()) { name = format!("{base}_{n}"); n += 1; } out.push(Some(name)); } out } /// A name a material library can hold: the body's name with every character that is not a /// letter, a digit or an underscore replaced by one, and the name cut short when it is longer /// than a material name needs to be. fn safe_name(name: &str) -> String { name.chars().map(|c| if c.is_ascii_alphanumeric() || c == '_' { c } else { '_' }).take(64).collect() } /// The diffuse colour of a material: three fractions between 0 and 1, as the OBJ convention /// writes them. fn kd(color: [f32; 3]) -> String { let [r, g, b] = color.map(|v| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 }); format!("{r:.3} {g:.3} {b:.3}") } /// The bodies of a model an export takes (all when `bodies` is empty). fn selected<'a>(state: &'a ModelState, bodies: &[String]) -> Result> { let sel: Vec<&solidcraft_doc::ModelBody> = state.bodies.iter().filter(|b| bodies.is_empty() || bodies.contains(&b.name)).collect(); if sel.is_empty() { return Err(IoError::Empty); } Ok(sel) } /// The OBJ export of the given bodies of a model (all when `bodies` is empty): the mesh file /// and the material library beside it, with the colour of each body. `mtl_name` is the name /// the `mtllib` line writes (the library's file name beside the mesh file). pub fn export_obj(state: &ModelState, bodies: &[String], mtl_name: &str, quality: MeshQuality) -> Result { obj_export(&selected(state, bodies)?, mtl_name, quality) } /// The OBJ export of the given bodies: the mesh file and the material library beside it. fn obj_export(sel: &[&solidcraft_doc::ModelBody], mtl_name: &str, quality: MeshQuality) -> Result { let (items, warnings) = per_placed_body(sel, |b, body| body_mesh(b, body, quality))?; let bodies: Vec> = items.iter().map(|(b, mesh)| ObjBody { name: b.name.as_str(), mesh, color: b.body.color() }).collect(); Ok(ObjFiles { warnings, ..obj_files(&bodies, mtl_name) }) } /// A body's export mesh as [`shared_placements`] gives it: its part's mesh placed /// ([`PartMesh::placed`]) for a placement of a part, else its own ([`export_mesh_sized`]), its /// chord from `size`, with its notes, each led by the body's name. A mesh it cannot make is an /// error led by the body's name too, so an export of several bodies says whose face it is. fn body_mesh(b: &solidcraft_doc::ModelBody, (body, size, part): &Placed, quality: MeshQuality) -> Result<(Mesh, Vec)> { let named = |e: IoError| match e { IoError::Kernel(k) => IoError::Invalid(format!("{}: {k}", b.name)), other => other, }; let placed = match part { Some((part, rel)) => part.placed(&quality.spec(*size), rel).map_err(named)?, None => None, }; let (mesh, notes) = match placed { Some(placed) => placed, None => export_mesh_sized(body, *size, quality).map_err(named)?, }; Ok((mesh, notes.into_iter().map(|n| format!("{}: {n}", b.name)).collect())) } /// A body of an export as it is meshed ([`shared_placements`]): the body, the size its chord is /// taken from, and for a placement of a part, the part's meshes and the placement relative to /// the part's first. type Placed = (solidcraft_kernel::Body, f64, Option<(std::sync::Arc, solidcraft_doc::Mat)>); /// A part's export meshes (its first placement's body), made once for all its placements, by /// spec: asked again, the same mesh without meshing again. The lock is held while meshing, so /// placements asking for the mesh wait for that one mesh rather than make it too. struct PartMesh { original: solidcraft_kernel::Body, made: std::sync::Mutex, u64), std::sync::Arc<(Mesh, solidcraft_kernel::PlanStats)>)>>, } /// Meshes a [`PartMesh`] keeps at most (the oldest goes first). const PART_MESHES: usize = 4; impl PartMesh { fn new(original: solidcraft_kernel::Body) -> Self { PartMesh { original, made: std::sync::Mutex::new(Vec::new()) } } /// The part's mesh to `spec` ([`solidcraft_kernel::Body::export_mesh`]), made now or kept. fn mesh(&self, spec: &solidcraft_kernel::MeshSpec) -> Result> { let make = || self.original.export_mesh(spec).map(std::sync::Arc::new); let Ok(mut made) = self.made.lock() else { return Ok(make()?) }; let key = (spec.chord.to_bits(), spec.size.map(f64::to_bits), spec.min_angle.to_bits()); if let Some((_, m)) = made.iter().find(|(k, _)| *k == key) { return Ok(m.clone()); } let m = make()?; if made.len() >= PART_MESHES { made.remove(0); } made.push((key, m.clone())); Ok(m) } /// The part's mesh to `spec`, moved by `rel` ([`solidcraft_kernel::placed_mesh`]), with its /// notes; `None` when `rel` is no rotation and translation (the placement is meshed on its own). fn placed(&self, spec: &solidcraft_kernel::MeshSpec, rel: &solidcraft_doc::Mat) -> Result)>> { let made = self.mesh(spec)?; Ok(solidcraft_kernel::placed_mesh(&made.0, rel).map(|m| (m, mesh_notes(&made.1, spec)))) } } /// The bodies of an export as they are meshed, each with the size its chord is taken from. Each /// placement of a component's body (a world state's computed placement) shows the mesh of the /// first placement of that body in `sel`, placed ([`PartMesh`], the first placement through it /// too), and takes that placement's size: every placement of one /// part asks for one spec, so the part is meshed once and its copies are those triangles, moved. /// The mesh path is not the same under a move to the bit: a copy's record is the part's moved, /// rounded (a rational form's weighted points round as they move), and its shaping can take /// other points for so small a difference; nor is a copy's own size its part's (a rotated box is /// another box). The share's lock is held while its part is meshed, so the copies wait for that /// one mesh rather than make it again; other parts are meshed on other threads meanwhile. Any /// other body is meshed as it is at its own size, and so is a placement that is not its first /// placement moved ([`placed_vertices_match`]). fn shared_placements(sel: &[&solidcraft_doc::ModelBody]) -> Vec { type Leader = (std::sync::Arc, solidcraft_doc::Mat, f64); let mut leaders: std::collections::BTreeMap<(String, u64), Leader> = std::collections::BTreeMap::new(); sel.iter() .map(|b| { let own = (b.body.clone(), b.body.size(), None); let (Some(name), key) = (b.source_name.as_ref(), b.source_key()) else { return own }; if key == 0 || b.body.is_mesh() || b.body.record().vertices.is_empty() { return own; } match leaders.get(&(name.clone(), key)) { None => { let share = std::sync::Arc::new(PartMesh::new(b.body.clone())); let size = b.body.size(); leaders.insert((name.clone(), key), (share.clone(), b.source_transform, size)); (b.body.clone(), size, Some((share, solidcraft_doc::IDENTITY))) } Some((share, first, size)) => { let Some(rel) = solidcraft_doc::mat_inverse(first).map(|inv| solidcraft_doc::mat_mul(&b.source_transform, &inv)) else { return own; }; if !placed_vertices_match(&share.original, &b.body, &rel) { return own; } (b.body.clone(), *size, Some((share.clone(), rel))) } } }) .collect() } /// `copy` is `original` moved by `m`: as many faces, edges and vertices, at least one vertex /// (so the comparison says something), each of `copy`'s vertices `original`'s moved, in the /// same order, within the export's weld distance ([`weld_distance`]), and so their boxes too. fn placed_vertices_match(original: &solidcraft_kernel::Body, copy: &solidcraft_kernel::Body, m: &solidcraft_doc::Mat) -> bool { let (a, b) = (original.record(), copy.record()); let eps = weld_distance(copy.size()); let at = |q: &solidcore_record::brep::Vertex| Vec3::new(q.point[0], q.point[1], q.point[2]); let moved: Vec = a.vertices.iter().map(|p| solidcraft_doc::apply_point(m, at(p))).collect(); let boxed = |ps: &mut dyn Iterator| { ps.fold(solidcraft_geom::Aabb3::EMPTY, |mut x, p| { x.add(p); x }) }; let (ba, bb) = (boxed(&mut moved.iter().copied()), boxed(&mut b.vertices.iter().map(at))); !b.vertices.is_empty() && a.faces.len() == b.faces.len() && a.edges.len() == b.edges.len() && a.vertices.len() == b.vertices.len() && moved.iter().zip(&b.vertices).all(|(p, q)| p.dist(at(q)) <= eps) && ba.min.dist(bb.min) <= eps && ba.max.dist(bb.max) <= eps } /// `f` for each body of an export and the body it is meshed as ([`shared_placements`]), on /// threads (a body at a time each), the results in the order of the bodies. The bodies are /// Mesh each placed body on threads. If a body fails to mesh (e.g. an untessellatable sliver face), /// but other bodies in the export succeed, the failing body is skipped with a warning note so the /// rest of the assembly can still be exported (#18780). If all bodies fail (or only one body was /// selected and failed), the first error is returned. fn per_placed_body<'a, R: Send>( sel: &[&'a solidcraft_doc::ModelBody], f: impl Fn(&solidcraft_doc::ModelBody, &Placed) -> Result<(R, Vec)> + Sync, ) -> Result<(Vec<(&'a solidcraft_doc::ModelBody, R)>, Vec)> { let meshed = shared_placements(sel); let pairs: Vec<(&solidcraft_doc::ModelBody, &Placed)> = sel.iter().copied().zip(&meshed).collect(); let thread_results = solidcraft_kernel::map_on_threads(&pairs, EXPORT_THREADS, |(b, body)| f(b, body)); let mut successful = Vec::new(); let mut notes = Vec::new(); let mut first_err = None; for (r, b) in thread_results.into_iter().zip(sel) { match r { Some(Ok((val, item_notes))) => { successful.push((*b, val)); notes.extend(item_notes); } Some(Err(e)) => { notes.push(format!("{}: skipped: meshing failed ({e})", b.name)); if first_err.is_none() { first_err = Some(e); } } None => { let e = IoError::Invalid(format!("body {}: meshing it failed", b.name)); notes.push(format!("{}: skipped: meshing failed ({e})", b.name)); if first_err.is_none() { first_err = Some(e); } } } } if successful.is_empty() { return Err(first_err.unwrap_or(IoError::Empty)); } Ok((successful, notes)) } #[allow(dead_code)] /// Results with their notes, as the results and every note in the results' order. fn noted(results: Vec<(R, Vec)>) -> (Vec, Vec) { let mut notes = Vec::new(); let out = results .into_iter() .map(|(r, n)| { notes.extend(n); r }) .collect(); (out, notes) } /// Export the given bodies of a model (all when `bodies` is empty) in a format. pub fn export(state: &ModelState, bodies: &[String], format: Format, name: &str) -> Result> { export_with_metadata(state, bodies, format, name, &Metadata::default()) } /// The STEP or IGES header of an export named `file_name`: the design's author, organization /// and description (#1015). fn step_header(file_name: String, meta: &Metadata) -> solidcraft_kernel::StepHeader { solidcraft_kernel::StepHeader { file_name, author: header_line(meta.author()), organization: header_line(meta.organization()), description: header_line(meta.description()), ..Default::default() } } /// A header field is one line: each run of white space (line breaks too) becomes one space. fn header_line(text: Option<&str>) -> String { text.map(|t| t.split_whitespace().collect::>().join(" ")).unwrap_or_default() } /// 3MF model metadata from the design properties, by the names the 3MF core specification /// gives them. Other tools' keys are never exported. fn threemf_metadata(meta: &Metadata) -> Vec<(&'static str, &str)> { [("Title", meta.project()), ("Designer", meta.author()), ("Description", meta.description()), ("LicenseTerms", meta.license())] .into_iter() .filter_map(|(name, text)| Some((name, text?))) .collect() } /// [`export`], with the design properties `meta` in the formats that have a place for them: /// STEP and IGES headers (author, organization; STEP also the description) and 3MF model /// metadata (project as the title, author as the designer, description, licence). pub fn export_with_metadata(state: &ModelState, bodies: &[String], format: Format, name: &str, meta: &Metadata) -> Result> { export_with_quality(state, bodies, format, name, meta, MeshQuality::Standard) } /// [`export_with_metadata`], meshing STL, OBJ and 3MF at `quality`. /// /// The OBJ export of this function carries no materials: it writes one file, so it names no /// material library it could not write. [`export_obj`] returns the mesh file and the material /// library with the colours of the bodies. pub fn export_with_quality( state: &ModelState, bodies: &[String], format: Format, name: &str, meta: &Metadata, quality: MeshQuality, ) -> Result> { let _span = solidcraft_profile::span("io", "export_with_quality"); export_with_parts(state, bodies, &[], format, name, meta, quality, None) } /// [`export_with_quality`], and in 3MF each of `parts` (a name and the names of its bodies) /// written as one object with those bodies as its parts ([`model_xml_parts`], #8139). /// Bodies of a part that are not exported are left out of it. Other formats have no parts. /// A 3MF carries `thumbnail` (a PNG) as its package thumbnail; other formats have no place for it. /// /// What meshing the bodies reported ([`export_mesh_noted`]) is logged as warnings; /// [`export_with_parts_noted`] returns it for the export's reply. #[allow(clippy::too_many_arguments)] pub fn export_with_parts( state: &ModelState, bodies: &[String], parts: &[(String, Vec)], format: Format, name: &str, meta: &Metadata, quality: MeshQuality, thumbnail: Option<&[u8]>, ) -> Result> { let (bytes, notes) = export_with_parts_noted(state, bodies, parts, format, name, meta, quality, thumbnail)?; for n in notes { log::warn!("export mesh: {n}"); } Ok(bytes) } /// [`export_with_parts`], with what meshing the bodies reported (STL, OBJ and 3MF: each face /// the mesh path left short of the smallest angle or the chord tolerance, led by its body's /// name), for the export's warnings. #[allow(clippy::too_many_arguments)] pub fn export_with_parts_noted( state: &ModelState, bodies: &[String], parts: &[(String, Vec)], format: Format, name: &str, meta: &Metadata, quality: MeshQuality, thumbnail: Option<&[u8]>, ) -> Result<(Vec, Vec)> { let sel = selected(state, bodies)?; let (bytes, notes) = match format { Format::StlBinary | Format::StlAscii => { // Each body welded on its own (as for 3MF), so shared vertices are written identically // and the file is closed where faces meet. let (items, notes) = per_placed_body(&sel, |b, body| { let (m, n) = body_mesh(b, body, quality)?; let (positions, triangles) = weld(&m.positions, &m.triangles, weld_eps(&b.body)); Ok((Mesh { positions, triangles, ..Mesh::default() }, n)) })?; let meshes: Vec = items.into_iter().map(|(_, m)| m).collect(); let bytes = if format == Format::StlBinary { stl_binary(&meshes, name) } else { stl_ascii(&meshes, name).into_bytes() }; (bytes, notes) } Format::Obj => { // One file, so no material library: a mesh file that names a library nobody wrote // would come out in the reader's default grey. let (items, notes) = per_placed_body(&sel, |b, body| body_mesh(b, body, quality))?; let meshes: Vec<(String, Mesh)> = items.into_iter().map(|(b, m)| (b.name.clone(), m)).collect(); (obj(&meshes).into_bytes(), notes) } Format::Step => { let bs: Vec = sel.iter().map(|b| solidcraft_kernel::ExportBody { name: b.name.clone(), body: &b.body, color: b.body.color() }).collect(); (solidcraft_kernel::step_export_bodies(&bs, &step_header(format!("{name}.step"), meta))?.into_bytes(), Vec::new()) } Format::Iges => { let bs: Vec = sel.iter().map(|b| solidcraft_kernel::ExportBody { name: b.name.clone(), body: &b.body, color: b.body.color() }).collect(); (solidcraft_kernel::iges_export_bodies(&bs, &step_header(format!("{name}.igs"), meta))?.into_bytes(), Vec::new()) } Format::ThreeMf | Format::ThreeMfTagged => { let (items, notes) = per_placed_body(&sel, |b, body| mesh_object(b, body, format == Format::ThreeMfTagged, quality))?; let (kept_bodies, objs): (Vec<_>, Vec<_>) = items.into_iter().unzip(); let index = |n: &String| kept_bodies.iter().position(|b| &b.name == n); let parts: Vec<(String, Vec)> = parts.iter().map(|(p, names)| (p.clone(), names.iter().filter_map(index).collect())).collect(); let bytes = write_3mf_parts(&objs, &parts, &threemf_metadata(meta), thumbnail)?; (bytes, notes) } Format::Design => return Err(IoError::Format("sc (save the document instead)".into())), Format::Urdf => return Err(IoError::Format("urdf (an assembly package; use file.export)".into())), Format::Glb => return Err(IoError::Format("glb (its looks come from the design; use file.export)".into())), Format::Sdf => return Err(IoError::Format("sdf (a model folder; use file.export)".into())), Format::Usd => return Err(IoError::Format("usd (the file's extension picks its encoding; use file.export)".into())), Format::Rhino => return Err(IoError::Format("3dm (written from the design by cadmpeg; use file.export)".into())), Format::FreeCad => return Err(IoError::Invalid(native_cad::FREECAD_REFUSED.into())), }; Ok((bytes, notes)) } /// Most threads an export meshes its bodies on, as many as the model cache encodes them on. const EXPORT_THREADS: usize = 16; /// A body as a 3MF mesh: welded watertight (T-junctions split), coloured, and with `tagged` /// each triangle keeps the B-rep face it came from. fn mesh_object(b: &solidcraft_doc::ModelBody, body: &Placed, tagged: bool, quality: MeshQuality) -> Result<(MeshObject, Vec)> { let (m, notes) = body_mesh(b, body, quality)?; let eps = weld_eps(&b.body); // Faces with colours of their own tag their triangles. let paint = b.body.paint(); let mut looks = Vec::new(); let mut by_face = std::collections::HashMap::new(); for f in paint.map(|p| p.faces.as_slice()).unwrap_or_default() { looks.push((f.color, 1.0 - f.opacity)); by_face.insert(f.face, looks.len() as u32); } // Weld with each triangle's own index as its tag: the pieces of a split triangle keep it, // and its colour and face follow from it. let n = u32::try_from(m.triangles.len()).map_err(|_| IoError::Invalid("mesh too large".into()))?; let (positions, triangles, origin) = threemf::weld_tagged(&m.positions, &m.triangles, &(0..n).collect::>(), eps); let face_of = |t: &u32| m.tri_face.get(*t as usize).copied().unwrap_or(0); let tri_looks = if looks.is_empty() { Vec::new() } else { origin.iter().map(|t| by_face.get(&(face_of(t) as usize)).copied().unwrap_or(0)).collect() }; let (tri_faces, faces) = if tagged { let tri_faces: Vec = origin.iter().map(face_of).collect(); let most = tri_faces.iter().max().map_or(0, |f| f.saturating_add(1)); let faces = u32::try_from(b.body.face_count()).unwrap_or(u32::MAX).max(most); (tri_faces, faces) } else { (Vec::new(), 0) }; let transparency = 1.0 - paint.map(|p| p.opacity).unwrap_or(1.0); let object = MeshObject { name: b.name.clone(), positions, triangles, color: b.body.color(), transparency, looks, tri_looks, tri_faces, faces, corner_normals: Vec::new(), }; Ok((object, notes)) } /// STEP assembly of a design with components: a product per component holding its bodies in /// the component's own frame (`local` is the model before placing occurrences), and an /// assembly occurrence per component occurrence. A body with an offset (an imported assembly's /// part, built where the file placed it) is taken into its component's frame by that offset, /// as the world placement does, so the occurrences above it place it only once. pub fn step_assembly(doc: &Document, local: &ModelState, name: &str) -> Result> { let _span = solidcraft_profile::span("io", "step_assembly"); use solidcraft_kernel::{ExportBody, ExportProduct}; let mut index: std::collections::HashMap = std::collections::HashMap::new(); index.insert(0, 0); let mut products = vec![ExportProduct { name: doc.name.clone(), bodies: Vec::new(), children: Vec::new() }]; for c in &doc.components { index.insert(c.id, products.len()); products.push(ExportProduct { name: c.name.clone(), bodies: Vec::new(), children: Vec::new() }); } let framed: Vec> = local .bodies .iter() .map(|b| match doc.model_body_offset(b) { Some(offset) if !solidcraft_doc::is_identity(offset) => solidcraft_kernel::transform_matrix(&b.body, *offset).map(Some), _ => Ok(None), }) .collect::>()?; for (b, framed) in local.bodies.iter().zip(&framed) { let comp = doc.model_body_component(b); let Some(p) = index.get(&comp).and_then(|i| products.get_mut(*i)) else { continue }; p.bodies.push(ExportBody { name: b.name.clone(), body: framed.as_ref().unwrap_or(&b.body), color: b.body.color() }); } for o in &doc.occurrences { let (Some(&parent), Some(&child)) = (index.get(&o.parent), index.get(&o.component)) else { continue }; if let Some(p) = products.get_mut(parent) { p.children.push((child, o.transform, o.name.clone())); } } Ok(solidcraft_kernel::step_export_products(&products, 0, &step_header(format!("{name}.step"), &doc.metadata))?.into_bytes()) } /// Read a design file's bytes. pub fn read_design(bytes: &[u8]) -> Result { let _span = solidcraft_profile::span("io", "read_design"); limits::check(limits::Kind::Design, bytes.len() as u64).map_err(|e| IoError::Invalid(format!("design {e}")))?; if is_design_container(bytes) { return design::read(bytes); } // Every DWG starts with its version (`AC1032`), whatever the file is called (#9328). if bytes.starts_with(b"AC1") { return Err(IoError::Invalid( "this is a DWG file, which SolidCraft can't read: export the model as STEP and open that, or the drawing as DXF and use Insert DXF in a sketch".into(), )); } let s = std::str::from_utf8(bytes).map_err(|_| IoError::Invalid("design file is not UTF-8 JSON".into()))?; // Only a file that isn't a design pays for asking whether it is a drawing. Document::from_json(s).map_err(|e| match file_kind(bytes) { Ok(FileKind::Drawing) => IoError::Invalid("this file is a SolidCraft drawing, not a design: open it as a drawing".into()), _ => e.into(), }) } /// Design file bytes. pub fn write_design(doc: &Document) -> Vec { doc.to_json().into_bytes() } /// Parse a binary or ASCII STL (used by tests and round-trip checks): triangles. pub fn read_stl(bytes: &[u8]) -> Result> { // Binary when the size matches the triangle count in the header (some binary files start // with "solid" too); ASCII when the text has facets. let count = bytes.get(80..84).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]) as usize); let binary_size = count.is_some_and(|n| bytes.len() == 84 + n.saturating_mul(50)); let head = String::from_utf8_lossy(bytes.get(..bytes.len().min(512)).unwrap_or_default()).to_string(); let ascii = !binary_size && head.trim_start().starts_with("solid") && String::from_utf8_lossy(bytes).contains("facet"); let mut tris = Vec::new(); let ok = |v: &[f32; 3]| v.iter().all(|x| x.is_finite() && x.abs() < 1e9); if ascii { let s = String::from_utf8_lossy(bytes); let mut cur: Vec<[f32; 3]> = Vec::new(); for l in s.lines() { let mut it = l.split_whitespace(); match it.next() { Some("vertex") => { let v: Vec = it.filter_map(|x| x.parse().ok()).collect(); if let [x, y, z] = v[..] { cur.push([x, y, z]); } } // Each facet takes exactly its three vertices (a bad vertex drops the facet). Some("endfacet") => { if let [a, b, c] = cur[..] && [a, b, c].iter().all(ok) { tris.push([a, b, c]); } cur.clear(); } _ => {} } if tris.len() > MAX_STL_TRIANGLES { return Err(IoError::Invalid(format!("STL with more than {MAX_STL_TRIANGLES} triangles"))); } } return Ok(tris); } let n = count.ok_or_else(|| IoError::Invalid("short STL".into()))?; // A wrong count in the header (some writers leave 0): use the triangles that are there. let room = bytes.len().saturating_sub(84) / 50; let n = if n == 0 || n > room { room } else { n }; if n == 0 { return Err(IoError::Invalid("STL has no triangles".into())); } if n > MAX_STL_TRIANGLES { return Err(IoError::Invalid(format!("STL with {n} triangles (limit {MAX_STL_TRIANGLES})"))); } let f = |o: usize| bytes.get(o..o + 4).map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])).unwrap_or(f32::NAN); tris.reserve(n); for i in 0..n { // The facet normal (first 12 bytes) is ignored: winding gives the orientation. let o = 84 + i * 50 + 12; let v = |k: usize| [f(o + k * 12), f(o + k * 12 + 4), f(o + k * 12 + 8)]; let t = [v(0), v(1), v(2)]; if t.iter().all(ok) { tris.push(t); } } Ok(tris) } /// Most triangles we read from one STL file. pub const MAX_STL_TRIANGLES: usize = 20_000_000; /// `secs` since 1970 as (year, month, day, hour, minute, second) in UTC: crash reports' stamps and /// sheet PDFs' dates. pub fn civil(secs: u64) -> (i64, i64, i64, u64, u64, u64) { let days = i64::try_from(secs / 86_400).unwrap_or(0); let rem = secs % 86_400; let z = days + 719_468; let era = z.div_euclid(146_097); let doe = z.rem_euclid(146_097); let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); let mp = (5 * doy + 2) / 153; let d = doy - (153 * mp + 2) / 5 + 1; let m = if mp < 10 { mp + 3 } else { mp - 9 }; (yoe + era * 400 + i64::from(m <= 2), m, d, rem / 3600, rem % 3600 / 60, rem % 60) } #[cfg(test)] mod tests { use super::*; use solidcore_record::Vec3; use solidcraft_doc::{FeatureKind, Model, Operation, point_expr}; /// What a flattened import treats as a placeholder: what `generic_name` gives up on, an /// exporting translator's own names and a library model's bare number; a part's name is kept. #[test] fn placeholder_names_are_the_ones_that_say_nothing_about_the_part() { for n in ["", " ", "Body1", "Solid 2", "Open CASCADE STEP translator 7.5 2.51.1.1.1", "open cascade step translator 6.8 1.1", "7417113264"] { assert!(placeholder_name(n), "{n:?}"); } for n in ["Terminal", "R63ARK FPV", "SM08B-GHS-TB", "Mid_Body", "0603 capacitor"] { assert!(!placeholder_name(n), "{n:?}"); } } fn model() -> (Document, Model) { let mut doc = Document::new("t"); doc.add_feature( FeatureKind::Box { corner: point_expr(Vec3::ZERO), length: "10".into(), width: "20".into(), height: "30".into(), operation: Operation::NewBody, centred: false, }, None, ) .unwrap(); let mut m = Model::new(); m.evaluate(&doc); (doc, m) } /// A binary STL of a cube's triangles. fn cube_stl(flip: &[usize], header: &[u8], count: Option, normals: [f32; 3]) -> Vec { let c = |i: usize| [(i & 1) as f32 * 10.0, ((i >> 1) & 1) as f32 * 10.0, ((i >> 2) & 1) as f32 * 10.0]; let quads = [[0, 2, 3, 1], [4, 5, 7, 6], [0, 1, 5, 4], [2, 6, 7, 3], [0, 4, 6, 2], [1, 3, 7, 5]]; let mut tris = Vec::new(); for q in quads { tris.push([c(q[0]), c(q[1]), c(q[2])]); tris.push([c(q[0]), c(q[2]), c(q[3])]); } for &k in flip { tris[k].swap(1, 2); } let mut b = header.to_vec(); b.resize(80, b' '); b.extend(count.unwrap_or(tris.len() as u32).to_le_bytes()); for t in &tris { for x in normals.iter().chain(t.iter().flatten()) { b.extend(x.to_le_bytes()); } b.extend([0, 0]); } b } fn mesh_volume(bytes: &[u8]) -> f64 { let f = mesh_import_feature(bytes, "x.stl").unwrap(); let solidcraft_doc::FeatureKind::MeshImport { meshes, .. } = f.kind else { panic!() }; let m = &meshes[0]; let pos: Vec = m.positions.chunks(3).map(|c| Vec3::new(c[0], c[1], c[2])).collect(); let tris: Vec<[u32; 3]> = m.triangles.chunks(3).map(|c| [c[0], c[1], c[2]]).collect(); solidcraft_kernel::measure(&solidcraft_kernel::mesh_body(&pos, &tris).unwrap()).unwrap().volume } /// A unit scales an STL's coordinates to millimetres once, as it is read (an inch cube of 10 is /// 254 mm across); the feature keeps nothing of the unit. A bad unit, a unit on a file that /// states its own, and a size beyond the limits are refused. #[test] fn stl_unit_scales_the_mesh_as_it_is_read() { let stl = cube_stl(&[], b"solid exported by something", None, [0.0; 3]); let volume = |mm: f64| { let f = mesh_import_feature_in(&stl, "x.stl", mm).unwrap(); let solidcraft_doc::FeatureKind::MeshImport { meshes, .. } = f.kind else { panic!() }; let m = &meshes[0]; let pos: Vec = m.positions.chunks(3).map(|c| Vec3::new(c[0], c[1], c[2])).collect(); let tris: Vec<[u32; 3]> = m.triangles.chunks(3).map(|c| [c[0], c[1], c[2]]).collect(); solidcraft_kernel::measure(&solidcraft_kernel::mesh_body(&pos, &tris).unwrap()).unwrap().volume }; assert!((volume(1.0) - 1000.0).abs() < 1e-6); assert!((volume(25.4) - 1000.0 * 25.4f64.powi(3)).abs() < 1e-3 * 25.4f64.powi(3)); assert!(mesh_import_feature_in(&stl, "x.stl", 0.0).is_err()); assert!(mesh_import_feature_in(&stl, "x.stl", f64::NAN).is_err()); assert!(mesh_import_feature_in(&stl, "x.stl", 1e12).is_err()); assert!(mesh_import_feature_in(&stl, "x.3mf", 25.4).is_err()); assert!(mesh_import_feature_in(&stl, "x.glb", 25.4).is_err()); } /// An STL holding `triangles` as a binary file. fn stl_of(triangles: &[[[f32; 3]; 3]]) -> Vec { let mut bytes = vec![0u8; 80]; bytes.extend((triangles.len() as u32).to_le_bytes()); for triangle in triangles { bytes.extend([0u8; 12]); for vertex in triangle { for coordinate in vertex { bytes.extend(coordinate.to_le_bytes()); } } bytes.extend([0u8; 2]); } bytes } /// Every stored coordinate is the file's `f32` value widened to `f64` and multiplied by the /// unit's millimetres, exactly: no rounding through `f32`, and not scaled twice. The values /// are exact in `f32`, so the expected numbers carry no rounding of their own. #[test] fn stl_coordinates_are_the_widened_value_times_the_unit_exactly() { let (a, b, c, d) = ([0.5, -3.75, 1.25], [7.0, 0.25, -2.5], [-1.5, 4.0, 0.125], [2.0, 2.0, 9.5]); let triangles = [[a, b, c], [a, c, d], [a, d, b], [b, d, c]]; let stl = stl_of(&triangles); for (unit, mm) in solidcraft_doc::point_cloud::UNITS { let feature = mesh_import_feature_in(&stl, "t.stl", mm).unwrap(); let solidcraft_doc::FeatureKind::MeshImport { meshes, .. } = feature.kind else { panic!() }; let want: Vec = triangles.iter().flatten().flatten().map(|v| f64::from(*v) * mm).collect(); assert_eq!(&*meshes[0].positions, want.as_slice(), "{unit}"); } } /// A PLY with faces, read as a mesh, takes a unit as an STL does: it states none either. #[test] fn ply_mesh_unit_scales_its_vertices_exactly() { let corners = [[0.5f32, -3.75, 1.25], [7.0, 0.25, -2.5], [-1.5, 4.0, 0.125], [2.0, 2.0, 9.5]]; let mut ply = String::from("ply\nformat ascii 1.0\nelement vertex 4\nproperty float x\nproperty float y\nproperty float z\n"); ply.push_str("element face 4\nproperty list uchar int vertex_indices\nend_header\n"); for c in corners { ply.push_str(&format!("{} {} {}\n", c[0], c[1], c[2])); } ply.push_str("3 0 1 2\n3 0 2 3\n3 0 3 1\n3 1 3 2\n"); let sorted = |mut v: Vec| { v.sort_by(f64::total_cmp); v }; for (unit, mm) in solidcraft_doc::point_cloud::UNITS { let feature = mesh_import_feature_in(ply.as_bytes(), "t.ply", mm).unwrap(); let solidcraft_doc::FeatureKind::MeshImport { meshes, .. } = feature.kind else { panic!() }; let want: Vec = corners.iter().flatten().map(|v| f64::from(*v) * mm).collect(); assert_eq!(sorted(meshes[0].positions.to_vec()), sorted(want), "{unit}"); } } /// STL quirks: a binary header starting with "solid", a zero triangle count, garbage /// normals, stray inverted facets and non-finite vertices. #[test] fn stl_quirks_read_cleanly() { let v = mesh_volume(&cube_stl(&[], b"solid exported by something", None, [0.0; 3])); assert!((v - 1000.0).abs() < 1e-6, "{v}"); let v = mesh_volume(&cube_stl(&[], b"x", Some(0), [f32::NAN, 9.0, -7.0])); assert!((v - 1000.0).abs() < 1e-6, "{v}"); let v = mesh_volume(&cube_stl(&[1, 4, 7], b"x", None, [1.0, 0.0, 0.0])); assert!((v - 1000.0).abs() < 1e-6, "flipped facets: {v}"); let mut bad = cube_stl(&[], b"x", None, [0.0; 3]); bad[84 + 12..84 + 16].copy_from_slice(&f32::INFINITY.to_le_bytes()); assert_eq!(read_stl(&bad).unwrap().len(), 11); // ASCII with a non-UTF-8 name and a facet with a bad vertex. let mut ascii = b"solid caf\xe9\n".to_vec(); ascii.extend(b"facet normal 0 0 1\nouter loop\nvertex 0 0 0\nvertex 1 0 0\nvertex 0 1 0\nendloop\nendfacet\n"); ascii.extend(b"facet normal 0 0 1\nouter loop\nvertex 0 0 0\nvertex nan 0 0\nvertex 0 1 0\nendloop\nendfacet\nendsolid\n"); assert_eq!(read_stl(&ascii).unwrap().len(), 1); for b in [&b""[..], b"solid", &[0u8; 83], &[0xff; 200], &cube_stl(&[], b"x", Some(u32::MAX), [0.0; 3])[..]] { let r = std::panic::catch_unwind(|| read_stl(b).map(|t| t.len())); assert!(r.is_ok()); } } #[test] fn stl_round_trip_volume() { let (_, m) = model(); let bytes = export(&m.state(), &[], Format::StlBinary, "t").unwrap(); let tris = read_stl(&bytes).unwrap(); let v: f64 = tris .iter() .map(|t| { let p = |k: usize| Vec3::new(t[k][0] as f64, t[k][1] as f64, t[k][2] as f64); p(0).dot(p(1).cross(p(2))) / 6.0 }) .sum(); assert!((v - 6000.0).abs() < 1e-2, "{v}"); let a = export(&m.state(), &[], Format::StlAscii, "t").unwrap(); assert_eq!(read_stl(&a).unwrap().len(), tris.len()); let o = String::from_utf8(export(&m.state(), &[], Format::Obj, "t").unwrap()).unwrap(); assert!(o.contains("o Body1") && o.contains("\nf ")); } /// OBJ shares the vertices faces meet at and keeps the body name as written, spaces included. /// The 10 × 20 × 30 box is meshed on the mesh path, shaped to the smallest angle, so its /// faces take nodes inside them (it was 8 vertices and 12 triangles, two a face, on the /// display path). Whatever their number: the welded mesh is closed (every side in two /// triangles, run opposite ways) and a sphere's (f = 2v - 4), each triangle keeps the angle, /// its area and volume are the box's (its faces are flat, so exactly, to rounding), and it has /// one normal per face. #[test] fn obj_export_is_welded_and_keeps_names() { let (_, m) = model(); let mut st = (*m.state()).clone(); for b in &mut st.bodies { b.name = "Red Block".into(); } let o = String::from_utf8(export(&st, &[], Format::Obj, "t").unwrap()).unwrap(); let count = |p: &str| o.lines().filter(|l| l.starts_with(p)).count(); assert!(o.contains("\no Red Block\n"), "{o}"); let (v, f) = (count("v "), count("f ")); assert_eq!(count("vn "), 6, "{o}"); assert_eq!(f, 2 * v - 4, "closed and of genus 0: {v} vertices, {f} triangles"); let points: Vec = o .lines() .filter_map(|l| l.strip_prefix("v ")) .map(|l| { let x: Vec = l.split(' ').map(|x| x.parse().unwrap()).collect(); Vec3::new(x[0], x[1], x[2]) }) .collect(); let tris: Vec<[usize; 3]> = o .lines() .filter_map(|l| l.strip_prefix("f ")) .map(|l| { let ids: Vec = l.split(' ').map(|c| c.split('/').next().unwrap().parse().unwrap()).collect(); [ids[0], ids[1], ids[2]] }) .collect(); assert!(tris.iter().flatten().all(|i| (1..=v).contains(i))); let mut sides = std::collections::BTreeMap::<(usize, usize), i32>::new(); for t in &tris { for (a, b) in [(t[0], t[1]), (t[1], t[2]), (t[2], t[0])] { *sides.entry((a.min(b), a.max(b))).or_default() += if a < b { 1 } else { -1 }; } } assert!(sides.values().all(|n| *n == 0), "every side is run once each way"); let corner = |a: Vec3, b: Vec3, c: Vec3| (b - a).cross(c - a).len().atan2((b - a).dot(c - a)).to_degrees(); let (mut area, mut volume) = (0.0, 0.0); for t in &tris { let [a, b, c] = t.map(|i| points[i - 1]); let smallest = corner(a, b, c).min(corner(b, c, a)).min(corner(c, a, b)); assert!(smallest >= solidcraft_kernel::MESH_MIN_ANGLE - 1e-6, "{smallest}°"); area += (b - a).cross(c - a).len() / 2.0; volume += a.dot(b.cross(c)) / 6.0; } assert!((area - 2200.0).abs() < 1e-9 * 2200.0, "{area}"); assert!((volume - 6000.0).abs() < 1e-9 * 6000.0, "{volume}"); } /// The OBJ export carries the colours of the bodies: the mesh file names the material /// library beside it and every body with a colour gets a material in it. #[test] fn obj_export_writes_the_colours_of_the_bodies() { let (_, m) = model(); let mut st = (*m.state()).clone(); st.bodies[0].body = st.bodies[0].body.clone().with_color(Some([208.0 / 255.0, 48.0 / 255.0, 48.0 / 255.0])); let files = export_obj(&st, &[], "part.mtl", MeshQuality::default()).unwrap(); assert!(files.obj.contains("\nmtllib part.mtl\n"), "{}", files.obj); assert!(files.obj.contains("\nusemtl Body1\n"), "{}", files.obj); assert!(files.mtl.contains("\nnewmtl Body1\n"), "{}", files.mtl); assert!(files.mtl.contains("Kd 0.816 0.188 0.188"), "{}", files.mtl); // The export that writes one file names no material library it cannot write. let o = String::from_utf8(export(&st, &[], Format::Obj, "part").unwrap()).unwrap(); assert!(!o.contains("mtllib"), "{o}"); } /// The design properties land in each format's own metadata (#1015): STEP and IGES headers, /// 3MF model metadata. Other tools' keys never leave the design file. #[test] fn exports_write_design_properties() { let (_, m) = model(); let meta: Metadata = serde_json::from_value(serde_json::json!({ "project": "ACME ", "author": "Jane O'Brien", "organization": "ACME", "license": "CC-BY-4.0", "description": "Vented Gehäuse\nfor a Pi", "revision": 7, "com.acme.secret": {"token": "SECRET-VALUE"}, })) .unwrap(); let step = String::from_utf8(export_with_metadata(&m.state(), &[], Format::Step, "t", &meta).unwrap()).unwrap(); assert!(step.contains("FILE_DESCRIPTION(('Vented Geh\\X2\\00E4\\X0\\use for a Pi'),'2;1');"), "{}", &step[..300]); assert!(step.contains("FILE_NAME('t.step','',('Jane O''Brien'),('ACME'),"), "{}", &step[..300]); assert_eq!(step_import_feature(step.as_bytes(), "t.step").unwrap().body_names, ["t"], "still reads back"); let iges = String::from_utf8(export_with_metadata(&m.state(), &[], Format::Iges, "t", &meta).unwrap()).unwrap(); assert!(iges.contains("12HJane O'Brien") && iges.contains("4HACME")); let model_xml = |bytes: Vec| { use std::io::Read as _; let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap(); let mut x = String::new(); zip.by_name("3D/3dmodel.model").unwrap().read_to_string(&mut x).unwrap(); x }; let x = model_xml(export_with_metadata(&m.state(), &[], Format::ThreeMf, "t", &meta).unwrap()); for want in [ "SolidCraft\n ACME <enclosures>", "Jane O'Brien", "Vented Gehäuse\nfor a Pi", "CC-BY-4.0", ] { assert!(x.contains(want), "{want}\n{}", &x[..400]); } assert!(write_3mf_with(&[], &[("Title", "x")]).is_err(), "no objects is still an error"); for out in [step.as_str(), iges.as_str(), x.as_str()] { assert!(!out.contains("SECRET-VALUE") && !out.contains("com.acme")); } // Without properties the files are as they always were. let plain = String::from_utf8(export(&m.state(), &[], Format::Step, "t").unwrap()).unwrap(); assert!(plain.contains("FILE_DESCRIPTION(('SolidCraft model'),'2;1');\nFILE_NAME('t.step','',(''),(''),")); assert!(!model_xml(export(&m.state(), &[], Format::ThreeMf, "t").unwrap()).contains("Title")); } /// #18780: in an export of multiple bodies, if one body fails to mesh, it is skipped with a /// warning note and the remaining valid bodies are exported. #[test] fn untessellated_body_is_skipped_with_warning_on_multi_body_export() -> Result<()> { let (_, m) = model(); let valid_body = &m.state().bodies[0]; let mut broken_model_body = valid_body.clone(); broken_model_body.name = "BrokenSliver".into(); let sel = [valid_body, &broken_model_body]; let res = per_placed_body(&sel, |b, body| { if b.name == "BrokenSliver" { Err(IoError::Invalid("not supported yet: tessellation: face 0 (cylinder)".into())) } else { body_mesh(b, body, MeshQuality::default()) } }); let (items, notes) = res?; assert_eq!(items.len(), 1, "only the valid body is kept"); assert_eq!(items[0].0.name, "Body1"); assert!( notes.iter().any(|n| n.contains("BrokenSliver: skipped: meshing failed")), "warning note must be reported for skipped body: {notes:?}" ); // However, if all bodies fail (or only the broken body is exported), it must return Err let only_broken = [&broken_model_body]; let err_res = per_placed_body(&only_broken, |_b, _body| -> Result<(Mesh, Vec)> { Err(IoError::Invalid("not supported yet: tessellation".into())) }); assert!(err_res.is_err(), "single failing body must fail the export"); Ok(()) } #[test] fn step_names_in_a_legacy_encoding() { // Exporters that write names in the system encoding instead of Part 21 escapes (#2344). let (_, m) = model(); let step = export(&m.state(), &[], Format::Step, "t").unwrap(); let at = step.windows(7).position(|w| w == b"'Body1'").unwrap(); for (encoding, name) in [(encoding_rs::GBK, "圆角20"), (encoding_rs::SHIFT_JIS, "ネジ穴の面取り"), (encoding_rs::WINDOWS_1252, "Gehäuse")] { let mut bytes = step[..at + 1].to_vec(); bytes.extend_from_slice(&encoding.encode(name).0); bytes.extend_from_slice(&step[at + 6..]); assert!(std::str::from_utf8(&bytes).is_err(), "{name}: the test file is not UTF-8"); assert_eq!(step_import_feature(&bytes, "t.step").unwrap().body_names, [name], "{}", encoding.name()); } // UTF-8 names are read as they are. let mut bytes = step[..at + 1].to_vec(); bytes.extend_from_slice("圆角".as_bytes()); bytes.extend_from_slice(&step[at + 6..]); assert_eq!(step_import_feature(&bytes, "t.step").unwrap().body_names, ["圆角"]); } #[test] fn step_and_design() { let (doc, m) = model(); let s = String::from_utf8(export(&m.state(), &[], Format::Step, "t").unwrap()).unwrap(); assert!(s.starts_with("ISO-10303-21;") && s.contains("CLOSED_SHELL")); let back = read_design(&write_design(&doc)).unwrap(); assert_eq!(back, doc); assert!(read_design(b"\xff\xfe").is_err()); let dwg = read_design(b"AC1032\0\0\0\0\0\xff\xfe").unwrap_err().to_string(); assert!(dwg.contains("this is a DWG file") && dwg.contains("STEP") && dwg.contains("DXF"), "{dwg}"); assert!(matches!(export(&m.state(), &["nope".into()], Format::Step, "t"), Err(IoError::Empty))); assert_eq!(Format::from_name("a.STP").unwrap(), Format::Step); assert!(is_step_path("/x/Part.STEP") && is_step_path("a.stp") && !is_step_path("a.step.json") && !is_step_path("step")); let f = step_import_feature(s.as_bytes(), "/tmp/My Part.step").unwrap(); // Named after the exported product (the export was called `t`). assert_eq!(f.name, "t"); assert_eq!(f.body_names, ["t"]); assert_eq!(f.body_names.len(), 1); assert!(matches!(&f.kind, FeatureKind::Import { file, .. } if file == "My Part.step")); let mut imported = Document::new("Imported STEP round trip"); imported.add_feature(f.kind, None).unwrap(); let packaged = read_design(&write_design_container(&imported).unwrap()).unwrap(); assert_eq!(packaged, imported); let mut rebuilt = Model::new(); rebuilt.evaluate(&packaged); assert!(rebuilt.results.iter().all(|r| r.error.is_none())); let state = rebuilt.state(); assert_eq!(state.bodies.len(), 1); assert!((solidcraft_kernel::measure(&state.bodies[0].body).unwrap().volume - 6000.0).abs() < 1e-6); assert!(step_import_feature(b"ISO-10303-21;", "x.step").is_err()); assert!(step_import_feature(&[0xff, 0xfe, 0x00], "x.step").is_err()); assert!(Format::from_name("a.dwg").is_err()); // Compatibility shim: the legacy design extensions are still designs. assert!(Format::from_name("old.solvecraft").is_err(), "the pre-rename extension is no longer a name we know; its files open by content"); assert_eq!(Format::from_name("older.solidcraft").unwrap(), Format::Design); assert_eq!(Format::from_name("new.sc").unwrap(), Format::Design); assert_eq!(Format::from_name("NEW.SC").unwrap(), Format::Design); assert!(!is_design_path("/d/old.SOLVECRAFT") && is_design_path("older.solidcraft") && is_design_path("new.sc") && !is_design_path("a.step")); assert_eq!(DESIGN_EXT, "sc"); assert_eq!(DESIGN_EXTS, ["sc", "solidcraft"], "new extension first, then every older one"); assert!(read_stl(&[0u8; 10]).is_err()); let mut fake = vec![0u8; 84]; fake[80..84].copy_from_slice(&u32::MAX.to_le_bytes()); assert!(read_stl(&fake).is_err()); } /// A frame holding a plate and two posts, whose solids carry the names of the last feature /// that made them, as some CAD systems write them; as STEP text. fn frame_step() -> String { use solidcraft_kernel::{ExportBody, ExportProduct, StepHeader, box_solid, step_export_products}; let plate = box_solid(Vec3::ZERO, Vec3::new(10.0, 10.0, 2.0)).unwrap(); let post = box_solid(Vec3::ZERO, Vec3::new(2.0, 2.0, 8.0)).unwrap(); let at = |x: f64| [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [x, 0.0, 0.0, 1.0]]; let part = |name: &str, label: &str, body| ExportProduct { name: name.into(), bodies: vec![ExportBody { name: label.into(), body, color: None }], children: Vec::new(), }; let products = vec![ ExportProduct { name: "Frame".into(), bodies: Vec::new(), children: vec![(1, at(0.0), "Plate-1".into()), (2, at(20.0), "Post-1".into()), (2, at(30.0), "Post-2".into())], }, part("Plate", "Cut-Extrude3", &plate), part("Post", "Boss-Extrude1", &post), ]; step_export_products(&products, 0, &StepHeader::default()).unwrap() } /// Automatic names keep meaningful solid labels and replace placeholders with part names. /// Explicit choices still select the solid, product or occurrence. #[test] fn step_import_names_follow_the_choice() { let text = frame_step(); let names = |text: &str, choice| step_import_feature_named(text.as_bytes(), "frame.step", choice).unwrap().body_names; assert_eq!(names(&text, StepNames::Solid), ["Cut-Extrude3", "Boss-Extrude1", "Boss-Extrude1"]); assert_eq!(names(&text, StepNames::Product), ["Plate", "Post", "Post"]); assert_eq!(names(&text, StepNames::Instance), ["Plate-1", "Post-1", "Post-2"]); // Meaningful solid names survive automatic naming, including SolidCraft exports. assert_eq!(step_import_feature(text.as_bytes(), "frame.step").unwrap().body_names, names(&text, StepNames::Solid)); let generic = text.replace("'Cut-Extrude3'", "'Body1'").replace("'Boss-Extrude1'", "'Body 2 (3)'"); assert_eq!(step_import_feature(generic.as_bytes(), "frame.step").unwrap().body_names, ["Plate", "Post", "Post"]); assert_eq!(names(&generic, StepNames::Solid), ["Body1", "Body 2 (3)", "Body 2 (3)"]); let named = generic.replace("'Body1'", "'Body housing'"); assert_eq!(names(&named, StepNames::Auto), ["Body housing", "Post", "Post"]); // The timeline entry is the root product's name whatever the bodies are called. for choice in [StepNames::Auto, StepNames::Solid, StepNames::Product, StepNames::Instance] { assert_eq!(step_import_feature_named(text.as_bytes(), "frame.step", choice).unwrap().name, "Frame"); } // A product the file leaves unnamed says nothing: its bodies keep the solid's name. let unnamed = text.replace("PRODUCT('Plate','Plate',", "PRODUCT('(unnamed)','(unnamed)',"); assert_eq!(names(&unnamed, StepNames::Product), ["Cut-Extrude3", "Post", "Post"]); // A part file has no occurrence: the instance choice gives the product's name. let (_, m) = model(); let part = String::from_utf8(export(&m.state(), &[], Format::Step, "Bracket").unwrap()).unwrap(); assert_eq!(names(&part, StepNames::Solid), ["Body1"]); assert_eq!(names(&part, StepNames::Product), ["Bracket"]); assert_eq!(names(&part, StepNames::Instance), ["Bracket"]); assert_eq!(names(&part, StepNames::Auto), ["Bracket"]); assert_eq!(StepNames::parse(" AuTo "), Some(StepNames::Auto)); assert_eq!(StepNames::parse(" Product "), Some(StepNames::Product)); assert_eq!(StepNames::parse("INSTANCE"), Some(StepNames::Instance)); assert_eq!(StepNames::parse("label"), None); } fn stl_volume(bytes: &[u8]) -> f64 { read_stl(bytes) .unwrap() .iter() .map(|t| { let p = |k: usize| Vec3::new(t[k][0] as f64, t[k][1] as f64, t[k][2] as f64); p(0).dot(p(1).cross(p(2))) / 6.0 }) .sum() } /// A filleted box, a cylinder and a torus: bodies whose faces are curved and meshed apart. fn curved_bodies() -> Model { let mut doc = Document::new("t"); doc.add_feature( FeatureKind::Box { corner: point_expr(Vec3::ZERO), length: "40".into(), width: "30".into(), height: "10".into(), operation: Operation::NewBody, centred: false, }, None, ) .unwrap(); doc.add_feature( FeatureKind::Fillet { edges: vec![solidcraft_doc::Position(Vec3::new(0.0, 0.0, 5.0))], radius: "4".into(), body: None, style: Default::default(), fit: Default::default(), corner: Default::default(), setbacks: Vec::new(), turn: Default::default(), tangent_chain: true, edge_radii: Vec::new(), }, None, ) .unwrap(); doc.add_feature( FeatureKind::Cylinder { base: point_expr(Vec3::new(80.0, 0.0, 0.0)), axis: solidcraft_doc::Dir(Vec3::Z), radius: "6".into(), height: "15".into(), operation: Operation::NewBody, references: Vec::new(), }, None, ) .unwrap(); doc.add_feature( FeatureKind::Torus { center: point_expr(Vec3::new(0.0, 80.0, 0.0)), major: "12".into(), minor: "3".into(), operation: Operation::NewBody, }, None, ) .unwrap(); let mut m = Model::new(); m.evaluate(&doc); m } /// The smallest angle (degrees) of each triangle of an STL file. fn stl_smallest_angles(bytes: &[u8]) -> Vec { read_stl(bytes) .unwrap() .iter() .map(|t| { let p = |k: usize| Vec3::new(t[k][0] as f64, t[k][1] as f64, t[k][2] as f64); let corner = |a: Vec3, b: Vec3, c: Vec3| { let (u, v) = (b - a, c - a); u.cross(v).len().atan2(u.dot(v)).to_degrees() }; let (a, b, c) = (p(0), p(1), p(2)); corner(a, b, c).min(corner(b, c, a)).min(corner(c, a, b)) }) .collect() } /// The smallest angle the mesh export asks for: `MeshSpec::chord`'s default. const EXPORT_MIN_ANGLE: f64 = solidcraft_kernel::MESH_MIN_ANGLE; /// How far an STL corner's angle may move from the mesh's own when the coordinates are /// rounded to `f32` (a relative 6e-8 of each coordinate, on parts of 10 to 30 mm with sides /// of a tenth of a millimetre or more: under 1e-4 degrees). const F32_ANGLE_SLACK: f64 = 1e-3; /// A part's export mesh placed ([`PartMesh::placed`]) is its first placement's, moved: the /// same triangles, its points moved by the placement, the same notes, and the part meshed /// once for every placement. #[test] fn a_placed_copys_export_mesh_is_its_originals_moved() { let part = solidcraft_kernel::box_solid(Vec3::ZERO, Vec3::new(30.0, 20.0, 10.0)).unwrap(); let share = PartMesh::new(part.clone()); let (angle, shift) = (0.7f64, Vec3::new(50.0, -20.0, 5.0)); let (c, s) = (angle.cos(), angle.sin()); let t = [[c, s, 0., 0.], [-s, c, 0., 0.], [0., 0., 1., 0.], [shift.x, shift.y, shift.z, 1.]]; let spec = solidcraft_kernel::MeshSpec::chord(part.size() * 2e-4); let (original, stats) = part.export_mesh(&spec).unwrap(); for _ in 0..2 { let (m, notes) = share.placed(&spec, &t).unwrap().unwrap(); assert_eq!(m.triangles, original.triangles); assert_eq!(m.tri_face, original.tri_face); assert_eq!(notes, mesh_notes(&stats, &spec)); let placed = solidcraft_kernel::placed_mesh(&original, &t).unwrap(); let far = m.positions.iter().zip(&placed.positions).map(|(p, q)| p.dist(*q)).fold(0.0, f64::max); assert!(far < 1e-9, "{far}"); } assert_eq!(share.made.lock().unwrap().len(), 1, "meshed once for both copies"); } /// A part keeps its export meshes by spec: asked again, the same mesh without meshing again; /// another spec meshes anew. #[test] fn a_part_keeps_its_export_meshes_by_spec() { let kept = PartMesh::new(solidcraft_kernel::box_solid(Vec3::ZERO, Vec3::new(30.0, 20.0, 10.0)).unwrap()); let (a, b) = (solidcraft_kernel::MeshSpec::chord(0.01), solidcraft_kernel::MeshSpec { min_angle: 20.0, ..solidcraft_kernel::MeshSpec::chord(0.01) }); let first = kept.mesh(&a).unwrap(); let again = kept.mesh(&a).unwrap(); assert!(std::sync::Arc::ptr_eq(&first, &again)); assert_eq!(kept.made.lock().unwrap().len(), 1, "one spec, one meshing"); let _ = kept.mesh(&b).unwrap(); assert_eq!(kept.made.lock().unwrap().len(), 2); } /// A face left short of the angle is said to be short of it; one whose shaping a bound stopped /// after it reached the angle is said to have reached it. A mesh with nothing to report has no notes. #[test] fn notes_say_short_only_for_a_face_under_the_angle() { let spec = solidcraft_kernel::MeshSpec::chord(0.01); assert!(mesh_notes(&solidcraft_kernel::PlanStats::default(), &spec).is_empty()); let unshaped = |face: usize, smallest_angle: f64| solidcore_tess::Unshaped { face, smallest_angle, limits: vec![solidcore_tess::ShapeLimit::Rounds] }; let stats = solidcraft_kernel::PlanStats { unshaped: vec![unshaped(3, 18.5), unshaped(7, 27.25)], ..Default::default() }; let notes = mesh_notes(&stats, &spec); assert_eq!(notes.len(), 2); assert!(notes[0].starts_with("face 3: smallest angle 18.50°, short of the 25° asked"), "{}", notes[0]); assert!(!notes[1].contains("short"), "{}", notes[1]); assert!(notes[1].contains("face 7") && notes[1].contains("reached") && notes[1].contains("27.25°"), "{}", notes[1]); } /// A 10 × 20 × 30 box exported as STL has no triangle sharper than the mesh export's smallest /// angle: every face goes through the mesh path (`solidcore_tess::mesh`), planar ones too. /// On the display path (`Body::mesh`, before #15622) it was 12 triangles, two per face, 4 of /// them under 25° (the 10 × 30 faces' halves), the smallest 18.43° (atan(10/30)). #[test] fn a_box_exported_as_stl_has_no_triangle_under_the_smallest_angle() { let (_, m) = model(); let bytes = export(&m.state(), &[], Format::StlBinary, "t").unwrap(); let angles = stl_smallest_angles(&bytes); let smallest = angles.iter().copied().fold(f64::INFINITY, f64::min); let under = angles.iter().filter(|a| **a < EXPORT_MIN_ANGLE - F32_ANGLE_SLACK).count(); assert!(under == 0, "{under} of {} triangles under {EXPORT_MIN_ANGLE}°, smallest {smallest}°", angles.len()); assert!((stl_volume(&bytes) - 6000.0).abs() < 1e-2); } /// A cylinder (radius 6, height 15) exported as STL has no triangle sharper than the mesh /// export's smallest angle, its side and caps alike. On the display path (`Body::mesh`, /// before #15622) it was 4848 triangles, 4608 of them under 25°, the smallest 15.11°. #[test] fn a_cylinder_exported_as_stl_has_no_triangle_under_the_smallest_angle() { let mut doc = Document::new("t"); doc.add_feature( FeatureKind::Cylinder { base: point_expr(Vec3::ZERO), axis: solidcraft_doc::Dir(Vec3::Z), radius: "6".into(), height: "15".into(), operation: Operation::NewBody, references: Vec::new(), }, None, ) .unwrap(); let mut m = Model::new(); m.evaluate(&doc); let bytes = export(&m.state(), &[], Format::StlBinary, "t").unwrap(); let angles = stl_smallest_angles(&bytes); let smallest = angles.iter().copied().fold(f64::INFINITY, f64::min); let under = angles.iter().filter(|a| **a < EXPORT_MIN_ANGLE - F32_ANGLE_SLACK).count(); assert!(under == 0, "{under} of {} triangles under {EXPORT_MIN_ANGLE}°, smallest {smallest}°", angles.len()); } /// OBJ is welded as STL and 3MF are: a filleted box, a cylinder and a torus written as OBJ /// open again closed, with their STL export's volume, every face keeping its normals /// (#9074). Before, each face wrote its edge points again, a few ulps apart, and the file /// opened as an open mesh with no volume. #[test] fn obj_round_trip_of_curved_bodies_is_closed() { let m = curved_bodies(); let st = m.state(); let bytes = export(&st, &[], Format::Obj, "t").unwrap(); let text = String::from_utf8(bytes.clone()).unwrap(); assert!(text.lines().filter(|l| l.starts_with("f ")).all(|l| l.matches("//").count() == 3), "every corner has a normal"); let f = mesh_import_feature(&bytes, "parts.obj").unwrap(); let mut d2 = Document::new("m"); let id = d2.add_feature(f.kind, Some(&f.name)).unwrap(); let mut m2 = Model::new(); m2.evaluate(&d2); assert!(m2.result(id).unwrap().error.is_none()); let st2 = m2.state(); assert_eq!(st2.bodies.len(), 3); for (a, b) in st.bodies.iter().zip(&st2.bodies) { assert!(b.body.is_mesh() && b.body.is_closed_mesh(), "{} is not watertight", a.name); let v_stl = stl_volume(&export(&st, std::slice::from_ref(&a.name), Format::StlBinary, "t").unwrap()); let v = solidcraft_kernel::measure(&b.body).unwrap().volume; assert!((v - v_stl).abs() <= 1e-6 * v_stl.abs(), "{}: {v} vs {v_stl}", a.name); } } /// Build → export 3MF → import → the same volume as the STL export, closed meshes, names. #[test] fn threemf_round_trip() { let m = curved_bodies(); let st = m.state(); assert_eq!(st.bodies.len(), 3); let bytes = export(&st, &[], Format::ThreeMf, "t").unwrap(); let f = mesh_import_feature(&bytes, "/tmp/parts.3MF").unwrap(); assert_eq!(f.body_names, st.bodies.iter().map(|b| b.name.clone()).collect::>()); let mut d2 = Document::new("m"); let id = d2.add_feature(f.kind, Some(&f.name)).unwrap(); let mut m2 = Model::new(); m2.evaluate(&d2); assert!(m2.result(id).unwrap().error.is_none()); let st2 = m2.state(); assert_eq!(st2.bodies.len(), 3); for (a, b) in st.bodies.iter().zip(&st2.bodies) { assert_eq!(a.name, b.name); assert!(b.body.is_mesh() && b.body.is_closed_mesh(), "{} is not watertight", b.name); let v_stl = stl_volume(&export(&st, std::slice::from_ref(&a.name), Format::StlBinary, "t").unwrap()); let v = solidcraft_kernel::measure(&b.body).unwrap().volume; assert!((v - v_stl).abs() <= 1e-6 * v_stl.abs(), "{}: {v} vs {v_stl}", a.name); } // Mesh bodies export again (3MF, STL, OBJ) but not as STEP. assert!(export(&st2, &[], Format::ThreeMf, "t").is_ok()); assert!(export(&st2, &[], Format::StlAscii, "t").is_ok()); assert!(export(&st2, &[], Format::Obj, "t").is_ok()); assert!(export(&st2, &[], Format::Step, "t").is_err()); // STL imports the same way. let stl = export(&st, &[], Format::StlBinary, "t").unwrap(); let fs = mesh_import_feature(&stl, "all.stl").unwrap(); assert_eq!(fs.name, "all"); assert!(mesh_import_feature(b"PK", "x.3mf").is_err()); assert!(mesh_import_feature(&[0u8; 84], "x.stl").is_err()); assert!(is_mesh_path("a.3MF") && is_mesh_path("b.stl") && !is_mesh_path("c.step")); } /// Face-tagged 3MF: every triangle carries its B-rep face, every coordinate is the /// tessellation's own `f64`, the bytes are deterministic, and the package stays plain 3MF. #[test] fn tagged_threemf_carries_faces_exactly() { use std::io::Read; let mut doc = Document::new("t"); doc.add_feature( FeatureKind::Box { corner: point_expr(Vec3::new(0.1, -0.3, 1.0 / 3.0)), length: "40".into(), width: "30".into(), height: "10".into(), operation: Operation::NewBody, centred: false, }, None, ) .unwrap(); doc.add_feature( FeatureKind::Fillet { edges: vec![solidcraft_doc::Position(Vec3::new(0.1, -0.3, 5.0 + 1.0 / 3.0))], radius: "4".into(), body: None, style: Default::default(), fit: Default::default(), corner: Default::default(), setbacks: Vec::new(), turn: Default::default(), tangent_chain: true, edge_radii: Vec::new(), }, None, ) .unwrap(); let mut m = Model::new(); m.evaluate(&doc); let st = m.state(); let body = &st.bodies[0].body; let faces = body.face_count(); assert_eq!(faces, 7); let bytes = export(&st, &[], Format::ThreeMfTagged, "t").unwrap(); assert_eq!(bytes, export(&st, &[], Format::ThreeMfTagged, "t").unwrap(), "deterministic bytes"); assert_eq!(Format::from_name("3mf-tagged").unwrap(), Format::ThreeMfTagged); assert_eq!(Format::from_name("part.3mf").unwrap(), Format::ThreeMf); let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes.as_slice())).unwrap(); let mut xml = String::new(); zip.by_name("3D/3dmodel.model").unwrap().read_to_string(&mut xml).unwrap(); assert!(xml.contains(&format!("xmlns:ft=\"{}\"", threemf::FACE_TAGS_NS)), "{}", &xml[..400]); assert!(xml.contains(&format!("ft:faces=\"{faces}\""))); let tris: Vec<&str> = xml.lines().filter(|l| l.trim_start().starts_with(" = tris.iter().map(|l| l.split("ft:face=\"").nth(1).and_then(|r| r.split('"').next()).unwrap().parse().unwrap()).collect(); seen.sort_unstable(); seen.dedup(); assert_eq!(seen, (0..faces).collect::>(), "every face is tagged"); // Coordinates are the tessellation's own values, bit for bit. let exact: std::collections::HashSet = export_mesh(body).unwrap().positions.iter().flat_map(|p| [p.x, p.y, p.z]).map(|v| (v + 0.0).to_bits()).collect(); let attr = |l: &str, k: &str| l.split(&format!(" {k}=\"")).nth(1).and_then(|r| r.split('"').next()).unwrap().parse::().unwrap(); for l in xml.lines().filter(|l| l.trim_start().starts_with("