From e007470e16ce223451cea782e9c34ca2fdbaa40a Mon Sep 17 00:00:00 2001 From: Bas <16050771+Basnederveen@users.noreply.github.com> Date: Sun, 1 Nov 2026 10:56:00 +0100 Subject: [PATCH 1/3] feat(exchange): export_step_in for bodies in a unit other than metres export_step takes a body's coordinates as metres and scales them to the file unit. A body built in millimetres had no way to say so: exporting it as millimetres multiplied every coordinate by 1000 (a 100 mm plate came out 100 m wide). export_step_in(brep, model_unit, unit) takes the unit the body is built in ("metre" or "millimetre") and scales from it to the file unit once. export_step keeps its behaviour and delegates with model_unit = "metre". The scale is a fixed table, so metre bodies export the same digits as before. export_bodies takes the model unit; the world graph passes "metre". Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VFZvqx1RmXzPtbL9VXP4H7 --- main/opengeometry/src/exchange/mod.rs | 4 ++- main/opengeometry/src/exchange/step/mod.rs | 37 ++++++++++++++------ main/opengeometry/src/exchange/step/tests.rs | 36 ++++++++++++++++++- main/opengeometry/src/world_graph/export.rs | 1 + 4 files changed, 66 insertions(+), 12 deletions(-) diff --git a/main/opengeometry/src/exchange/mod.rs b/main/opengeometry/src/exchange/mod.rs index 346095bb..4793eddb 100644 --- a/main/opengeometry/src/exchange/mod.rs +++ b/main/opengeometry/src/exchange/mod.rs @@ -5,4 +5,6 @@ mod preflight; mod step; pub(super) use step::{export_bodies, StepBodyInput, StepExportFailure}; -pub use step::{export_step, StepBodyReport, StepExportReport, StepReport, StepSkipped}; +pub use step::{ + export_step, export_step_in, StepBodyReport, StepExportReport, StepReport, StepSkipped, +}; diff --git a/main/opengeometry/src/exchange/step/mod.rs b/main/opengeometry/src/exchange/step/mod.rs index 1d5fbeeb..3a03e54e 100644 --- a/main/opengeometry/src/exchange/step/mod.rs +++ b/main/opengeometry/src/exchange/step/mod.rs @@ -15,6 +15,14 @@ use body::{emit_body, BodyEmission}; use product::{emit_context, emit_products, emit_representations}; pub fn export_step(brep: &BrepEnvelope, unit: &str) -> Result<(String, StepReport), GeometryError> { + export_step_in(brep, "metre", unit) +} + +pub fn export_step_in( + brep: &BrepEnvelope, + model_unit: &str, + unit: &str, +) -> Result<(String, StepReport), GeometryError> { let (text, report) = export_bodies( &[StepBodyInput { og_id: &brep.id, @@ -22,6 +30,7 @@ pub fn export_step(brep: &BrepEnvelope, unit: &str) -> Result<(String, StepRepor shape_revision: brep.revision, brep, }], + model_unit, unit, "Y", &brep.id, @@ -50,22 +59,14 @@ pub fn export_step(brep: &BrepEnvelope, unit: &str) -> Result<(String, StepRepor pub(crate) fn export_bodies( bodies: &[StepBodyInput<'_>], + model_unit: &str, unit: &str, up_axis: &str, name: &str, timestamp: &str, skipped: Vec, ) -> Result<(String, StepExportReport), StepExportFailure> { - let scale = match unit { - "metre" => 1.0, - "millimetre" => 1000.0, - _ => { - return Err(GeometryError::InvalidGeometry( - "STEP length unit must be metre or millimetre".into(), - ) - .into()) - } - }; + let scale = unit_scale(model_unit, unit)?; if bodies.is_empty() { return Err( GeometryError::InvalidGeometry("STEP export has no solid bodies".into()).into(), @@ -121,6 +122,22 @@ pub(crate) fn export_bodies( Ok((text, report)) } +fn unit_scale(model_unit: &str, unit: &str) -> Result { + if !matches!(unit, "metre" | "millimetre") { + return Err(GeometryError::InvalidGeometry( + "STEP length unit must be metre or millimetre".into(), + )); + } + match (model_unit, unit) { + ("metre", "millimetre") => Ok(1000.0), + ("millimetre", "metre") => Ok(1e-3), + ("metre" | "millimetre", _) => Ok(1.0), + _ => Err(GeometryError::InvalidGeometry( + "STEP model length unit must be metre or millimetre".into(), + )), + } +} + fn add_bodies( writer: &mut Part21Writer, bodies: &[StepBodyInput<'_>], diff --git a/main/opengeometry/src/exchange/step/tests.rs b/main/opengeometry/src/exchange/step/tests.rs index de60a67d..e00b41f1 100644 --- a/main/opengeometry/src/exchange/step/tests.rs +++ b/main/opengeometry/src/exchange/step/tests.rs @@ -1,4 +1,4 @@ -use super::{export_bodies, export_step, StepBodyInput}; +use super::{export_bodies, export_step, export_step_in, StepBodyInput}; use crate::brep::{ coarse_accuracy, BrepEnvelope, Curve, CurveGeometry, EdgeGeometry, Frame3, GeometryError, IntersectionDefinition, IntersectionSide, PcurveGeometry, Surface, TraceAnchor, @@ -194,6 +194,39 @@ fn rejects_unrepresentable_exchange_and_preserves_large_revisions() { )); } +#[test] +fn a_body_in_millimetres_exports_unscaled_in_millimetres() { + let brep = primitives::cuboid( + "plate".into(), + Frame3::IDENTITY, + [100.0, 50.0, 2.0], + coarse_accuracy(1e-3), + ) + .unwrap(); + let (metres, _) = export_step(&brep, "metre").unwrap(); + let (mm, report) = export_step_in(&brep, "millimetre", "millimetre").unwrap(); + assert_eq!(report.length_unit, "millimetre"); + assert_eq!( + mm.replace("SI_UNIT(.MILLI.,.METRE.)", "SI_UNIT($,.METRE.)"), + metres + ); + let (scaled, _) = export_step(&brep, "millimetre").unwrap(); + assert_ne!(scaled, mm); + let (_, to_metres) = export_step_in(&brep, "millimetre", "metre").unwrap(); + assert_eq!( + to_metres.exchange_error_bound, + report.exchange_error_bound * 1e-3 + ); + assert!(matches!( + export_step_in(&brep, "millimetre", "inch"), + Err(GeometryError::InvalidGeometry(_)) + )); + assert!(matches!( + export_step_in(&brep, "inch", "millimetre"), + Err(GeometryError::InvalidGeometry(_)) + )); +} + #[test] fn two_million_entity_export_is_limit_exceeded() { let brep = primitives::cuboid( @@ -214,6 +247,7 @@ fn two_million_entity_export_is_limit_exceeded() { let failure = export_bodies( &inputs, "metre", + "metre", "Y", "cap", "1970-01-01T00:00:00", diff --git a/main/opengeometry/src/world_graph/export.rs b/main/opengeometry/src/world_graph/export.rs index dda17854..6f8cf915 100644 --- a/main/opengeometry/src/world_graph/export.rs +++ b/main/opengeometry/src/world_graph/export.rs @@ -145,6 +145,7 @@ impl WorldGraph { .collect::>(); export_bodies( &inputs, + "metre", &options.unit, &options.up_axis, &options.name, From 4efe15357839c827c33fa48236c2b29e0bdb41ea Mon Sep 17 00:00:00 2001 From: Bas <16050771+Basnederveen@users.noreply.github.com> Date: Mon, 16 Nov 2026 08:28:21 +0100 Subject: [PATCH 2/3] fix(exchange): exact unit scaling in STEP export and one test per behaviour Each length unit is now its size in millimetres, reduced to a single factor: metre to millimetre still multiplies by 1000 (same digits as before), millimetre to metre divides by 1000 instead of multiplying by 1e-3, and equal units leave coordinates untouched. A 9 mm thickness is written as 0.009 rather than 0.009000000000000001. The millimetre tests build their plate with an accuracy scaled to millimetres and check the written SI_UNIT and corner points. The one combined test is split into five, one per behaviour. Co-Authored-By: Claude Opus 5.5 --- main/opengeometry/src/exchange/step/body.rs | 11 +-- .../src/exchange/step/entities.rs | 13 +-- main/opengeometry/src/exchange/step/mod.rs | 26 ++---- .../opengeometry/src/exchange/step/product.rs | 8 +- main/opengeometry/src/exchange/step/tests.rs | 80 +++++++++++++++---- main/opengeometry/src/exchange/step/unit.rs | 60 ++++++++++++++ 6 files changed, 149 insertions(+), 49 deletions(-) create mode 100644 main/opengeometry/src/exchange/step/unit.rs diff --git a/main/opengeometry/src/exchange/step/body.rs b/main/opengeometry/src/exchange/step/body.rs index 9166646b..626d225d 100644 --- a/main/opengeometry/src/exchange/step/body.rs +++ b/main/opengeometry/src/exchange/step/body.rs @@ -1,6 +1,7 @@ use super::entities::{ bspline_curve, curve, pcurve, placement, point, real, refs, sense, PcurveOnSurface, }; +use super::unit::Scale; use crate::brep::{ BrepEnvelope, CurveGeometry, Edge, EdgeGeometry, GeometryError, Orientation, PcurveGeometry, SurfaceGeometry, @@ -21,7 +22,7 @@ pub(super) struct BodyEmission { struct BodyEntities<'a> { brep: &'a BrepEnvelope, - scale: f64, + scale: Scale, context2: usize, surfaces: &'a [Option], vertices: &'a [usize], @@ -37,7 +38,7 @@ struct EdgeEmission { pub(super) fn emit_body( writer: &mut Part21Writer, brep: &BrepEnvelope, - scale: f64, + scale: Scale, context2: usize, mut exchange_bound: f64, ) -> Result { @@ -85,7 +86,7 @@ pub(super) fn emit_body( fn add_surfaces( writer: &mut Part21Writer, brep: &BrepEnvelope, - scale: f64, + scale: Scale, ) -> Result>, GeometryError> { let mut surfaces = vec![None; brep.geometry.surfaces.len()]; for face in &brep.topology.faces { @@ -120,7 +121,7 @@ fn add_surfaces( Ok(surfaces) } -fn add_vertices(writer: &mut Part21Writer, brep: &BrepEnvelope, scale: f64) -> Vec { +fn add_vertices(writer: &mut Part21Writer, brep: &BrepEnvelope, scale: Scale) -> Vec { brep.topology .vertices .iter() @@ -205,7 +206,7 @@ fn add_fitted_curve( brep: &BrepEnvelope, definition: u32, fitting_budget: f64, - scale: f64, + scale: Scale, fitting_error: &mut f64, ) -> Result<(usize, FittedIntersectionCurve), GeometryError> { if fitting_budget <= 0.0 { diff --git a/main/opengeometry/src/exchange/step/entities.rs b/main/opengeometry/src/exchange/step/entities.rs index b8d863b7..0b9a7eaf 100644 --- a/main/opengeometry/src/exchange/step/entities.rs +++ b/main/opengeometry/src/exchange/step/entities.rs @@ -1,3 +1,4 @@ +use super::unit::Scale; use crate::brep::{ CurveGeometry, Frame3, GeometryError, Orientation, PcurveGeometry, SurfaceGeometry, }; @@ -22,7 +23,7 @@ pub(super) fn sense(value: Orientation) -> &'static str { pub(super) fn curve( writer: &mut Part21Writer, geometry: &CurveGeometry, - scale: f64, + scale: Scale, ) -> Result { Ok(match geometry { CurveGeometry::Line { origin, direction } => line( @@ -91,7 +92,7 @@ fn direction(writer: &mut Part21Writer, value: &[f64]) -> usize { value.iter().map(|v| real(*v)).collect::>().join(",") )) } -pub(super) fn placement(writer: &mut Part21Writer, frame: Frame3, scale: f64) -> usize { +pub(super) fn placement(writer: &mut Part21Writer, frame: Frame3, scale: Scale) -> usize { let p = point(writer, &frame.origin.map(|v| v * scale)); let z = direction(writer, &frame.z); let x = direction(writer, &frame.x); @@ -102,7 +103,7 @@ pub(super) fn pcurve( writer: &mut Part21Writer, on_surface: &PcurveOnSurface<'_>, context: usize, - scale: f64, + scale: Scale, lift: [i32; 2], fitted: Option<&FittedIntersectionCurve>, ) -> Result { @@ -112,9 +113,9 @@ pub(super) fn pcurve( surface_id, } = *on_surface; let metric = match surface { - SurfaceGeometry::Plane { .. } => [scale, scale], - SurfaceGeometry::Cylinder { .. } => [1.0, scale], - SurfaceGeometry::Cone { semi_angle, .. } => [1.0, scale / semi_angle.cos()], + SurfaceGeometry::Plane { .. } => [scale.ratio(); 2], + SurfaceGeometry::Cylinder { .. } => [1.0, scale.ratio()], + SurfaceGeometry::Cone { semi_angle, .. } => [1.0, scale.ratio() / semi_angle.cos()], _ => [1.0, 1.0], }; let period = match surface { diff --git a/main/opengeometry/src/exchange/step/mod.rs b/main/opengeometry/src/exchange/step/mod.rs index 3a03e54e..42bac839 100644 --- a/main/opengeometry/src/exchange/step/mod.rs +++ b/main/opengeometry/src/exchange/step/mod.rs @@ -4,6 +4,7 @@ mod product; mod report; #[cfg(test)] mod tests; +mod unit; pub(crate) use report::{StepBodyInput, StepExportFailure}; pub use report::{StepBodyReport, StepExportReport, StepReport, StepSkipped}; @@ -13,6 +14,7 @@ use crate::brep::{BrepEnvelope, GeometryError}; use crate::exchange::part21::Part21Writer; use body::{emit_body, BodyEmission}; use product::{emit_context, emit_products, emit_representations}; +use unit::Scale; pub fn export_step(brep: &BrepEnvelope, unit: &str) -> Result<(String, StepReport), GeometryError> { export_step_in(brep, "metre", unit) @@ -66,7 +68,7 @@ pub(crate) fn export_bodies( timestamp: &str, skipped: Vec, ) -> Result<(String, StepExportReport), StepExportFailure> { - let scale = unit_scale(model_unit, unit)?; + let scale = Scale::between(model_unit, unit)?; if bodies.is_empty() { return Err( GeometryError::InvalidGeometry("STEP export has no solid bodies".into()).into(), @@ -122,31 +124,15 @@ pub(crate) fn export_bodies( Ok((text, report)) } -fn unit_scale(model_unit: &str, unit: &str) -> Result { - if !matches!(unit, "metre" | "millimetre") { - return Err(GeometryError::InvalidGeometry( - "STEP length unit must be metre or millimetre".into(), - )); - } - match (model_unit, unit) { - ("metre", "millimetre") => Ok(1000.0), - ("millimetre", "metre") => Ok(1e-3), - ("metre" | "millimetre", _) => Ok(1.0), - _ => Err(GeometryError::InvalidGeometry( - "STEP model length unit must be metre or millimetre".into(), - )), - } -} - fn add_bodies( writer: &mut Part21Writer, bodies: &[StepBodyInput<'_>], - scale: f64, + scale: Scale, context2: usize, ) -> Result, StepExportFailure> { let mut emitted = Vec::with_capacity(bodies.len()); for (index, input) in bodies.iter().enumerate() { - let body = preflight(input.brep, scale) + let body = preflight(input.brep, scale.ratio()) .and_then(|initial_bound| emit_body(writer, input.brep, scale, context2, initial_bound)) .map_err(|error| StepExportFailure { body_index: Some(index), @@ -160,7 +146,7 @@ fn add_bodies( fn step_body_reports( bodies: &[StepBodyInput<'_>], emitted: &[BodyEmission], - scale: f64, + scale: Scale, ) -> Vec { bodies .iter() diff --git a/main/opengeometry/src/exchange/step/product.rs b/main/opengeometry/src/exchange/step/product.rs index ee5b42f4..fc49f514 100644 --- a/main/opengeometry/src/exchange/step/product.rs +++ b/main/opengeometry/src/exchange/step/product.rs @@ -1,8 +1,14 @@ use super::body::BodyEmission; use super::entities::{real, refs}; +use super::unit::Scale; use crate::exchange::part21::{sanitize_string_literal, Part21Writer}; -pub(super) fn emit_context(writer: &mut Part21Writer, unit: &str, bound: f64, scale: f64) -> usize { +pub(super) fn emit_context( + writer: &mut Part21Writer, + unit: &str, + bound: f64, + scale: Scale, +) -> usize { let prefix = if unit == "millimetre" { ".MILLI." } else { "$" }; let length = writer.add_entity(format!( "(LENGTH_UNIT() NAMED_UNIT(*) SI_UNIT({prefix},.METRE.))" diff --git a/main/opengeometry/src/exchange/step/tests.rs b/main/opengeometry/src/exchange/step/tests.rs index e00b41f1..f42bab0e 100644 --- a/main/opengeometry/src/exchange/step/tests.rs +++ b/main/opengeometry/src/exchange/step/tests.rs @@ -1,7 +1,8 @@ +use super::entities::real; use super::{export_bodies, export_step, export_step_in, StepBodyInput}; use crate::brep::{ - coarse_accuracy, BrepEnvelope, Curve, CurveGeometry, EdgeGeometry, Frame3, GeometryError, - IntersectionDefinition, IntersectionSide, PcurveGeometry, Surface, TraceAnchor, + coarse_accuracy, Accuracy, BrepEnvelope, Curve, CurveGeometry, EdgeGeometry, Frame3, + GeometryError, IntersectionDefinition, IntersectionSide, PcurveGeometry, Surface, TraceAnchor, }; use crate::math::Interval; use crate::operations::modifying::boolean::{boolean_spheres, BooleanOp}; @@ -194,35 +195,80 @@ fn rejects_unrepresentable_exchange_and_preserves_large_revisions() { )); } -#[test] -fn a_body_in_millimetres_exports_unscaled_in_millimetres() { - let brep = primitives::cuboid( +fn millimetre_plate() -> BrepEnvelope { + let accuracy = Accuracy { + geometric: 1e-5, + intersection: 1e-6, + tessellation: 10.0, + exchange: 1e-3, + }; + primitives::cuboid( "plate".into(), Frame3::IDENTITY, - [100.0, 50.0, 2.0], - coarse_accuracy(1e-3), + [100.0, 50.0, 9.0], + accuracy, ) - .unwrap(); - let (metres, _) = export_step(&brep, "metre").unwrap(); - let (mm, report) = export_step_in(&brep, "millimetre", "millimetre").unwrap(); + .unwrap() +} + +fn corner(x: f64, y: f64, z: f64) -> String { + format!("CARTESIAN_POINT('',({},{},{}))", real(x), real(y), real(z)) +} + +#[test] +fn millimetre_body_to_millimetre_file_writes_coordinates_unchanged() { + let plate = millimetre_plate(); + let (mm, report) = export_step_in(&plate, "millimetre", "millimetre").unwrap(); assert_eq!(report.length_unit, "millimetre"); + assert!(mm.contains("SI_UNIT(.MILLI.,.METRE.)")); + assert!(mm.contains(&corner(100.0, 50.0, 9.0))); + let (metres, _) = export_step(&plate, "metre").unwrap(); assert_eq!( mm.replace("SI_UNIT(.MILLI.,.METRE.)", "SI_UNIT($,.METRE.)"), metres ); - let (scaled, _) = export_step(&brep, "millimetre").unwrap(); - assert_ne!(scaled, mm); - let (_, to_metres) = export_step_in(&brep, "millimetre", "metre").unwrap(); +} + +#[test] +fn millimetre_body_to_metre_file_scales_by_a_thousandth() { + let plate = millimetre_plate(); + let (metres, report) = export_step_in(&plate, "millimetre", "metre").unwrap(); + assert_eq!(report.length_unit, "metre"); + assert!(metres.contains("SI_UNIT($,.METRE.)")); + assert!(metres.contains(&corner(0.1, 0.05, 0.009))); + let (_, mm) = export_step_in(&plate, "millimetre", "millimetre").unwrap(); assert_eq!( - to_metres.exchange_error_bound, - report.exchange_error_bound * 1e-3 + report.exchange_error_bound, + mm.exchange_error_bound / 1000.0 ); +} + +#[test] +fn metre_body_to_millimetre_file_scales_by_a_thousand() { + let plate = primitives::cuboid( + "plate".into(), + Frame3::IDENTITY, + [1.0, 0.5, 0.25], + Accuracy::STANDARD, + ) + .unwrap(); + let (mm, _) = export_step(&plate, "millimetre").unwrap(); + assert!(mm.contains("SI_UNIT(.MILLI.,.METRE.)")); + assert!(mm.contains(&corner(1000.0, 500.0, 250.0))); +} + +#[test] +fn unknown_file_unit_is_rejected() { assert!(matches!( - export_step_in(&brep, "millimetre", "inch"), + export_step_in(&millimetre_plate(), "millimetre", "inch"), Err(GeometryError::InvalidGeometry(_)) )); +} + +#[test] +fn unknown_model_unit_is_rejected() { assert!(matches!( - export_step_in(&brep, "inch", "millimetre"), + export_step_in(&millimetre_plate(), "inch", "millimetre"), Err(GeometryError::InvalidGeometry(_)) )); } diff --git a/main/opengeometry/src/exchange/step/unit.rs b/main/opengeometry/src/exchange/step/unit.rs new file mode 100644 index 00000000..c90d2626 --- /dev/null +++ b/main/opengeometry/src/exchange/step/unit.rs @@ -0,0 +1,60 @@ +use crate::brep::GeometryError; +use std::ops::Mul; + +#[derive(Clone, Copy)] +pub(super) struct Scale { + times: f64, + per: f64, +} + +impl Scale { + pub(super) fn between(model_unit: &str, unit: &str) -> Result { + let per = millimetres_in(unit).ok_or_else(|| { + GeometryError::InvalidGeometry("STEP length unit must be metre or millimetre".into()) + })?; + let times = millimetres_in(model_unit).ok_or_else(|| { + GeometryError::InvalidGeometry( + "STEP model length unit must be metre or millimetre".into(), + ) + })?; + Ok(if times >= per { + Self { + times: times / per, + per: 1.0, + } + } else { + Self { + times: 1.0, + per: per / times, + } + }) + } + + pub(super) fn ratio(self) -> f64 { + 1.0 * self + } +} + +impl Mul for f64 { + type Output = f64; + + fn mul(self, scale: Scale) -> f64 { + self * scale.times / scale.per + } +} + +impl Mul for &f64 { + type Output = f64; + + fn mul(self, scale: Scale) -> f64 { + *self * scale + } +} + +fn millimetres_in(unit: &str) -> Option { + match unit { + "metre" => Some(1000.0), + "millimetre" => Some(1.0), + _ => None, + } +} From 067bd7d212c5cee118eecc66f7b3144369b23f94 Mon Sep 17 00:00:00 2001 From: Bas <16050771+Basnederveen@users.noreply.github.com> Date: Tue, 17 Nov 2026 07:10:30 +0100 Subject: [PATCH 3/3] feat(exchange): model unit for IFC bodies and world-graph STEP export export_ifc_body_in(brep, model_unit, conversion) scales a body built in millimetres to metres through placed(), with the geometric tolerance, exchange error bound and fitting budget scaled alike; export_ifc_body delegates with "metre". The Scale helper moves from exchange/step to exchange so both exports share it. StepOptions gets modelUnit (default "metre") and WorldGraph::export_ifc_body takes the model unit, so OpenGeometry.exportStep({ modelUnit }) and OpenGeometry.exportIfcBody(node, { modelUnit }) reach it from JavaScript. Metre bodies export exactly as before. Co-Authored-By: Claude Opus 5.5 --- README.md | 4 +- docs/opengeometry/api/export.mdx | 7 +- docs/opengeometry/guides/export-step.mdx | 3 +- .../opengeometry/guides/ifc-exchange-body.mdx | 2 +- .../src/export/export-step.ts | 1 + .../opengeometry-three/src/export/ifc-body.ts | 7 +- main/opengeometry-three/src/opengeometry.ts | 6 +- .../tests/node/export-step.test.mjs | 15 ++++ .../tests/node/ifc-body.test.mjs | 17 ++++ .../src/bindings/world_graph/ifc_body.rs | 9 +- .../opengeometry/src/exchange/ifc_body/mod.rs | 20 +++-- main/opengeometry/src/exchange/mod.rs | 1 + main/opengeometry/src/exchange/step/body.rs | 2 +- .../src/exchange/step/entities.rs | 2 +- main/opengeometry/src/exchange/step/mod.rs | 3 +- .../opengeometry/src/exchange/step/product.rs | 2 +- .../src/exchange/{step => }/unit.rs | 4 +- main/opengeometry/src/world_graph/export.rs | 5 +- .../src/world_graph/export_ifc.rs | 28 ++++-- .../tests/step_oracle/ifc_body.rs | 86 +++++++++++++++---- main/opengeometry/tests/step_oracle/placed.rs | 38 ++++++++ 21 files changed, 213 insertions(+), 49 deletions(-) rename main/opengeometry/src/exchange/{step => }/unit.rs (90%) diff --git a/README.md b/README.md index d4b00699..b3bc55be 100644 --- a/README.md +++ b/README.md @@ -168,8 +168,8 @@ This is a compact reference for writing OpenGeometry 3.0 code, by hand or with a | Picking | `OpenGeometry.resolveHit(intersection)` takes a Three.js raycast hit and returns `{ ogId, shapeRevision, faceId?, edgeId? }` or `undefined`. | | `OGMark` | `const mark = OpenGeometry.mark()`, then `mark.rollback()` and `mark.release()`. `OpenGeometry.markStats()` returns `{ liveMarks, retainedRevisions }`. `OpenGeometry.transaction(fn, { dryRun? })` runs a synchronous `fn` and rolls back if it throws. | | Events | `OpenGeometry.on(event, handler)` with `'geometry'`, `'warning'`, `'error'` or `'fatal'`; it returns a function that unsubscribes. | -| STEP | `await OpenGeometry.exportStep({ nodes, unit?, upAxis?, name?, timestamp? })` returns `{ text, report }`. `nodes`: bodies, assemblies or `ogId` strings. `unit`: `'millimetre'` (default) or `'metre'`; `upAxis`: `'Z'` (default) or `'Y'`. | -| IFC body | `OpenGeometry.exportIfcBody(solid)` returns the IFC exchange body (type `AnalyticExchangeBodyV2`): `schema_version` 2, world metres, Z up, `representation_type` `'AdvancedBrep'` or `'CSG'` for a solid with a cavity, `entities`, `solids` and `faces`. It refuses a Sheet, a Wire or an assembly. | +| STEP | `await OpenGeometry.exportStep({ nodes, unit?, modelUnit?, upAxis?, name?, timestamp? })` returns `{ text, report }`. `nodes`: bodies, assemblies or `ogId` strings. `unit`: `'millimetre'` (default) or `'metre'`, the unit of the file; `modelUnit`: `'metre'` (default) or `'millimetre'`, the unit the bodies are built in; `upAxis`: `'Z'` (default) or `'Y'`. | +| IFC body | `OpenGeometry.exportIfcBody(solid, { modelUnit? })` returns the IFC exchange body (type `AnalyticExchangeBodyV2`): `schema_version` 2, world metres, Z up (`modelUnit: 'millimetre'` for a body built in millimetres), `representation_type` `'AdvancedBrep'` or `'CSG'` for a solid with a cavity, `entities`, `solids` and `faces`. It refuses a Sheet, a Wire or an assembly. | | 2D regions | `OpenGeometry.booleanRegions2D(a, b, operation)` and `OpenGeometry.booleanCurvedRegions2D(a, b, operation)` with `'union'`, `'intersection'` or `'subtraction'`. A region is `{ outer, holes }`: an outer ring and a list of hole rings, each ring of `{ x, y, z }` points at one height (type `OffsetRegion`) or of line and arc edges (type `CurvedRegion2D`). Outer rings run clockwise in XZ and holes counter-clockwise. A plain ring is not a region and throws `InvalidParameter`; the tolerance is `OG_REGION_TOLERANCE`. | | 2D offsets | `OpenGeometry.offsetRingVariable(ring, distances, holes?)` insets a closed ring by one distance per edge, each hole `{ ring, distances }` grown by its own; `OpenGeometry.offsetCurvedRingVariable(region, distances, holeDistances?)` insets one `CurvedRegion2D` of lines and arcs by one distance (>= 0) per edge, one list per hole, each arc kept on its centre at its own distance and refused when that distance passes the centre; `OpenGeometry.offsetPolylineRegions(path, width, closed, miterLimit?)` strokes a path. Both return `CurvedRegion2D[]` with exact arcs. `OpenGeometry.insetCurvedRegion2D(region, distance)` insets one `CurvedRegion2D` by a distance above zero, holes grown by the same, and returns `CurvedRegion2D[]` of exact lines and arcs: each arc keeps its centre and a reflex corner rounds to an arc of the distance; an inset past the half width is an empty list. `OpenGeometry.offsetPolyline(path, distance, { acuteThresholdDegrees?, bevel?, closed? })` offsets a path to one side and returns `{ edges, bevelled, closed }` (type `OffsetPath2D`). Rings and paths are flat `[x, y, z, ...]` lists; `y` is ignored. | | `OGError` | Failures throw an `OGError` with `code` (for example `InvalidParameter`, `SharedShape`, `Disposed`), `call`, `message` and `details`. | diff --git a/docs/opengeometry/api/export.mdx b/docs/opengeometry/api/export.mdx index 16723934..0ff48a88 100644 --- a/docs/opengeometry/api/export.mdx +++ b/docs/opengeometry/api/export.mdx @@ -12,6 +12,7 @@ icon: file-export | ----------- | -------------------------------------- | ---------------- | | `nodes` | `(Body \| SystemAssembly \| string)[]` | required | | `unit` | `'millimetre' \| 'metre'` | `'millimetre'` | +| `modelUnit` | `'metre' \| 'millimetre'` | `'metre'` | | `upAxis` | `'Z' \| 'Y'` | `'Z'` | | `name` | `string` | none | | `timestamp` | `string` | the current time | @@ -29,13 +30,15 @@ icon: file-export | `bodies` | One entry per body: its `ogId`, shape and counts | | `skipped` | `{ ogId, reason }` for each node that was not written | +`unit` is the unit of the file and `modelUnit` the unit the bodies are built in. A body built in millimetres and written to millimetres keeps its numbers. + A wire or a sheet on its own throws `InvalidOperand`. A selection with no solid throws `EmptyResult`. See [Export STEP](/opengeometry/guides/export-step). ## exportIfcBody -`static exportIfcBody(node: Body | SystemAssembly): AnalyticExchangeBodyV2` +`static exportIfcBody(node: Body | SystemAssembly, options?: { modelUnit?: 'metre' | 'millimetre' }): AnalyticExchangeBodyV2` -Returns the exact geometry of one solid, in world metres with Z up. A sheet, a wire or an assembly throws. +Returns the exact geometry of one solid, in world metres with Z up. `modelUnit` (default `'metre'`) is the unit the body is built in; a body built in millimetres is scaled to metres. A sheet, a wire or an assembly throws. ```ts import { diff --git a/docs/opengeometry/guides/export-step.mdx b/docs/opengeometry/guides/export-step.mdx index 7af0c84c..da5aa9bc 100644 --- a/docs/opengeometry/guides/export-step.mdx +++ b/docs/opengeometry/guides/export-step.mdx @@ -9,7 +9,8 @@ icon: file-export | Option | Default | Meaning | | ----------- | ---------------- | -------------------------------------------------------------- | | `nodes` | required | Bodies, assemblies, or `ogId` strings | -| `unit` | `'millimetre'` | `'millimetre'` or `'metre'` | +| `unit` | `'millimetre'` | `'millimetre'` or `'metre'`: the unit of the file | +| `modelUnit` | `'metre'` | `'metre'` or `'millimetre'`: the unit the bodies are built in | | `upAxis` | `'Z'` | `'Z'` or `'Y'`. The model is Y up; the file is Z up by default | | `name` | none | The product name in the file | | `timestamp` | the current time | The time in the file header, for files that must not change | diff --git a/docs/opengeometry/guides/ifc-exchange-body.mdx b/docs/opengeometry/guides/ifc-exchange-body.mdx index 4a983bb7..1e54841d 100644 --- a/docs/opengeometry/guides/ifc-exchange-body.mdx +++ b/docs/opengeometry/guides/ifc-exchange-body.mdx @@ -33,7 +33,7 @@ This prints `AdvancedBrep Z 1 6`. `AnalyticExchangeBodyV2` is a read-only object: - `schema_version`: `2`. -- World metres, with Z up. +- World metres, with Z up. For a body built in millimetres, pass `{ modelUnit: 'millimetre' }` and the numbers are scaled to metres. - `representation_type`: `'AdvancedBrep'`, or `'CSG'` for a solid with a cavity. - `entities`, `solids` and `faces`: the geometry and topology for the writer. Values are of type `IfcPreparedValue`. diff --git a/main/opengeometry-three/src/export/export-step.ts b/main/opengeometry-three/src/export/export-step.ts index 1e839084..4a17c1d7 100644 --- a/main/opengeometry-three/src/export/export-step.ts +++ b/main/opengeometry-three/src/export/export-step.ts @@ -12,6 +12,7 @@ const LABEL = 'OpenGeometry.exportStep'; export function exportStep(options: { nodes: (Body | SystemAssembly | string)[]; unit?: 'metre' | 'millimetre'; + modelUnit?: 'metre' | 'millimetre'; upAxis?: 'Y' | 'Z'; name?: string; timestamp?: string; diff --git a/main/opengeometry-three/src/export/ifc-body.ts b/main/opengeometry-three/src/export/ifc-body.ts index 900f0817..2e64b6e0 100644 --- a/main/opengeometry-three/src/export/ifc-body.ts +++ b/main/opengeometry-three/src/export/ifc-body.ts @@ -9,10 +9,13 @@ import { checkHandle, worldGraph } from '../world-graph/world-graph-client'; const LABEL = 'OpenGeometry.exportIfcBody'; -export function exportIfcBody(node: Body | SystemAssembly): AnalyticExchangeBodyV2 { +export function exportIfcBody( + node: Body | SystemAssembly, + options: { modelUnit?: 'metre' | 'millimetre' } = {}, +): AnalyticExchangeBodyV2 { if (!(node instanceof SystemAssembly) && runtime().bodies.get(bodyKey(node.handle, node.generation)) !== node) { throw new OGError('Disposed', LABEL, `${node.ogId} is not a live body`); } checkHandle(LABEL, node); - return decodeIfcBody(call(LABEL, () => worldGraph().exportIfcBody(node.ogId)), LABEL); + return decodeIfcBody(call(LABEL, () => worldGraph().exportIfcBody(node.ogId, options.modelUnit ?? 'metre')), LABEL); } diff --git a/main/opengeometry-three/src/opengeometry.ts b/main/opengeometry-three/src/opengeometry.ts index a72e1b4b..e3dc2e99 100644 --- a/main/opengeometry-three/src/opengeometry.ts +++ b/main/opengeometry-three/src/opengeometry.ts @@ -74,12 +74,16 @@ export class OpenGeometry { static exportStep(options: { nodes: (Body | SystemAssembly | string)[]; unit?: 'metre' | 'millimetre'; + modelUnit?: 'metre' | 'millimetre'; upAxis?: 'Y' | 'Z'; name?: string; timestamp?: string; }): Promise { return exportStep(options); } - static exportIfcBody(node: Body | SystemAssembly): AnalyticExchangeBodyV2 { return exportIfcBody(node); } + static exportIfcBody( + node: Body | SystemAssembly, + options: { modelUnit?: 'metre' | 'millimetre' } = {}, + ): AnalyticExchangeBodyV2 { return exportIfcBody(node, options); } static booleanRegions2D( a: readonly OffsetRegion[], diff --git a/main/opengeometry-three/tests/node/export-step.test.mjs b/main/opengeometry-three/tests/node/export-step.test.mjs index 56226c2f..cd204955 100644 --- a/main/opengeometry-three/tests/node/export-step.test.mjs +++ b/main/opengeometry-three/tests/node/export-step.test.mjs @@ -39,3 +39,18 @@ test('a body from a reset runtime rejects with Disposed', async () => { cuboid('reset-export'); assert(failsWith('Disposed')(await rejection(OpenGeometry.exportStep({ nodes: [stale] })))); }); + +test('exportStep of a millimetre model to millimetres writes the metre digits', async () => { + await boot(); + const body = cuboid('step-millimetre', 100); + const timestamp = '2026-01-01T00:00:00'; + const millimetre = await OpenGeometry.exportStep({ + nodes: [body], unit: 'millimetre', modelUnit: 'millimetre', timestamp, + }); + const metre = await OpenGeometry.exportStep({ nodes: [body], unit: 'metre', modelUnit: 'metre', timestamp }); + assert.equal(millimetre.report.unit, 'millimetre'); + assert.equal(millimetre.text.replace('SI_UNIT(.MILLI.,.METRE.)', 'SI_UNIT($,.METRE.)'), metre.text); + const inch = Reflect.apply(OpenGeometry.exportStep, OpenGeometry, [{ nodes: [body], modelUnit: 'inch' }]); + assert(failsWith('InvalidParameter')(await rejection(inch))); + body.dispose(); +}); diff --git a/main/opengeometry-three/tests/node/ifc-body.test.mjs b/main/opengeometry-three/tests/node/ifc-body.test.mjs index bcbd1117..a011a31c 100644 --- a/main/opengeometry-three/tests/node/ifc-body.test.mjs +++ b/main/opengeometry-three/tests/node/ifc-body.test.mjs @@ -95,3 +95,20 @@ test('exportIfcBody leaves revision, changes, mark stats and getBrep unchanged', assert.equal(state(), before); body.dispose(); }); + +test('exportIfcBody of a millimetre model writes a thousandth of the metre numbers', async () => { + await boot(); + const body = cuboid('ifc-millimetre', 100); + const metre = points(OpenGeometry.exportIfcBody(body)); + const millimetre = OpenGeometry.exportIfcBody(body, { modelUnit: 'millimetre' }); + assert.equal(millimetre.length_unit, 'metre'); + assert.equal(points(millimetre).length, metre.length); + points(millimetre).forEach((point, i) => point.forEach((value, axis) => { + assert(Math.abs(value - metre[i][axis] / 1000) <= 1e-15); + })); + assert.throws( + () => Reflect.apply(OpenGeometry.exportIfcBody, OpenGeometry, [body, { modelUnit: 'inch' }]), + failsWith('InvalidParameter'), + ); + body.dispose(); +}); diff --git a/main/opengeometry/src/bindings/world_graph/ifc_body.rs b/main/opengeometry/src/bindings/world_graph/ifc_body.rs index 07344ded..8efa7c85 100644 --- a/main/opengeometry/src/bindings/world_graph/ifc_body.rs +++ b/main/opengeometry/src/bindings/world_graph/ifc_body.rs @@ -6,7 +6,12 @@ use wasm_bindgen::JsValue; #[wasm_bindgen] impl OGWorldGraph { #[wasm_bindgen(js_name = exportIfcBody)] - pub fn export_ifc_body(&self, og_id: &str) -> Result { - serialise(&self.inner.export_ifc_body(og_id).map_err(errors::json)?) + pub fn export_ifc_body(&self, og_id: &str, model_unit: &str) -> Result { + serialise( + &self + .inner + .export_ifc_body(og_id, model_unit) + .map_err(errors::json)?, + ) } } diff --git a/main/opengeometry/src/exchange/ifc_body/mod.rs b/main/opengeometry/src/exchange/ifc_body/mod.rs index b3313ede..7771c379 100644 --- a/main/opengeometry/src/exchange/ifc_body/mod.rs +++ b/main/opengeometry/src/exchange/ifc_body/mod.rs @@ -5,6 +5,7 @@ mod surfaces; mod topology; use super::preflight::preflight; +use super::unit::Scale; use crate::brep::{placed, BrepEnvelope, FaceProvenance, Frame3, GeometryError, GeometryQuality}; use entities::{Entities, IfcEntity}; use serde::{Deserialize, Serialize}; @@ -40,18 +41,27 @@ pub fn export_ifc_body( input: &BrepEnvelope, conversion: Frame3, ) -> Result { - let preflight_bound = preflight(input, 1.0)?; + export_ifc_body_in(input, "metre", conversion) +} + +pub fn export_ifc_body_in( + input: &BrepEnvelope, + model_unit: &str, + conversion: Frame3, +) -> Result { + let scale = Scale::between(model_unit, "metre")?; + let preflight_bound = preflight(input, scale.ratio())?; check_entity_estimate(input)?; - let mut brep = placed(input, conversion, 1.0)?; + let mut brep = placed(input, conversion, scale.ratio())?; let has_cavities = cavities::reverse_cavities(&mut brep)?; let mut entities = Entities::default(); let surfaces = surfaces::add_surfaces(&mut entities, &brep)?; let edges = curves::add_edges( &mut entities, &brep, - input.accuracy.exchange - preflight_bound, + (input.accuracy.exchange - preflight_bound) * scale, )?; - let exchange_error_bound = preflight_bound + edges.fitting_error; + let exchange_error_bound = preflight_bound * scale + edges.fitting_error; let faces = topology::add_faces(&mut entities, &brep, &surfaces, &edges)?; let solids = topology::add_solids(&mut entities, &brep, &faces, has_cavities); Ok(AnalyticExchangeBodyV2 { @@ -62,7 +72,7 @@ pub fn export_ifc_body( coordinate_space: "world".into(), representation_type: if has_cavities { "CSG" } else { "AdvancedBrep" }.into(), quality: input.quality.clone(), - geometric_tolerance: input.accuracy.geometric, + geometric_tolerance: input.accuracy.geometric * scale, exchange_error_bound, validation_level: "v2 structure, sampled residuals and bounded analytic entity preparation; receiver schema validation required".into(), entities: entities.0, diff --git a/main/opengeometry/src/exchange/mod.rs b/main/opengeometry/src/exchange/mod.rs index 4793eddb..19c1facd 100644 --- a/main/opengeometry/src/exchange/mod.rs +++ b/main/opengeometry/src/exchange/mod.rs @@ -3,6 +3,7 @@ pub mod ifc_body; mod part21; mod preflight; mod step; +mod unit; pub(super) use step::{export_bodies, StepBodyInput, StepExportFailure}; pub use step::{ diff --git a/main/opengeometry/src/exchange/step/body.rs b/main/opengeometry/src/exchange/step/body.rs index 626d225d..45118957 100644 --- a/main/opengeometry/src/exchange/step/body.rs +++ b/main/opengeometry/src/exchange/step/body.rs @@ -1,13 +1,13 @@ use super::entities::{ bspline_curve, curve, pcurve, placement, point, real, refs, sense, PcurveOnSurface, }; -use super::unit::Scale; use crate::brep::{ BrepEnvelope, CurveGeometry, Edge, EdgeGeometry, GeometryError, Orientation, PcurveGeometry, SurfaceGeometry, }; use crate::exchange::fit_curve::{fit_intersection_curve, FittedIntersectionCurve}; use crate::exchange::part21::{sanitize_string_literal, Part21Writer}; +use crate::exchange::unit::Scale; pub(super) struct BodyEmission { pub(super) solids: Vec, diff --git a/main/opengeometry/src/exchange/step/entities.rs b/main/opengeometry/src/exchange/step/entities.rs index 0b9a7eaf..fdbd6c43 100644 --- a/main/opengeometry/src/exchange/step/entities.rs +++ b/main/opengeometry/src/exchange/step/entities.rs @@ -1,9 +1,9 @@ -use super::unit::Scale; use crate::brep::{ CurveGeometry, Frame3, GeometryError, Orientation, PcurveGeometry, SurfaceGeometry, }; use crate::exchange::fit_curve::FittedIntersectionCurve; use crate::exchange::part21::Part21Writer; +use crate::exchange::unit::Scale; use crate::math::{dot, norm}; pub(super) struct PcurveOnSurface<'a> { diff --git a/main/opengeometry/src/exchange/step/mod.rs b/main/opengeometry/src/exchange/step/mod.rs index 42bac839..4cbb4979 100644 --- a/main/opengeometry/src/exchange/step/mod.rs +++ b/main/opengeometry/src/exchange/step/mod.rs @@ -4,17 +4,16 @@ mod product; mod report; #[cfg(test)] mod tests; -mod unit; pub(crate) use report::{StepBodyInput, StepExportFailure}; pub use report::{StepBodyReport, StepExportReport, StepReport, StepSkipped}; use super::preflight::preflight; +use super::unit::Scale; use crate::brep::{BrepEnvelope, GeometryError}; use crate::exchange::part21::Part21Writer; use body::{emit_body, BodyEmission}; use product::{emit_context, emit_products, emit_representations}; -use unit::Scale; pub fn export_step(brep: &BrepEnvelope, unit: &str) -> Result<(String, StepReport), GeometryError> { export_step_in(brep, "metre", unit) diff --git a/main/opengeometry/src/exchange/step/product.rs b/main/opengeometry/src/exchange/step/product.rs index fc49f514..e9e94558 100644 --- a/main/opengeometry/src/exchange/step/product.rs +++ b/main/opengeometry/src/exchange/step/product.rs @@ -1,7 +1,7 @@ use super::body::BodyEmission; use super::entities::{real, refs}; -use super::unit::Scale; use crate::exchange::part21::{sanitize_string_literal, Part21Writer}; +use crate::exchange::unit::Scale; pub(super) fn emit_context( writer: &mut Part21Writer, diff --git a/main/opengeometry/src/exchange/step/unit.rs b/main/opengeometry/src/exchange/unit.rs similarity index 90% rename from main/opengeometry/src/exchange/step/unit.rs rename to main/opengeometry/src/exchange/unit.rs index c90d2626..dea6de45 100644 --- a/main/opengeometry/src/exchange/step/unit.rs +++ b/main/opengeometry/src/exchange/unit.rs @@ -13,9 +13,7 @@ impl Scale { GeometryError::InvalidGeometry("STEP length unit must be metre or millimetre".into()) })?; let times = millimetres_in(model_unit).ok_or_else(|| { - GeometryError::InvalidGeometry( - "STEP model length unit must be metre or millimetre".into(), - ) + GeometryError::InvalidGeometry("model length unit must be metre or millimetre".into()) })?; Ok(if times >= per { Self { diff --git a/main/opengeometry/src/world_graph/export.rs b/main/opengeometry/src/world_graph/export.rs index 6f8cf915..34188cfe 100644 --- a/main/opengeometry/src/world_graph/export.rs +++ b/main/opengeometry/src/world_graph/export.rs @@ -13,6 +13,7 @@ use std::collections::BTreeSet; #[serde(default, rename_all = "camelCase", deny_unknown_fields)] pub struct StepOptions { pub unit: String, + pub model_unit: String, pub up_axis: String, pub name: String, pub timestamp: String, @@ -22,6 +23,7 @@ impl Default for StepOptions { fn default() -> Self { Self { unit: "millimetre".into(), + model_unit: "metre".into(), up_axis: "Z".into(), name: "opengeometry-export".into(), timestamp: "1970-01-01T00:00:00".into(), @@ -111,6 +113,7 @@ impl WorldGraph { )); } if !matches!(options.unit.as_str(), "metre" | "millimetre") + || !matches!(options.model_unit.as_str(), "metre" | "millimetre") || !matches!(options.up_axis.as_str(), "Y" | "Z") || !valid_timestamp(&options.timestamp) || options.name.is_empty() @@ -145,7 +148,7 @@ impl WorldGraph { .collect::>(); export_bodies( &inputs, - "metre", + &options.model_unit, &options.unit, &options.up_axis, &options.name, diff --git a/main/opengeometry/src/world_graph/export_ifc.rs b/main/opengeometry/src/world_graph/export_ifc.rs index c0b4fcc4..0064ab13 100644 --- a/main/opengeometry/src/world_graph/export_ifc.rs +++ b/main/opengeometry/src/world_graph/export_ifc.rs @@ -2,15 +2,29 @@ use super::error::{ErrorCode, ErrorContext, GraphError}; use super::export::up_conversion; use super::graph::WorldGraph; use crate::brep::{BodyType, Similarity3}; -use crate::exchange::ifc_body::{export_ifc_body, AnalyticExchangeBodyV2}; +use crate::exchange::ifc_body::{export_ifc_body_in, AnalyticExchangeBodyV2}; impl WorldGraph { - pub fn export_ifc_body(&self, og_id: &str) -> Result { - self.try_export_ifc_body(og_id) + pub fn export_ifc_body( + &self, + og_id: &str, + model_unit: &str, + ) -> Result { + self.try_export_ifc_body(og_id, model_unit) .map_err(|error| error.in_context(ErrorContext::Export)) } - fn try_export_ifc_body(&self, og_id: &str) -> Result { + fn try_export_ifc_body( + &self, + og_id: &str, + model_unit: &str, + ) -> Result { + if !matches!(model_unit, "metre" | "millimetre") { + return Err(GraphError::code( + ErrorCode::InvalidParameter, + "invalid IFC body model unit", + )); + } if self.shape(og_id)?.brep.body_type()? != BodyType::Solid { return Err(GraphError::code( ErrorCode::InvalidOperand, @@ -21,6 +35,10 @@ impl WorldGraph { .placed_bodies(vec![og_id.into()], Similarity3::IDENTITY)? .pop() .ok_or_else(|| GraphError::code(ErrorCode::InvalidTopology, "body has no shape"))?; - Ok(export_ifc_body(&world, up_conversion("Z").frame)?) + Ok(export_ifc_body_in( + &world, + model_unit, + up_conversion("Z").frame, + )?) } } diff --git a/main/opengeometry/tests/step_oracle/ifc_body.rs b/main/opengeometry/tests/step_oracle/ifc_body.rs index 59ff1b0c..d5a320d7 100644 --- a/main/opengeometry/tests/step_oracle/ifc_body.rs +++ b/main/opengeometry/tests/step_oracle/ifc_body.rs @@ -1,6 +1,8 @@ use crate::support::{fixture_names, fixture_text}; use opengeometry::brep::{Accuracy, BrepEnvelope, Frame3, GeometryError}; -use opengeometry::exchange::ifc_body::{export_ifc_body, AnalyticExchangeBodyV2}; +use opengeometry::exchange::ifc_body::{ + export_ifc_body, export_ifc_body_in, AnalyticExchangeBodyV2, +}; use opengeometry::primitives; use opengeometry::world_graph::{ CreateOptions, CreatingOperation, ErrorCode, Primitive, StepOptions, Transform, WorldGraph, @@ -294,7 +296,7 @@ fn more_than_100_000_estimated_entities_is_limit_exceeded() { named("prism"), ) .unwrap(); - let error = world.export_ifc_body("prism").unwrap_err(); + let error = world.export_ifc_body("prism", "metre").unwrap_err(); assert_eq!(error.error_code(), ErrorCode::LimitExceeded); assert!(error .message() @@ -375,25 +377,11 @@ fn graph_ifc_body_is_world_placed_z_up_and_read_only() { let world = scene(); let revision = world.revision(); let before = state(&world, revision); - let body = world.export_ifc_body("box").unwrap(); + let body = world.export_ifc_body("box", "metre").unwrap(); let value = serde_json::to_value(&body).unwrap(); assert_eq!(value["coordinate_space"], "world"); assert_eq!(value["representation_type"], "AdvancedBrep"); - let points: Vec> = value["entities"] - .as_array() - .unwrap() - .iter() - .filter(|entity| entity["entity_type"] == "IfcCartesianPoint") - .filter_map(|entity| { - let values = entity["attributes"][0]["values"].as_array()?; - (values.len() == 3).then(|| { - values - .iter() - .map(|v| v["value"].as_f64().unwrap()) - .collect() - }) - }) - .collect(); + let points = points(&value); assert!(points.iter().any(|point| point[0] >= 10.5)); assert!(points.iter().any(|point| point[2] >= 3.5)); assert!(points.iter().all(|point| point[1].abs() <= 1.5)); @@ -410,9 +398,69 @@ fn graph_ifc_body_refuses_sheets_wires_assemblies_and_unknown_nodes() { ("missing", ErrorCode::UnknownNode), ] { assert_eq!( - world.export_ifc_body(og_id).unwrap_err().error_code(), + world + .export_ifc_body(og_id, "metre") + .unwrap_err() + .error_code(), code, "{og_id}" ); } } + +fn points(value: &Value) -> Vec> { + value["entities"] + .as_array() + .unwrap() + .iter() + .filter(|entity| entity["entity_type"] == "IfcCartesianPoint") + .filter_map(|entity| { + let values = entity["attributes"][0]["values"].as_array()?; + (values.len() == 3).then(|| { + values + .iter() + .map(|v| v["value"].as_f64().unwrap()) + .collect() + }) + }) + .collect() +} + +#[test] +fn unknown_ifc_body_model_unit_is_rejected() { + let (_, body) = single_body_fixtures().remove(0); + assert!(matches!( + export_ifc_body_in(&body, "inch", Frame3::IDENTITY), + Err(GeometryError::InvalidGeometry(_)) + )); +} + +#[test] +fn graph_ifc_body_of_a_millimetre_model_is_a_thousandth_of_the_metre_body() { + let world = scene(); + let metre = serde_json::to_value(world.export_ifc_body("box", "metre").unwrap()).unwrap(); + let millimetre = + serde_json::to_value(world.export_ifc_body("box", "millimetre").unwrap()).unwrap(); + assert_eq!(millimetre["length_unit"], "metre"); + for field in ["geometric_tolerance", "exchange_error_bound"] { + assert_eq!( + millimetre[field].as_f64().unwrap(), + metre[field].as_f64().unwrap() / 1000.0, + "{field}" + ); + } + let (metre, millimetre) = (points(&metre), points(&millimetre)); + assert_eq!(metre.len(), millimetre.len()); + for (metre, millimetre) in metre.iter().zip(&millimetre) { + for (metre, millimetre) in metre.iter().zip(millimetre) { + assert!((metre / 1000.0 - millimetre).abs() <= 1e-15); + } + } + assert_eq!( + world + .export_ifc_body("box", "inch") + .unwrap_err() + .error_code(), + ErrorCode::InvalidParameter + ); +} diff --git a/main/opengeometry/tests/step_oracle/placed.rs b/main/opengeometry/tests/step_oracle/placed.rs index 2a5f72e3..6f6206f8 100644 --- a/main/opengeometry/tests/step_oracle/placed.rs +++ b/main/opengeometry/tests/step_oracle/placed.rs @@ -130,6 +130,7 @@ fn world_export_applies_z_up_and_escapes_file_name() { fn world_export_handles_far_body_and_rejects_options_without_mutation() { let defaults: StepOptions = serde_json::from_str("{}").unwrap(); assert_eq!(defaults.unit, "millimetre"); + assert_eq!(defaults.model_unit, "metre"); assert_eq!(defaults.up_axis, "Z"); let mut world = graph(); world @@ -157,6 +158,10 @@ fn world_export_handles_far_body_and_rejects_options_without_mutation() { unit: "inch".into(), ..StepOptions::default() }, + StepOptions { + model_unit: "inch".into(), + ..StepOptions::default() + }, StepOptions { up_axis: "X".into(), ..StepOptions::default() @@ -386,3 +391,36 @@ fn circle_extrusion_and_cylinder_edges_are_circles_of_the_source_radius() { } } } + +#[test] +fn world_export_of_a_millimetre_model_to_millimetres_writes_the_metre_digits() { + let mut world = graph(); + world + .create_primitive( + Primitive::Cuboid { + width: 100.0, + height: 9.0, + depth: 50.0, + }, + named("plate"), + ) + .unwrap(); + let export = |model_unit: &str, unit: &str| { + world + .export_step( + &["plate".into()], + &StepOptions { + unit: unit.into(), + model_unit: model_unit.into(), + ..StepOptions::default() + }, + ) + .unwrap() + }; + let (millimetre, _) = export("millimetre", "millimetre"); + let (metre, _) = export("metre", "metre"); + assert_eq!( + millimetre.replace("SI_UNIT(.MILLI.,.METRE.)", "SI_UNIT($,.METRE.)"), + metre + ); +}