Skip to content
Merged
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
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`. |
Expand Down
7 changes: 5 additions & 2 deletions docs/opengeometry/api/export.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand All @@ -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 {
Expand Down
3 changes: 2 additions & 1 deletion docs/opengeometry/guides/export-step.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
2 changes: 1 addition & 1 deletion docs/opengeometry/guides/ifc-exchange-body.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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`.

Expand Down
1 change: 1 addition & 0 deletions main/opengeometry-three/src/export/export-step.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
7 changes: 5 additions & 2 deletions main/opengeometry-three/src/export/ifc-body.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
6 changes: 5 additions & 1 deletion main/opengeometry-three/src/opengeometry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<StepExport> { 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[],
Expand Down
15 changes: 15 additions & 0 deletions main/opengeometry-three/tests/node/export-step.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
});
17 changes: 17 additions & 0 deletions main/opengeometry-three/tests/node/ifc-body.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
});
9 changes: 7 additions & 2 deletions main/opengeometry/src/bindings/world_graph/ifc_body.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<String, JsValue> {
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<String, JsValue> {
serialise(
&self
.inner
.export_ifc_body(og_id, model_unit)
.map_err(errors::json)?,
)
}
}
20 changes: 15 additions & 5 deletions main/opengeometry/src/exchange/ifc_body/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -40,18 +41,27 @@ pub fn export_ifc_body(
input: &BrepEnvelope,
conversion: Frame3,
) -> Result<AnalyticExchangeBodyV2, GeometryError> {
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<AnalyticExchangeBodyV2, GeometryError> {
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 {
Expand All @@ -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,
Expand Down
5 changes: 4 additions & 1 deletion main/opengeometry/src/exchange/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ pub mod ifc_body;
mod part21;
mod preflight;
mod step;
mod unit;

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,
};
11 changes: 6 additions & 5 deletions main/opengeometry/src/exchange/step/body.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use crate::brep::{
};
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<usize>,
Expand All @@ -21,7 +22,7 @@ pub(super) struct BodyEmission {

struct BodyEntities<'a> {
brep: &'a BrepEnvelope,
scale: f64,
scale: Scale,
context2: usize,
surfaces: &'a [Option<usize>],
vertices: &'a [usize],
Expand All @@ -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<BodyEmission, GeometryError> {
Expand Down Expand Up @@ -85,7 +86,7 @@ pub(super) fn emit_body(
fn add_surfaces(
writer: &mut Part21Writer,
brep: &BrepEnvelope,
scale: f64,
scale: Scale,
) -> Result<Vec<Option<usize>>, GeometryError> {
let mut surfaces = vec![None; brep.geometry.surfaces.len()];
for face in &brep.topology.faces {
Expand Down Expand Up @@ -120,7 +121,7 @@ fn add_surfaces(
Ok(surfaces)
}

fn add_vertices(writer: &mut Part21Writer, brep: &BrepEnvelope, scale: f64) -> Vec<usize> {
fn add_vertices(writer: &mut Part21Writer, brep: &BrepEnvelope, scale: Scale) -> Vec<usize> {
brep.topology
.vertices
.iter()
Expand Down Expand Up @@ -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 {
Expand Down
13 changes: 7 additions & 6 deletions main/opengeometry/src/exchange/step/entities.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use crate::brep::{
};
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> {
Expand All @@ -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<usize, GeometryError> {
Ok(match geometry {
CurveGeometry::Line { origin, direction } => line(
Expand Down Expand Up @@ -91,7 +92,7 @@ fn direction(writer: &mut Part21Writer, value: &[f64]) -> usize {
value.iter().map(|v| real(*v)).collect::<Vec<_>>().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);
Expand All @@ -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<usize, GeometryError> {
Expand All @@ -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 {
Expand Down
28 changes: 15 additions & 13 deletions main/opengeometry/src/exchange/step/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,19 +9,29 @@ 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};

pub fn export_step(brep: &BrepEnvelope, unit: &str) -> Result<(String, StepReport), GeometryError> {
export_step_in(brep, "metre", unit)
}

pub fn export_step_in(
Comment thread
aka-blackboots marked this conversation as resolved.
Resolved
brep: &BrepEnvelope,
model_unit: &str,
Comment thread
aka-blackboots marked this conversation as resolved.
Resolved
unit: &str,
) -> Result<(String, StepReport), GeometryError> {
let (text, report) = export_bodies(
&[StepBodyInput {
og_id: &brep.id,
shape_id: &brep.id,
shape_revision: brep.revision,
brep,
}],
model_unit,
unit,
"Y",
&brep.id,
Expand Down Expand Up @@ -50,22 +60,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<StepSkipped>,
) -> 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 = Scale::between(model_unit, unit)?;
if bodies.is_empty() {
return Err(
GeometryError::InvalidGeometry("STEP export has no solid bodies".into()).into(),
Expand Down Expand Up @@ -124,12 +126,12 @@ pub(crate) fn export_bodies(
fn add_bodies(
writer: &mut Part21Writer,
bodies: &[StepBodyInput<'_>],
scale: f64,
scale: Scale,
context2: usize,
) -> Result<Vec<BodyEmission>, 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),
Expand All @@ -143,7 +145,7 @@ fn add_bodies(
fn step_body_reports(
bodies: &[StepBodyInput<'_>],
emitted: &[BodyEmission],
scale: f64,
scale: Scale,
) -> Vec<StepBodyReport> {
bodies
.iter()
Expand Down
Loading