Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion ATTRIBUTION.md
Original file line number Diff line number Diff line change
Expand Up @@ -1024,7 +1024,7 @@ into THIRD-PARTY-LICENSES.txt when `main` regenerates it.

## FreeCAD, Rhino and OpenUSD library

FreeCAD `.FCStd` and Rhino `.3dm` files are read, and OpenUSD files read and written, with
FreeCAD `.FCStd` files are read, and Rhino `.3dm` and OpenUSD files read and written, with
[cadmpeg](https://github.com/cadmpeg/cadmpeg) 0.6.12 (Apache-2.0), linked as the crates `cadmpeg-core`,
`cadmpeg-ir`, `cadmpeg-registry`, `cadmpeg-container`, `cadmpeg-codec-freecad`, `cadmpeg-codec-rhino`,
`cadmpeg-codec-step`, `cadmpeg-codec-usd` and `cadmpeg-tessellate`
Expand Down
44 changes: 44 additions & 0 deletions assets/locales/pending/rhino-export.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
{
"ar": {
"ui.export_3dm": "تصدير Rhino"
},
"ca": {
"ui.export_3dm": "Exportar Rhino"
},
"de": {
"ui.export_3dm": "Als Rhino exportieren"
},
"en": {
"ui.export_3dm": "Export Rhino"
},
"es": {
"ui.export_3dm": "Exportar Rhino"
},
"he": {
"ui.export_3dm": "ייצוא Rhino"
},
"ja": {
"ui.export_3dm": "Rhino をエクスポート"
},
"ka": {
"ui.export_3dm": "Rhino ექსპორტი"
},
"ko": {
"ui.export_3dm": "Rhino 내보내기"
},
"lv": {
"ui.export_3dm": "Eksportēt Rhino"
},
"pl": {
"ui.export_3dm": "Eksportuj Rhino"
},
"uk": {
"ui.export_3dm": "Експорт Rhino"
},
"vi": {
"ui.export_3dm": "Xuất tệp Rhino"
},
"zh": {
"ui.export_3dm": "导出 Rhino"
}
}
2 changes: 1 addition & 1 deletion crates/doc/src/joints.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1532,7 +1532,7 @@ pub fn joint_values(asm: &Assembly) -> BTreeMap<u64, Vec<f64>> {
/// unless flipped. Two datum references (a plane or an axis on each side) both point along the
/// geometry's own normal rather than out of a body, so they mate aligned - each part keeps its
/// side of the datum - and `flip` asks for the mated relation.
fn flip_of(j: &Joint) -> Mat {
pub fn flip_of(j: &Joint) -> Mat {
// An angle relation's `angle` is its tilt (`tail`); a perpendicular one has none.
let turn = if matches!(j.kind, JointKind::Angle | JointKind::Perpendicular) { 0.0 } else { j.angle };
let mut m = rot_z(turn);
Expand Down
249 changes: 210 additions & 39 deletions crates/engine/src/cmd/file.rs

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion crates/engine/src/cmd/render.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ mod resources;
mod shots;
mod staging;
mod studio_presets;
mod surface_bindings;
pub(super) mod surface_bindings;
mod surface_resources;
mod textures;
mod transmission;
Expand Down
137 changes: 137 additions & 0 deletions crates/engine/src/cmd/render/surface_bindings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -209,3 +209,140 @@ pub(super) fn unbind(s: &mut Session, params: &Value) -> Result<Value> {
setup.surfaces.remove(&input.target);
publish(s, input.name, setup, command)
}

/// The image textures render setup `name` gives the design's bodies, for an export: one plan per
/// binding, with its maps' bytes. A binding that cannot be read (its target gone, a built-in
/// surface this build lacks or that changed, an image missing) is left out with a warning.
pub(in crate::cmd) fn export_plans(s: &Session, name: &str, command: &str, warnings: &mut Vec<String>) -> Result<Vec<solidcraft_io::SurfacePlan>> {
use solidcraft_render::texture_input::MapRole;
let setup = s.doc.render.setups.get(name).ok_or_else(|| bad(command, format!("there is no render setup named `{name}`")))?;
if setup.surfaces.is_empty() {
return Ok(Vec::new());
}
// A design whose bodies cannot be named for the setup (too many placed bodies for the
// renderer, say) is still exported: its images are left out, with why.
let identities = match targets(s, command) {
Ok(identities) => identities,
Err(e) => {
warnings.push(format!("render setup `{name}`: its images are left out: {e}"));
return Ok(Vec::new());
}
};
let maximum = solidcraft_doc::render_texture_resources::MAX_TEXTURE_BYTES as u64;
// Each image read once and shared by every binding that uses it.
let mut read: BTreeMap<String, Arc<[u8]>> = BTreeMap::new();
let mut map = |sha: String, bytes: &dyn Fn() -> std::result::Result<Vec<u8>, String>| -> std::result::Result<solidcraft_io::SurfaceMap, String> {
let bytes = match read.get(&sha) {
Some(b) => b.clone(),
None => {
let b: Arc<[u8]> = Arc::from(bytes()?);
read.insert(sha.clone(), b.clone());
b
}
};
Ok(solidcraft_io::SurfaceMap { sha256: sha, bytes })
};
let mut plans = Vec::new();
for binding in setup.surfaces.iter() {
let Some(world) = identities.get(&binding.target) else {
warnings.push(format!("render setup `{name}`: a surface's body is gone or changed: left out"));
continue;
};
let mut plan = solidcraft_io::SurfacePlan {
setup: name.to_string(),
definition: binding.target.definition.clone(),
component: binding.target.component,
path: binding.target.occurrence_path.clone(),
world: world.clone(),
origin: binding.local_frame.origin,
u: binding.local_frame.u,
v: binding.local_frame.v,
flip_v: true,
normal_strength: binding.normal_strength,
base_color: None,
normal: None,
roughness: None,
metallic: None,
};
let outcome = match &binding.source {
SurfaceSource::Builtin(builtin) => (|| {
if !cfg!(feature = "bundled-render-library") {
return Err(format!("this build has no built-in surface images, so `{}` is written without them", builtin.id));
}
if source(&builtin.id, command).ok().as_ref() != Some(builtin) {
return Err(format!("built-in surface `{}` differs from the installed one: written without its images", builtin.id));
}
let bytes = |role: MapRole, file: &str| {
super::library::texture_bytes(&format!("{}/{file}", builtin.id), role, maximum, command).map_err(|e| e.to_string())
};
plan.base_color = Some(map(builtin.base_color_sha256.to_string(), &|| bytes(MapRole::BaseColor, "base_color"))?);
plan.normal = Some(map(builtin.normal_sha256.to_string(), &|| bytes(MapRole::NormalOpenGl, "normal_open_gl"))?);
plan.roughness = Some(map(builtin.roughness_sha256.to_string(), &|| bytes(MapRole::Roughness, "roughness"))?);
plan.metallic = Some(map(builtin.metallic_sha256.to_string(), &|| bytes(MapRole::Metallic, "metallic"))?);
Ok(())
})(),
SurfaceSource::Embedded(embedded) => (|| {
plan.flip_v = embedded.flip_v;
let resources = &s.doc.render.texture_resources;
let mut bytes = |id: Option<HdrId>| -> std::result::Result<Option<solidcraft_io::SurfaceMap>, String> {
id.map(|id| map(id.to_string(), &|| resources.required(&id).map(|r| r.bytes().to_vec()).map_err(|e| e.to_string()))).transpose()
};
plan.base_color = bytes(embedded.base_color)?;
plan.normal = bytes(embedded.normal_open_gl)?;
plan.roughness = bytes(embedded.roughness)?;
plan.metallic = bytes(embedded.metallic)?;
Ok(())
})(),
};
match outcome {
Ok(()) => plans.push(plan),
Err(e) => warnings.push(format!("{world}: render setup `{name}`: {e}")),
}
}
Ok(plans)
}

/// The optics render setup `name` gives the design's bodies, for an export: one plan per binding.
/// What the export cannot write (a glass model, subsurface scattering, transmissive shadows) is a
/// warning naming the body; a binding whose body is gone is left out with a warning.
pub(in crate::cmd) fn optics_plans(s: &Session, name: &str, command: &str, warnings: &mut Vec<String>) -> Result<Vec<solidcraft_io::OpticsPlan>> {
let Some(setup) = s.doc.render.setups.get(name) else { return Ok(Vec::new()) };
if setup.optics.is_empty() {
return Ok(Vec::new());
}
let identities = match targets(s, command) {
Ok(identities) => identities,
Err(e) => {
warnings.push(format!("render setup `{name}`: its optics are not written: {e}"));
return Ok(Vec::new());
}
};
let mut plans = Vec::new();
for binding in setup.optics.iter() {
let Some(world) = identities.get(&binding.target) else {
warnings.push(format!("render setup `{name}`: a body given optics is gone or changed: left out"));
continue;
};
let optics = &binding.optics;
for (unwritten, what) in [
(optics.model.is_some(), "its glass model"),
(optics.subsurface.is_some(), "its subsurface scattering"),
(optics.shadow_transmission, "its transmissive shadows"),
] {
if unwritten {
warnings.push(format!("{world}: render setup `{name}`: {what} has no OpenUSD form here: left out"));
}
}
plans.push(solidcraft_io::OpticsPlan {
setup: name.to_string(),
definition: binding.target.definition.clone(),
component: binding.target.component,
path: binding.target.occurrence_path.clone(),
world: world.clone(),
ior: optics.ior,
absorption_per_mm: optics.absorption_per_mm,
thin_sheet: optics.boundary == solidcraft_doc::render_optics::OpticalBoundary::ThinSheet,
});
}
Ok(plans)
}
70 changes: 65 additions & 5 deletions crates/engine/src/schema/file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -172,15 +172,15 @@ pub struct ExportParams {
/// The file to write.
#[serde(default)]
pub path: Option<String>,
/// The format: stl, stla, obj, step, 3mf, 3mf-tagged, glb, urdf, sdf or json, or a file name
/// whose extension names it. Default: from the path's extension.
/// The format: stl, stla, obj, step, 3mf, 3mf-tagged, glb, usd, 3dm, urdf, sdf or json, or a
/// file name whose extension names it. Default: from the path's extension.
#[serde(default)]
pub format: Option<String>,
/// The bodies to export, by name. Default: every body. Design JSON and URDF export the
/// complete design, so they refuse a list.
#[serde(default)]
pub bodies: Option<StringList>,
/// How closely the mesh follows curved faces (STL, OBJ, 3MF and GLB). Default: standard. Not read
/// How closely the mesh follows curved faces (STL, OBJ, 3MF, GLB, OpenUSD and Rhino). Default: standard. Not read
/// for URDF.
#[serde(default)]
pub quality: Option<MeshQualityParam>,
Expand All @@ -197,13 +197,32 @@ pub struct ExportParams {
/// URDF only: each joint's velocity limit, a positive number. Default: 10.
#[serde(default)]
pub velocity: Option<f64>,
/// URDF only: also write each picture shown on the model as a textured visual. Default: false.
/// URDF and OpenUSD only: also write each picture shown on the model as a textured visual
/// (OpenUSD: in a `.usdz` package). Default: false.
#[serde(default)]
pub images: Option<bool>,
/// STL and 3MF only: true writes each body with a print face laid on it, as
/// `file.export_stl` has it; refused for the other formats. Default: false. Not read for URDF.
#[serde(default)]
pub lay_on_print_faces: Option<bool>,
/// OpenUSD only: also write the joints, the grounded placements and each component's mass as
/// OpenUSD physics, for a simulator. Default: false.
#[serde(default)]
pub physics: Option<bool>,
/// OpenUSD only: what the file is for. `interchange` (for another CAD program: each body's
/// exact shape beside its mesh) or `distribution` (for a viewer or a game engine: meshes only,
/// with the pictures shown on the model). `exact_brep` and `images` override it. Default:
/// interchange.
#[serde(default)]
pub purpose: Option<String>,
/// OpenUSD only: write each body's exact shape (B-rep) beside its mesh. Default: from
/// `purpose` (true for interchange, false for distribution).
#[serde(default)]
pub exact_brep: Option<bool>,
/// OpenUSD only: the saved render setup whose image textures a `.usdz` package holds.
/// Default: none, each body written with its look.
#[serde(default)]
pub render_setup: Option<String>,
/// SDF only: the model's name. Default: the folder's name.
#[serde(default)]
pub name: Option<String>,
Expand Down Expand Up @@ -285,6 +304,10 @@ impl<'de> Deserialize<'de> for ExportParams {
velocity: None,
images: None,
lay_on_print_faces: None,
physics: None,
render_setup: None,
purpose: None,
exact_brep: None,
name: None,
is_static: None,
model_uris: None,
Expand All @@ -302,6 +325,36 @@ impl<'de> Deserialize<'de> for ExportParams {
return Ok(out);
};
out.bodies = names::<D::Error>(&m)?;
// Read before URDF and SDF read their own keys, as the handler reads them.
out.physics = match m.get("physics") {
None | Some(Value::Null) => None,
Some(Value::Bool(false)) => Some(false),
Some(Value::Bool(true)) if format == Format::Usd => Some(true),
Some(Value::Bool(true)) => {
return Err(refuse("`physics` is for OpenUSD: URDF and SDF always write their joints and masses, and the other formats hold none"));
}
Some(_) => return Err(refuse("`physics` must be true or false")),
};
out.render_setup = match m.get("render_setup") {
None | Some(Value::Null) => None,
Some(Value::String(n)) if format == Format::Usd && !n.trim().is_empty() => Some(n.clone()),
Some(Value::String(_)) if format == Format::Usd => return Err(refuse("`render_setup` must name a render setup")),
Some(Value::String(_)) => return Err(refuse("`render_setup` is for OpenUSD: other formats written here hold no image textures")),
Some(_) => return Err(refuse("`render_setup` must be the name of a render setup")),
};
// Read before URDF and SDF return, so neither takes an OpenUSD option silently.
out.purpose = match m.get("purpose") {
None | Some(Value::Null) => None,
Some(_) if format != Format::Usd => return Err(refuse("`purpose` is for OpenUSD: other formats written here have one form")),
Some(Value::String(s)) if s == "interchange" || s == "distribution" => Some(s.clone()),
Some(_) => return Err(refuse("`purpose` must be interchange or distribution")),
};
out.exact_brep = match m.get("exact_brep") {
None | Some(Value::Null) => None,
Some(Value::Bool(b)) if format == Format::Usd => Some(*b),
Some(Value::Bool(_)) => return Err(refuse("`exact_brep` is for OpenUSD: other formats written here choose their own")),
Some(_) => return Err(refuse("`exact_brep` must be true or false")),
};
if format == Format::Urdf {
// URDF reads its own keys; `quality` and `objects` are not read.
out.mesh_prefix = text::<D::Error>(&m, "mesh_prefix")?;
Expand Down Expand Up @@ -341,6 +394,12 @@ impl<'de> Deserialize<'de> for ExportParams {
_ => return Err(refuse(format!("`objects` must be body or component, not {v}"))),
},
};
if format == Format::Usd {
out.images = match m.get("images") {
None | Some(Value::Null) => None,
Some(v) => Some(v.as_bool().ok_or_else(|| refuse::<D::Error>("`images` must be true or false"))?),
};
}
out.lay_on_print_faces = match m.get("lay_on_print_faces") {
None | Some(Value::Null) => None,
Some(Value::Bool(false)) => Some(false),
Expand All @@ -360,7 +419,8 @@ pub struct ExportResult {
/// Its size in bytes.
pub bytes: usize,
/// The format written: Step, StlBinary, ThreeMf or Obj (and for `file.export` and
/// `file.save_mesh` also StlAscii or ThreeMfTagged, and for `file.export` also Design and Glb).
/// `file.save_mesh` also StlAscii or ThreeMfTagged, and for `file.export` also Design, Glb, Usd
/// and Rhino).
pub format: String,
/// OBJ only: every file written, the material library first and the mesh file last.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
Expand Down
32 changes: 32 additions & 0 deletions crates/engine/src/schema/file_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ fn schemas_and_the_key_check_agree() {
&[
"bodies",
"effort",
"exact_brep",
"format",
"images",
"lay_on_print_faces",
Expand All @@ -33,7 +34,10 @@ fn schemas_and_the_key_check_agree() {
"name",
"objects",
"path",
"physics",
"purpose",
"quality",
"render_setup",
"static",
"velocity",
],
Expand Down Expand Up @@ -344,6 +348,11 @@ fn strict_keeps_todays_errors() {
("file.export", json!({"path": at("a.obj"), "lay_on_print_faces": true})),
("file.export", json!({"path": at("a.stl"), "lay_on_print_faces": "yes"})),
("file.export", json!({"path": at("a.3mf"), "lay_on_print_faces": 1})),
("file.export", json!({"path": at("a.urdf"), "physics": true})),
("file.export", json!({"path": at("a.sdf"), "physics": "yes"})),
("file.export", json!({"path": at("a.step"), "physics": true})),
("file.export", json!({"path": at("a.urdf"), "render_setup": "Studio"})),
("file.export", json!({"path": at("a.sdf"), "render_setup": 5})),
("file.export_stl", json!({"path": at("a.stl"), "lay_on_print_faces": "yes"})),
("file.export_3mf", json!({"path": at("a.3mf"), "lay_on_print_faces": [true]})),
("doc.open", json!({"path": ""})),
Expand Down Expand Up @@ -398,6 +407,29 @@ fn the_export_type_reads_each_key_only_for_its_format() {
assert!(e.contains("must be true or false"), "{e}");
}

/// OpenUSD's `purpose` and `exact_brep` are refused for every other format, URDF, SDF and laid-out
/// prints included, by the type and by the handler alike.
#[test]
fn openusd_only_options_are_refused_for_every_other_format() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10}));
let calls = [
(json!({"path": "robot.urdf", "purpose": "distribution"}), "`purpose` is for OpenUSD"),
(json!({"path": "world.sdf", "purpose": "interchange"}), "`purpose` is for OpenUSD"),
(json!({"path": "robot.urdf", "exact_brep": true}), "`exact_brep` is for OpenUSD"),
(json!({"path": "part.step", "exact_brep": false}), "`exact_brep` is for OpenUSD"),
(json!({"path": "part.stl", "lay_on_print_faces": true, "exact_brep": false}), "`exact_brep` is for OpenUSD"),
];
for (p, says) in calls {
let typed = serde_json::from_value::<ExportParams>(p.clone()).expect_err("the type refuses").to_string();
assert!(typed.contains(says), "{p}: {typed}");
let handled = s.execute("file.export", &p).expect_err("the handler refuses").to_string();
assert!(handled.contains(says), "{p}: {handled}");
}
// Absent or null, they are the defaults for any format.
assert!(serde_json::from_value::<ExportParams>(json!({"path": "robot.urdf", "purpose": null, "exact_brep": null})).is_ok());
}

/// (`conforms` does not read `oneOf`, so `quality` and `objects` values are checked by the type,
/// in `the_export_type_reads_each_key_only_for_its_format`.)
#[test]
Expand Down
Loading