diff --git a/src/parametric/README.md b/src/parametric/README.md
index e6ef73aaba..d25150c71f 100644
--- a/src/parametric/README.md
+++ b/src/parametric/README.md
@@ -30,7 +30,7 @@ It runs entirely in the browser. The geometry kernel is OpenCascade compiled to
- Fillet, chamfer (equal distance, two distances, distance and angle), shell, draft.
- Holes: simple, counterbored and countersunk, placed by clicking faces.
- Linear patterns (one or two directions), circular patterns and mirroring.
-- Reference planes, STEP import.
+- Reference planes, STEP and IGES import. IGES trimmed surfaces are sewn into solids; B-spline surfaces that are really planes, cylinders, cones, spheres or tori come in as those, so holes and fillets stay recognizable.
- Open SolidWorks parts (.sldprt, SolidWorks 2003 and later) without SolidWorks: the exact solid is read from the file and becomes an imported body you can keep modeling on. The SolidWorks feature tree is not carried over.
- References to faces and edges are stored by name, so fillets and sketches on faces survive dimension changes.
@@ -52,12 +52,12 @@ It runs entirely in the browser. The geometry kernel is OpenCascade compiled to
- Cut list in the design tree: identical members grouped with quantity, description, length, end angles and mass, exported as CSV.
**Assemblies**
-- File > New Assembly. Insert Components places parts from your cloud, this browser or your device (a part file or a STEP model); insert a part several times for several instances (bracket<1>, bracket<2>). The first component is fixed; the others float.
+- File > New Assembly. Insert Components places parts from your cloud, this browser or your device (a part file, or a STEP or IGES model); insert a part several times for several instances (bracket<1>, bracket<2>). The first component is fixed; the others float.
- Mates: coincident, parallel, perpendicular, distance, angle, concentric, tangent and lock, between faces, edges and the assembly planes, with aligned or anti-aligned alignment and values that take equations. Distance and angle mates can be limited to a range instead of a value (the component moves freely between a minimum and a maximum). The Mates folder in the design tree edits, flips, suppresses and deletes them. The status bar shows whether the assembly is under, fully or over defined; conflicting mates are marked.
- Mechanical mates: hinge (concentric and coincident in one, with optional angle limits from where it was added), slider (a straight edge or axis, or two planar faces, on each component: one move along it and no turn, with optional travel limits), gear (two axes turning by a ratio of pitch diameters or teeth, reversible for internal gears), rack and pinion (the rack's travel by the pinion's pitch diameter or a distance per turn), screw (a nut travelling a pitch per turn, right- or left-hand), width (a tab centred in a groove), slot (a pin travelling along a slot between its ends), cam follower (a vertex, a roller or a flat face kept on the cam's profile faces as it turns; convex profiles, exactly for round faces; a profile with a hollow is refused with its depth) and universal joint (two shafts at an angle β, the output turning by atan(tan φ / cos β), with an optional joint point where their axes meet). Gear, rack and screw mates hold from wherever the components are when they are added, and their turns add up past a full turn.
- Drag a component (Alt+drag, or Rotate Component, turns it): it moves only as its mates allow, so a lid on a hinge pin turns about the pin, turning one gear turns the other, dragging a rack turns its pinion, and a drag stops at a mate's limits. Fixed components do not move.
- Motion studies (Motion Study): rotary motors (a constant speed in °/s or rpm, or oscillating; on a face or edge, or on a hinge), linear motors (constant speed or oscillating; along a face or edge, or on a slider) and mate drivers (a distance or angle mate's value at a constant speed, harmonic, or ramped between two values) drive the mechanism for a duration at a frame rate. Frames are calculated without freezing the interface (with progress, and a Cancel); the study stops and says why when a limit is reached or the mechanism locks up. Play, pause, loop and scrub through the motion; plot a point of a component (its displacement, velocity, acceleration, or its turn, angular velocity and acceleration) or what a mate measures against time, download the results as CSV, and check the frames for interference. Studies are listed in the design tree and saved with the assembly; editing the assembly puts their results out of date.
-- Exploded view steps, interference detection with the overlapping volumes, a bill of materials (item, part, quantity, material; copy or download as CSV), mass properties with each part's material, measure, section view, and STEP (components as named solids) and STL export of the whole assembly.
+- Exploded view steps, interference detection with the overlapping volumes, a bill of materials (item, part, quantity, material; copy or download as CSV), mass properties with each part's material, measure, section view, and STEP (components as named solids), IGES (components as named, colored groups) and STL export of the whole assembly.
- An assembly references its part files and keeps a copy of each, so it opens even when a part file is moved, shared or downloaded. Open Part edits a component's part; save it and go back, and the assembly takes the change (Update Parts reads the part files again).
**Assistant**
@@ -98,8 +98,8 @@ It runs entirely in the browser. The geometry kernel is OpenCascade compiled to
- Global variables and equations: type `=Width/2` in any dimension or feature value.
- Material and appearance, mass properties (mass, volume, area, center of mass, inertia), measure, section view.
- Display styles (shaded with edges, shaded, hidden lines removed or visible, wireframe), standard views, perspective.
-- Save to your Puter cloud or this browser, crash recovery of unsaved work, export STEP and STL, download the part file.
-- Open parts, STEP and SolidWorks files from the Puter desktop (double-click or Open with), or drag them onto the app from a Puter folder window or your computer. Files dragged onto the assistant go with your next message.
+- Save to your Puter cloud or this browser, crash recovery of unsaved work, export STEP, IGES (trimmed NURBS surfaces, with each boundary in model space and on its surface) and STL, download the part file.
+- Open parts, STEP, IGES and SolidWorks files from the Puter desktop (double-click or Open with), or drag them onto the app from a Puter folder window or your computer. Files dragged onto the assistant go with your next message.
- Share parts saved in your Puter cloud with other Puter users, with view or edit access. Parts shared with you appear under **Shared with me** in the Open dialog.
- Undo and redo for everything, including sketch edits.
- Light, dark and system themes. Works with mouse, trackpad, touch and keyboard, from phones to large desktop screens.
@@ -134,6 +134,7 @@ npm run build # type check, license check, production build in dist/
| Geometry kernel | `src/kernel` | OpenCascade (WebAssembly) in a Web Worker. Each feature is cached under a hash of everything before it, so edits rebuild only what changed. Faces are named after the feature and sketch entity that created them. |
| Renderer | `src/render` | WebGL2: shaded meshes with per-face state in a data texture, screen-space thick edges, GPU picking with depth (asynchronous readback for hover), section clipping, render on demand. |
| Interface | `src/app`, `src/ui` | No framework. CommandManager, design tree, PropertyManager panels, sketch editor, dialogs. |
+| IGES | `src/formats/iges`, `src/kernel/iges.ts` | Writes every face as an exact rational B-spline trimmed surface (144 over 128, boundaries as 142 with model-space and parameter-space curves). Reads trimmed and bounded surfaces, analytic surfaces, B-rep solids (186) and subfigures, converts them to STEP for the kernel's reader, and sews the faces into solids. Runs in the geometry worker. |
| SolidWorks import | `src/formats/sldprt` | Reads the SolidWorks container (2015+ chunk format and the older OLE2), decodes the embedded Parasolid transmit and writes it as exact STEP for the kernel. Runs in the geometry worker. |
| CAM | `src/model/cam.ts`, `src/cam`, `src/app/cam` | Toolpaths are generated in a worker of their own from a fine mesh of the part, in the setup's work coordinates. Drop-cutter (`src/cam/dropcutter.ts`) gives the lowest height a flat, ball, bull nose or conical cutter can reach at a point (face, edge and corner contacts, exact where a closed form exists). Where the tool can be at a height is where that is lower: its boundary is traced by marching squares with each crossing refined by bisection on the drop-cutter, and the passes inside it are offsets of a distance transform, cut from the innermost out. Parallel finishing follows drop-cutter heights along lines. The simulation lowers a height map of the stock along every move. Post processors write the moves with arcs fitted to them. |
| Analysis | `src/model/fea.ts`, `src/fea`, `src/app/fea` | Static stress analysis in a worker of its own, loaded on first use. The mesher (`src/fea/mesher.ts`) fills the solid with a body-centred cubic lattice (isosurface stuffing: exact inside tests by ray crossings of the kernel's triangulation, lattice points near the boundary warped onto it, lattice tetrahedra clipped with fixed stencils), moves vertices onto the part's corners and onto the edges between faces (splitting edges where a move would spoil an element), smooths, and adds midside nodes on the curved surface. The solver assembles 10-node tetrahedra into node-block sparse rows, applies fixtures as constraints in each node's own frame, and solves with conjugate gradients preconditioned by smoothed aggregation multigrid (rigid body modes as the near null space; block Gauss-Seidel smoothing). Fixtures are checked against rigid body motions before solving. |
diff --git a/src/parametric/index.html b/src/parametric/index.html
index 42823cd0b8..741aad9cb7 100644
--- a/src/parametric/index.html
+++ b/src/parametric/index.html
@@ -4,7 +4,7 @@
Parametric
-
+
diff --git a/src/parametric/package.json b/src/parametric/package.json
index 4449d345a7..450808b1f0 100644
--- a/src/parametric/package.json
+++ b/src/parametric/package.json
@@ -1,7 +1,7 @@
{
"name": "parametric",
"version": "0.1.0",
- "description": "Parametric: feature-based 3D part modeling in the browser. Sketch with constraints, extrude, revolve, fillet, shell and pattern on a real B-rep kernel, then export STEP and STL or machine it with CAM toolpaths and G-code, stored in your own Puter cloud.",
+ "description": "Parametric: feature-based 3D part modeling in the browser. Sketch with constraints, extrude, revolve, fillet, shell and pattern on a real B-rep kernel, then export STEP, IGES and STL or machine it with CAM toolpaths and G-code, stored in your own Puter cloud.",
"type": "module",
"private": true,
"license": "AGPL-3.0-only",
diff --git a/src/parametric/src/app/actions.ts b/src/parametric/src/app/actions.ts
index 0a14468a43..918d497f1d 100644
--- a/src/parametric/src/app/actions.ts
+++ b/src/parametric/src/app/actions.ts
@@ -148,13 +148,14 @@ export function registerCommands(app: App, files: FileOps) {
// ---- file ----
{ id: 'new', label: 'New', icon: 'new', shortcut: 'Control+N', description: 'Start a new part.', run: () => files.newPart() },
{ id: 'open', label: 'Open...', icon: 'open', shortcut: 'Ctrl+O', description: 'Open a saved part.', run: () => files.open() },
- { id: 'openDevice', label: 'Open from Device...', icon: 'upload', description: 'Open a part file, or a STEP or SolidWorks file, from this device.', run: () => files.openFromDevice() },
+ { id: 'openDevice', label: 'Open from Device...', icon: 'upload', description: 'Open a part file, or a STEP, IGES or SolidWorks file, from this device.', run: () => files.openFromDevice() },
{ id: 'save', label: 'Save', icon: 'save', shortcut: 'Ctrl+S', description: 'Save the part.', run: () => { void files.save(); } },
{ id: 'saveAs', label: 'Save As...', icon: 'save', shortcut: 'Ctrl+Shift+S', run: () => files.saveAs() },
{ id: 'downloadPart', label: 'Download Part File', icon: 'download', description: 'Download the part file to this device.', run: () => files.exportAs('part') },
{ id: 'exportStep', label: 'Export STEP...', icon: 'export', keywords: 'stp export cad', description: 'Export the solid as a STEP file.', enabled: hasBody, run: () => files.exportAs('step') },
+ { id: 'exportIges', label: 'Export IGES...', icon: 'export', keywords: 'igs iges export cad surfaces', description: 'Export the solid as an IGES file (trimmed NURBS surfaces).', enabled: hasBody, run: () => files.exportAs('iges') },
{ id: 'exportStl', label: 'Export STL...', icon: 'export', keywords: '3d print mesh', description: 'Export the solid as an STL mesh for 3D printing.', enabled: hasBody, run: () => files.exportAs('stl') },
- { id: 'importStep', label: 'Import...', icon: 'import', keywords: 'stp step sldprt solidworks import', description: 'Insert a STEP file or SolidWorks part as a solid body.', run: () => files.importStep() },
+ { id: 'importStep', label: 'Import...', icon: 'import', keywords: 'stp step igs iges sldprt solidworks import', description: 'Insert a STEP or IGES file, or a SolidWorks part, as a solid body.', run: () => files.importStep() },
{ id: 'rename', label: 'Rename Part...', icon: 'edit', run: () => files.rename() },
{
id: 'assistant', label: 'Assistant', icon: 'assistant', shortcut: 'Ctrl+J', keywords: 'ai chat copilot design help agent claude',
@@ -476,7 +477,7 @@ export function buildMenus(app: App): { label: string; items: () => MenuItem[] }
{
label: 'File', items: () => [
m('new'), ...(c.get('newAssembly') ? [m('newAssembly')] : []), m('open'), m('openDevice'), { label: 'Recent', icon: 'files', submenu: () => app.recentMenu() }, sep,
- m('save'), m('saveAs'), m('downloadPart'), sep, m('importStep'), m('exportStep'), m('exportStl'), sep, m('openDrawing'), m('drawing:pdf'), m('drawing:dxf'), sep, m('share'), m('rename'), m('properties'),
+ m('save'), m('saveAs'), m('downloadPart'), sep, m('importStep'), m('exportStep'), m('exportIges'), m('exportStl'), sep, m('openDrawing'), m('drawing:pdf'), m('drawing:dxf'), sep, m('share'), m('rename'), m('properties'),
],
},
{
diff --git a/src/parametric/src/app/assembly/index.ts b/src/parametric/src/app/assembly/index.ts
index cc5c835546..620c1365e5 100644
--- a/src/parametric/src/app/assembly/index.ts
+++ b/src/parametric/src/app/assembly/index.ts
@@ -70,7 +70,7 @@ export const ASSEMBLY_TAB: RibbonTab = {
* measuring...). Every other command is disabled while an assembly is open.
*/
const SHARED = new Set([
- 'new', 'newAssembly', 'open', 'openDevice', 'save', 'saveAs', 'downloadPart', 'exportStep', 'exportStl', 'rename', 'share', 'properties', 'assistant',
+ 'new', 'newAssembly', 'open', 'openDevice', 'save', 'saveAs', 'downloadPart', 'exportStep', 'exportIges', 'exportStl', 'rename', 'share', 'properties', 'assistant',
'undo', 'redo', 'redo2', 'rebuild', 'forceRebuild', 'repeat', 'delete', 'equations', 'options', 'measure', 'massProperties', 'sectionView',
'zoomFit', 'zoomIn', 'zoomOut', 'previousView', 'normalTo', 'viewOrientation', 'displayStyle', 'toggleVisibility', 'perspective', 'showPlanes', 'showOrigin',
'toggleTree', 'shortcutBar', 'shortcuts', 'shortcutsF1', 'github', 'about', 'openDrawing', 'backToModel',
diff --git a/src/parametric/src/app/assembly/panels.ts b/src/parametric/src/app/assembly/panels.ts
index 1ffca66f05..e45debbc08 100644
--- a/src/parametric/src/app/assembly/panels.ts
+++ b/src/parametric/src/app/assembly/panels.ts
@@ -16,7 +16,7 @@ import {
} from '../../model/assembly';
import { type Geo, fittingMates, initialMateSettings, mateProblem, placeGeo, relativePlacement } from '../../assembly/solver';
import {
- EXT, acceptList, cloudVersion, download, isSolidWorksFile, isStepFile, listParts, loadPart, locationLabel, pickCloudFile, pickDeviceFile, readIndexEntry, safeName, sameLocation, versionChanged,
+ EXT, IMPORT_EXTS, acceptList, cloudVersion, download, isIgesFile, isSolidWorksFile, isStepFile, listParts, loadPart, locationLabel, pickCloudFile, pickDeviceFile, readIndexEntry, safeName, sameLocation, versionChanged,
type FileEntry, type FileVersion, type Location,
} from '../../platform/files';
import { cloudAvailable, puter, storageError } from '../../platform/puter';
@@ -25,6 +25,7 @@ import { icon } from '../../ui/icons';
import { showDialog, toast } from '../../ui/overlay';
import type { App } from '../app';
import { formatGroup } from '../dialogs';
+import { igesWarning } from '../fileops';
import { type PickFilter, type SelBoxItem, PropertyPanel, SelectionBox, checkbox, numberField, section, segmented, selectField } from '../pm';
import type { SelItem } from '../selection';
import type { AssemblyMode } from './mode';
@@ -64,7 +65,7 @@ function partFrom(text: string, name: string): PartDocument | null {
/**
* Asks which part to insert: parts in the cloud or this browser (as the Open
- * dialog lists them), a file from the device (a part, or a STEP model, which
+ * dialog lists them), a file from the device (a part, or a STEP or IGES model, which
* becomes a part kept inside the assembly) or one picked in Puter.
*/
export async function pickPart(app: App): Promise {
@@ -75,7 +76,7 @@ export async function pickPart(app: App): Promise {
const list = h('div', { class: 'file-list', role: 'list' });
let chosen: FileEntry | null = null;
let close: ((v: string | null) => void) | null = null;
- if (!entries.length) list.replaceChildren(h('p', {}, 'No saved parts yet. Save a part first, or insert a part or STEP file from this device.'));
+ if (!entries.length) list.replaceChildren(h('p', {}, 'No saved parts yet. Save a part first, or insert a part, STEP or IGES file from this device.'));
for (const e of entries) {
const b = h('button', { class: 'file-item', type: 'button' },
h('span', { 'aria-hidden': 'true', style: { color: e.location.type === 'cloud' ? 'var(--accent)' : 'var(--text-3)' } }, icon(e.location.type === 'cloud' ? 'cloud' : 'device', 18)),
@@ -109,7 +110,7 @@ export async function pickPart(app: App): Promise {
return fromFile(app, r.blob, r.fileName, r.location, r.version);
}
if (v === 'device') {
- const file = await pickDeviceFile(acceptList([EXT, '.json', '.step', '.stp', '.sldprt']));
+ const file = await pickDeviceFile(acceptList([EXT, '.json', ...IMPORT_EXTS]));
if (!file || signal.aborted) return null;
return fromFile(app, file, file.name, null, null);
}
@@ -118,11 +119,13 @@ export async function pickPart(app: App): Promise {
async function fromFile(app: App, blob: Blob, fileName: string, loc: Location | null, version: FileVersion | null): Promise {
const base = safeName(fileName.replace(/\.[^.]+$/, ''));
- if (isStepFile(fileName) || isSolidWorksFile(fileName)) {
+ if (isStepFile(fileName) || isIgesFile(fileName) || isSolidWorksFile(fileName)) {
if (/\.(sldasm|slddrw)$/i.test(fileName)) { toast({ kind: 'error', message: `${fileName} is not a SolidWorks part. Insert parts (.sldprt) one by one.` }); return null; }
let step: string;
try {
- step = isStepFile(fileName) ? await blob.text() : (await app.kernel.convertSolidWorks(new Uint8Array(await blob.arrayBuffer()), fileName)).step;
+ step = isStepFile(fileName) ? await blob.text()
+ : isIgesFile(fileName) ? await readIges(app, blob, fileName, base || 'Part')
+ : (await app.kernel.convertSolidWorks(new Uint8Array(await blob.arrayBuffer()), fileName)).step;
} catch (e) {
toast({ kind: 'error', title: 'Could not insert the file', message: (e as Error).message });
return null;
@@ -142,6 +145,19 @@ async function fromFile(app: App, blob: Blob, fileName: string, loc: Location |
return { doc, source: loc, version };
}
+/** An IGES file as STEP text, saying what the import left out (as opening it does). */
+async function readIges(app: App, blob: Blob, fileName: string, name: string): Promise {
+ const done = toast({ message: `Reading ${fileName}...`, timeout: 0 });
+ try {
+ const r = await app.kernel.convertIges(await blob.text(), name);
+ const warning = igesWarning(r, fileName);
+ if (warning) toast({ kind: 'warning', message: warning, timeout: 9000 });
+ return r.step;
+ } finally {
+ done();
+ }
+}
+
/** Embeds the part (once) and places a new component of it. */
export function insertComponent(mode: AssemblyMode, picked: PickedPart) {
const app = mode.app;
diff --git a/src/parametric/src/app/fileops.ts b/src/parametric/src/app/fileops.ts
index 9c0b8fdd3a..c4f84a4156 100644
--- a/src/parametric/src/app/fileops.ts
+++ b/src/parametric/src/app/fileops.ts
@@ -6,7 +6,7 @@ import { allocateId, newDocument, serializeDocument, withUsedBlobs } from '../mo
import type { ImportFeature, PartDocument } from '../model/types';
import { newAssembly, parseAnyDocument } from '../model/assembly';
import {
- type Location, EXT, IMPORT_EXTS, clearRecovery, download, isSolidWorksFile, isStepFile, listParts, loadText, locationLabel, newLocation,
+ type Location, EXT, IMPORT_EXTS, clearRecovery, download, isIgesFile, isSolidWorksFile, isStepFile, listParts, loadText, locationLabel, newLocation,
pickCloudFile, pickCloudSave, pickDeviceFile, claimRecovery, orphanRecoveries, removeRecovery, safeName, writeRecovery, writeRecoveryOnUnload, type FileEntry, deletePart, forgetRecent, rememberRecent,
newLocalLocation, localPartNames, onPartDeleted, onRenamedElsewhere, recentParts, onSavedElsewhere, sameLocation, acceptList, type FileVersion, cloudEntry, cloudVersion, loadPart, partFileName, readIndexEntry, renameCloudPart, savePart, versionChanged, versionOf,
} from '../platform/files';
@@ -200,7 +200,7 @@ export class FileOps {
const other = files.filter((f) => !canOpen(f.name));
if (other.length) {
const what = other.length === 1 ? `${other[0].name} is not a file Parametric opens.` : `${other.length} of these files are not files Parametric opens.`;
- toast({ kind: openable.length ? 'warning' : 'error', message: `${what} Choose a part (${EXT}), a STEP file (.step, .stp) or a SolidWorks part (.sldprt).`, timeout: 8000 });
+ toast({ kind: openable.length ? 'warning' : 'error', message: `${what} Choose a part (${EXT}), a STEP file (.step, .stp), an IGES file (.igs, .iges) or a SolidWorks part (.sldprt).`, timeout: 8000 });
}
if (!openable.length) return null;
if (openable.length > 1) toast({ message: `Parametric opens one part at a time, so only ${openable[0].name} is opened.`, timeout: 8000 });
@@ -616,18 +616,23 @@ export class FileOps {
const text = await blob.text();
if (signal.aborted) return false;
if (isStepFile(fileName)) { await this.openStep(text, fileName, signal); return false; }
+ if (isIgesFile(fileName)) {
+ const step = await this.convertIges(text, fileName);
+ if (step && !signal.aborted) await this.openStep(step, fileName, signal);
+ return false;
+ }
return this.openPartText(text, loc, fileName.replace(/\.[^.]+$/, ''), signal, version);
}
- /** Imports a STEP or SolidWorks file as a solid feature in the current part. */
+ /** Imports a STEP, IGES or SolidWorks file as a solid feature in the current part. */
async importStep() {
const documentVersion = this.documentVersion;
const file = await pickDeviceFile(acceptList(IMPORT_EXTS));
if (!file || documentVersion !== this.documentVersion) return;
// Any file can be picked (iPhone and iPad, or All Files): only models are imported.
- if (!isStepFile(file.name) && !isSolidWorksFile(file.name)) {
+ if (!isStepFile(file.name) && !isIgesFile(file.name) && !isSolidWorksFile(file.name)) {
const part = file.name.toLowerCase().endsWith(EXT);
- toast({ kind: 'error', title: 'Import failed', message: `${file.name} is not a STEP file (.step, .stp) or a SolidWorks part (.sldprt).${part ? ' To work on a part file, open it with Open.' : ''}`, timeout: 8000 });
+ toast({ kind: 'error', title: 'Import failed', message: `${file.name} is not a STEP file (.step, .stp), an IGES file (.igs, .iges) or a SolidWorks part (.sldprt).${part ? ' To work on a part file, open it with Open.' : ''}`, timeout: 8000 });
return;
}
if (tooLarge(file.size, file.name)) return;
@@ -637,7 +642,13 @@ export class FileOps {
return;
}
const text = await file.text();
- if (documentVersion === this.documentVersion) await this.importStepText(text, file.name);
+ if (documentVersion !== this.documentVersion) return;
+ if (isIgesFile(file.name)) {
+ const step = await this.convertIges(text, file.name);
+ if (step && documentVersion === this.documentVersion) await this.importStepText(step, file.name);
+ return;
+ }
+ await this.importStepText(text, file.name);
}
/** Opens a SolidWorks part as a new part whose first feature is its solid. */
@@ -646,15 +657,16 @@ export class FileOps {
if (step && !signal.aborted) await this.openStep(step, fileName, signal);
}
- /** Opens a STEP model (or a converted SolidWorks part) as a new part whose first feature is its solid. */
+ /** Opens a STEP model (or a converted SolidWorks part or IGES model) as a new part whose first feature is its solid. */
private async openStep(step: string, fileName: string, signal: AbortSignal) {
const app = this.app;
const solidWorks = isSolidWorksFile(fileName);
+ const iges = isIgesFile(fileName);
// Checked first: a file that cannot be opened leaves the current part alone.
if (!step.trim()) { toast({ kind: 'error', title: 'Could not open the file', message: `${fileName} is empty.` }); return; }
const err = await app.kernel.checkImport(step).catch((e) => (e as Error).message);
if (signal.aborted) return;
- if (err) { toast({ kind: 'error', title: solidWorks ? 'Could not open the SolidWorks part' : 'Could not open the STEP file', message: err }); return; }
+ if (err) { toast({ kind: 'error', title: solidWorks ? 'Could not open the SolidWorks part' : iges ? 'Could not open the IGES file' : 'Could not open the STEP file', message: err }); return; }
if (!(await this.confirmDiscard('open another part', signal)) || signal.aborted) return;
const doc = newDocument(safeName(fileName.replace(/\.[^.]+$/, '')) || 'Part1', app.settings.defaultUnits);
const blobId = newBlobId(doc);
@@ -683,6 +695,23 @@ export class FileOps {
}
}
+ /** Converts an IGES file to STEP in the geometry worker; null after reporting a failure. */
+ private async convertIges(text: string, fileName: string): Promise {
+ if (!text.trim()) { toast({ kind: 'error', title: 'Could not read the IGES file', message: `${fileName} is empty.` }); return null; }
+ const done = toast({ message: `Reading ${fileName}...`, timeout: 0 });
+ try {
+ const r = await this.app.kernel.convertIges(text, fileName.replace(/\.[^.]+$/, ''));
+ const warning = igesWarning(r, fileName);
+ if (warning) toast({ kind: 'warning', message: warning, timeout: 9000 });
+ return r.step;
+ } catch (e) {
+ toast({ kind: 'error', title: 'Could not read the IGES file', message: (e as Error).message });
+ return null;
+ } finally {
+ done();
+ }
+ }
+
async importStepText(text: string, fileName: string, signal = this.app.documentSignal) {
const app = this.app;
const documentVersion = this.documentVersion;
@@ -703,7 +732,7 @@ export class FileOps {
toast({ kind: 'success', message: `Imported ${fileName}` });
}
- async exportAs(format: 'step' | 'stl' | 'part') {
+ async exportAs(format: 'step' | 'iges' | 'stl' | 'part') {
const app = this.app;
const documentVersion = this.documentVersion;
const name = safeName(app.store.doc.name);
@@ -727,9 +756,9 @@ export class FileOps {
if (!app.bbox) { toast({ kind: 'warning', message: 'There is no geometry to export yet.' }); return; }
const data = await app.kernel.exportFile(format, Math.max(1, app.settings.quality), app.store.doc.name);
if (documentVersion !== this.documentVersion) return;
- const blob = new Blob([data as BlobPart], { type: format === 'step' ? 'model/step' : 'model/stl' });
+ const blob = new Blob([data as BlobPart], { type: format === 'step' ? 'model/step' : format === 'iges' ? 'model/iges' : 'model/stl' });
- download(blob, `${name}.${format === 'step' ? 'step' : 'stl'}`);
+ download(blob, `${name}.${format === 'iges' ? 'igs' : format}`);
// Surface bodies (listed after the solid's faces) are not in an STL file.
if (format === 'stl' && app.faces.at(-1)?.body) toast({ kind: 'warning', message: 'The surface bodies are not in the STL file: STL holds solids only. Export STEP to keep them.', timeout: 9000 });
// The file has what the model shows: say so when the rollback bar leaves features out.
@@ -982,14 +1011,23 @@ const PART_LIMIT = 200_000_000;
/** Checked before a file is read into memory: true after reporting that it is too large. */
function tooLarge(size: number, fileName: string): boolean {
const step = isStepFile(fileName);
+ const iges = isIgesFile(fileName);
const solidWorks = isSolidWorksFile(fileName);
- if (size <= (step ? STEP_LIMIT : solidWorks ? SOLIDWORKS_LIMIT : PART_LIMIT)) return false;
- toast({ kind: 'error', message: step ? 'This STEP file is too large to import (60 MB limit).' : solidWorks ? 'This SolidWorks file is too large to open (200 MB limit).' : 'This file is too large to open as a part (200 MB limit).' });
+ if (size <= (step || iges ? STEP_LIMIT : solidWorks ? SOLIDWORKS_LIMIT : PART_LIMIT)) return false;
+ toast({ kind: 'error', message: step ? 'This STEP file is too large to import (60 MB limit).' : iges ? 'This IGES file is too large to import (60 MB limit).' : solidWorks ? 'This SolidWorks file is too large to open (200 MB limit).' : 'This file is too large to open as a part (200 MB limit).' });
return true;
}
+/** What an IGES import left out or could not close into solids, or null when it read everything. */
+export function igesWarning(r: { skipped: number; solids: number; sheets: number }, fileName: string): string | null {
+ const notes: string[] = [];
+ if (r.skipped) notes.push(`${r.skipped} ${r.skipped === 1 ? 'surface' : 'surfaces'} of ${fileName} could not be read.`);
+ if (r.sheets) notes.push(r.solids ? `Some surfaces of ${fileName} do not close into a solid, so they are imported as surfaces.` : `The surfaces of ${fileName} do not close into a solid, so they are imported as surfaces.`);
+ return notes.length ? notes.join(' ') : null;
+}
+
const OPENS = [EXT, '.json', ...IMPORT_EXTS];
-/** A file Parametric opens: a part, or a STEP or SolidWorks model. */
+/** A file Parametric opens: a part, or a STEP, IGES or SolidWorks model. */
const canOpen = (name: string) => OPENS.some((ext) => name.toLowerCase().endsWith(ext));
const isDriveFolder = (it: PuterFSItem) => {
const d = it as PuterFSItem & { isDirectory?: boolean; fsentry_is_dir?: boolean };
diff --git a/src/parametric/src/app/start.ts b/src/parametric/src/app/start.ts
index 7ac0b4e0ae..a06f953956 100644
--- a/src/parametric/src/app/start.ts
+++ b/src/parametric/src/app/start.ts
@@ -56,7 +56,7 @@ export class StartScreen {
app.newDocument('Part1');
}),
action('open', 'Open', cloudAvailable() ? 'Open a part from your Puter cloud or this browser' : 'Open a part saved in this browser', () => { this.hide(); void this.files.open(); }),
- action('upload', 'Open from device', 'Open a part file, or a STEP or SolidWorks file', () => { this.hide(); void this.files.openFromDevice(); }),
+ action('upload', 'Open from device', 'Open a part file, or a STEP, IGES or SolidWorks file', () => { this.hide(); void this.files.openFromDevice(); }),
),
h('div', { class: 'row' }, h('label', { class: 'field-label', for: unitSel.id }, 'Units for new parts'), unitSel),
recents.length ? h('div', { class: 'start-section' }, h('h2', {}, 'Recent'), h('div', { class: 'file-list' }, recents.map((r) => {
diff --git a/src/parametric/src/app/taskpane.ts b/src/parametric/src/app/taskpane.ts
index 34cd8885fd..45cf0d8599 100644
--- a/src/parametric/src/app/taskpane.ts
+++ b/src/parametric/src/app/taskpane.ts
@@ -192,7 +192,7 @@ export function renderHelp(body: HTMLElement) {
['3. Constrain', 'Use Smart Dimension (D) to set sizes, and the Constrain group of the Sketch tab (Coincident, Parallel, Tangent...) to fix how geometry relates. Convert Entities projects model edges into the sketch, linked to the model. Blue geometry can still move; black is fully defined; red conflicts.'],
['4. Build', 'Exit the sketch and use Extruded Boss, Revolved Boss or a Cut. Then add fillets, chamfers, holes, shells and patterns.'],
['5. Change', 'Double-click a feature in the design tree or a face in the model to edit it. Everything after it rebuilds.'],
- ['6. Save and share', 'Save to your Puter cloud (or this browser), or export STEP and STL files.'],
+ ['6. Save and share', 'Save to your Puter cloud (or this browser), or export STEP, IGES and STL files.'],
];
for (const [t, d] of steps) body.append(h('div', {}, h('div', { style: { fontWeight: '600' } }, t), h('div', { class: 'field-label' }, d)));
body.append(h('div', { class: 'field-label' }, 'Navigate: middle or right drag to rotate, Ctrl + middle or Shift + right drag to pan, wheel to zoom, F to fit. Press F1 for all shortcuts.'));
diff --git a/src/parametric/src/assistant/tools.ts b/src/parametric/src/assistant/tools.ts
index b36ea8c493..30b630a39d 100644
--- a/src/parametric/src/assistant/tools.ts
+++ b/src/parametric/src/assistant/tools.ts
@@ -357,7 +357,7 @@ const TOOLS: ToolDef[] = [
{
name: 'run_command',
description: 'Run an app command the user would otherwise click: save the part, or export it (opens a save dialog for the user).',
- parameters: obj({ command: S('Command', { enum: ['save', 'export_step', 'export_stl', 'download_part', 'export_drawing_pdf', 'export_drawing_svg'] }) }, ['command']),
+ parameters: obj({ command: S('Command', { enum: ['save', 'export_step', 'export_iges', 'export_stl', 'download_part', 'export_drawing_pdf', 'export_drawing_svg'] }) }, ['command']),
run: async (a, k) => k.runCommand(a),
},
];
@@ -1015,7 +1015,7 @@ class Toolkit {
runCommand(a: Obj): string {
const ui = this.host.ui;
if (!ui) throw new ToolError('commands need the app\'s interface');
- const map: Record = { save: 'save', export_step: 'exportStep', export_stl: 'exportStl', download_part: 'downloadPart', export_drawing_pdf: 'drawing:pdf', export_drawing_svg: 'drawing:svg' };
+ const map: Record = { save: 'save', export_step: 'exportStep', export_iges: 'exportIges', export_stl: 'exportStl', download_part: 'downloadPart', export_drawing_pdf: 'drawing:pdf', export_drawing_svg: 'drawing:svg' };
const id = map[str(a.command)];
if (!id) throw new ToolError(`command: one of ${Object.keys(map).join(', ')}`);
if (!ui.runCommand(id)) throw new ToolError(`${a.command} is not available right now${id.startsWith('drawing:') ? ' (show the drawing first)' : id.startsWith('export') ? ' (there is no solid)' : ''}`);
diff --git a/src/parametric/src/formats/iges/convert.ts b/src/parametric/src/formats/iges/convert.ts
new file mode 100644
index 0000000000..05d95a67a3
--- /dev/null
+++ b/src/parametric/src/formats/iges/convert.ts
@@ -0,0 +1,1010 @@
+// Converts IGES entities into faces in millimetres: surfaces with their
+// boundary loops of model-space curves. Trimmed surfaces (144), bounded
+// surfaces (143), bounded planes (108), untrimmed surfaces, manifold solid
+// B-reps (186) and subfigure instances (408) are read; curves and points on
+// their own are not bodies and are left out.
+
+import { IgesError, type IgesEntity, type IgesFile, int, num } from './parse';
+import {
+ type NurbsCurve, type NurbsSurface, type Pt, add, arcCurve, clampCurve, clampSurface, cross, curveDomain, curvePoint, distance, dot,
+ elevateDegree, extrudeCurve, fitCurve, isoCurve, lineCurve, mapCurve, mapSurface, mul, norm, reparamCurve, reverseCurve, revolveCurve, ruledSurface, sub,
+ surfaceDomain, surfacePoint, unit,
+} from './nurbs';
+
+export type Curve3 =
+ | { kind: 'line'; a: Pt; b: Pt }
+ /** c + r (cos t x + sin t y) for t from a0 to a1 (x, y orthonormal). */
+ | { kind: 'circle'; c: Pt; x: Pt; y: Pt; r: number; a0: number; a1: number }
+ | { kind: 'ellipse'; c: Pt; x: Pt; y: Pt; r1: number; r2: number; a0: number; a1: number }
+ | { kind: 'nurbs'; n: NurbsCurve };
+
+export type Surf =
+ | { kind: 'plane'; o: Pt; z: Pt; x: Pt }
+ | { kind: 'cylinder'; o: Pt; z: Pt; x: Pt; r: number }
+ /** Radius r at o, growing along z at the semi-angle (radians, positive). */
+ | { kind: 'cone'; o: Pt; z: Pt; x: Pt; r: number; angle: number }
+ | { kind: 'sphere'; o: Pt; z: Pt; x: Pt; r: number }
+ | { kind: 'torus'; o: Pt; z: Pt; x: Pt; R: number; r: number }
+ | { kind: 'revolution'; curve: Curve3; o: Pt; z: Pt }
+ | { kind: 'extrusion'; curve: Curve3; d: Pt }
+ | { kind: 'nurbs'; n: NurbsSurface };
+
+export interface TrimmedFace {
+ surface: Surf;
+ /** False when the surface's normal is the other way round from the file's surface (the loops run counterclockwise about that one). */
+ sense: boolean;
+ /** Loops of model-space curves, head to tail; the outer one first. */
+ loops: Curve3[][];
+}
+
+export interface BrepFace { surface: Surf; sense: boolean; loops: { e: number; fwd: boolean }[][] }
+export interface Brep {
+ vertices: Pt[];
+ edges: { curve: Curve3; v0: number; v1: number }[];
+ /** The outer shell first, then voids. */
+ shells: BrepFace[][];
+}
+
+export interface IgesModel {
+ faces: TrimmedFace[];
+ breps: Brep[];
+ /** Faces that could not be read. */
+ skipped: number;
+ problems: string[];
+ /** The file's resolution in millimetres (0 when it gives none). */
+ resolution: number;
+ /** Largest coordinate, for tolerances. */
+ size: number;
+}
+
+// ---------- transforms: [R (3x3, row-major) | T] ----------
+
+type Mat = number[];
+const IDENT: Mat = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0];
+const scaleMat = (s: number): Mat => [s, 0, 0, 0, 0, s, 0, 0, 0, 0, s, 0];
+const apply = (m: Mat, p: Pt): Pt => [
+ m[0] * p[0] + m[1] * p[1] + m[2] * (p[2] ?? 0) + m[3],
+ m[4] * p[0] + m[5] * p[1] + m[6] * (p[2] ?? 0) + m[7],
+ m[8] * p[0] + m[9] * p[1] + m[10] * (p[2] ?? 0) + m[11],
+];
+const applyDir = (m: Mat, d: Pt): Pt => [m[0] * d[0] + m[1] * d[1] + m[2] * d[2], m[4] * d[0] + m[5] * d[1] + m[6] * d[2], m[8] * d[0] + m[9] * d[1] + m[10] * d[2]];
+/** a after b. */
+function compose(a: Mat, b: Mat): Mat {
+ const o = new Array(12);
+ for (let r = 0; r < 3; r++) {
+ for (let c = 0; c < 3; c++) o[r * 4 + c] = a[r * 4] * b[c] + a[r * 4 + 1] * b[4 + c] + a[r * 4 + 2] * b[8 + c];
+ o[r * 4 + 3] = a[r * 4] * b[3] + a[r * 4 + 1] * b[7] + a[r * 4 + 2] * b[11] + a[r * 4 + 3];
+ }
+ return o;
+}
+/** How much a transform scales lengths (uniform scaling assumed). */
+const scaleOf = (m: Mat) => Math.cbrt(Math.abs(m[0] * (m[5] * m[10] - m[6] * m[9]) - m[1] * (m[4] * m[10] - m[6] * m[8]) + m[2] * (m[4] * m[9] - m[5] * m[8]))) || 1;
+
+const perpendicular = (z: Pt): Pt => unit(Math.abs(z[0]) < 0.9 ? cross(z, [1, 0, 0]) : cross(z, [0, 1, 0]));
+
+// ---------- curves ----------
+
+export function curveStart(c: Curve3): Pt {
+ switch (c.kind) {
+ case 'line': return c.a;
+ case 'circle': return add(c.c, add(mul(c.x, c.r * Math.cos(c.a0)), mul(c.y, c.r * Math.sin(c.a0))));
+ case 'ellipse': return add(c.c, add(mul(c.x, c.r1 * Math.cos(c.a0)), mul(c.y, c.r2 * Math.sin(c.a0))));
+ case 'nurbs': return curvePoint(c.n, curveDomain(c.n)[0]);
+ }
+}
+
+export function curveEnd(c: Curve3): Pt {
+ switch (c.kind) {
+ case 'line': return c.b;
+ case 'circle': return add(c.c, add(mul(c.x, c.r * Math.cos(c.a1)), mul(c.y, c.r * Math.sin(c.a1))));
+ case 'ellipse': return add(c.c, add(mul(c.x, c.r1 * Math.cos(c.a1)), mul(c.y, c.r2 * Math.sin(c.a1))));
+ case 'nurbs': return curvePoint(c.n, curveDomain(c.n)[1]);
+ }
+}
+
+export function reverse(c: Curve3): Curve3 {
+ switch (c.kind) {
+ case 'line': return { kind: 'line', a: c.b, b: c.a };
+ // Mirror the angle: t -> -t with y -> -y keeps the points.
+ case 'circle': return { ...c, y: mul(c.y, -1), a0: -c.a1, a1: -c.a0 };
+ case 'ellipse': return { ...c, y: mul(c.y, -1), a0: -c.a1, a1: -c.a0 };
+ case 'nurbs': return { kind: 'nurbs', n: reverseCurve(c.n) };
+ }
+}
+
+/** A curve as one NURBS (exact). */
+export function toNurbs(c: Curve3): NurbsCurve {
+ switch (c.kind) {
+ case 'line': return lineCurve(c.a, c.b);
+ case 'circle': return arcCurve(c.c, mul(c.x, c.r), mul(c.y, c.r), c.a0, c.a1);
+ case 'ellipse': return arcCurve(c.c, mul(c.x, c.r1), mul(c.y, c.r2), c.a0, c.a1);
+ case 'nurbs': return c.n;
+ }
+}
+
+/** Joins curves end to end into one NURBS (degree raised to the highest, C0 joins). */
+export function joinNurbs(list: NurbsCurve[]): NurbsCurve {
+ if (list.length === 1) return clampCurve(list[0]);
+ const deg = Math.max(...list.map((c) => c.degree));
+ let t = 0;
+ const parts = list.map((c0) => {
+ let c = clampCurve(c0);
+ while (c.degree < deg) c = elevateDegree(c);
+ const len = Math.max(1e-9, distance(c.poles[0], c.poles[c.poles.length - 1]) || 1);
+ c = reparamCurve(c, t, t + len);
+ t += len;
+ return c;
+ });
+ const rational = parts.some((c) => c.weights);
+ const poles: Pt[] = [...parts[0].poles];
+ const weights: number[] = [...(parts[0].weights ?? parts[0].poles.map(() => 1))];
+ const knots = parts[0].knots.slice(0, -1);
+ for (const c of parts.slice(1)) {
+ let w = c.weights ?? c.poles.map(() => 1);
+ // Scale the weights so the shared pole has one weight (the curve is unchanged).
+ const f = weights[weights.length - 1] / w[0];
+ w = w.map((x) => x * f);
+ poles.push(...c.poles.slice(1));
+ weights.push(...w.slice(1));
+ knots.push(...c.knots.slice(deg + 1, -1));
+ }
+ knots.push(t);
+ return { degree: deg, knots, poles, weights: rational ? weights : null };
+}
+
+const near = (a: Pt, b: Pt, tol: number) => distance(a, b) <= tol;
+
+/** Orders a loop head to tail, reversing pieces drawn the other way. */
+function orientLoop(loop: Curve3[], tol: number): Curve3[] {
+ const out: Curve3[] = [];
+ for (let i = 0; i < loop.length; i++) {
+ let c = loop[i];
+ if (out.length) {
+ const prev = curveEnd(out[out.length - 1]);
+ if (!near(curveStart(c), prev, tol) && near(curveEnd(c), prev, tol)) c = reverse(c);
+ } else if (loop.length > 1) {
+ // The first piece: it must lead into the second.
+ const next = loop[1];
+ const e = curveEnd(c);
+ if (!near(e, curveStart(next), tol) && !near(e, curveEnd(next), tol)) {
+ const s = curveStart(c);
+ if (near(s, curveStart(next), tol) || near(s, curveEnd(next), tol)) c = reverse(c);
+ }
+ }
+ out.push(c);
+ }
+ return out;
+}
+
+const isDegenerate = (c: Curve3, tol: number) => {
+ if (c.kind === 'line') return near(c.a, c.b, tol);
+ if (c.kind === 'circle') return c.r <= tol;
+ if (c.kind === 'nurbs') return c.n.poles.every((p) => near(p, c.n.poles[0], tol));
+ return false;
+};
+
+// ---------- the converter ----------
+
+export function convertIges(file: IgesFile): IgesModel {
+ return new Converter(file).run();
+}
+
+class Converter {
+ private faces: TrimmedFace[] = [];
+ private breps: Brep[] = [];
+ private skipped = 0;
+ private problems: string[] = [];
+ private tol: number;
+ private size = 0;
+ private transforms = new Map();
+
+ constructor(private file: IgesFile) {
+ this.tol = Math.max((file.resolution || 0) * file.unit, 1e-6);
+ }
+
+ private ent(de: number): IgesEntity {
+ const e = this.file.entities.get(de);
+ if (!e) throw new IgesError(`Entity ${de} is missing`);
+ return e;
+ }
+
+ private p(e: IgesEntity, i: number, fallback = 0) { return num(e.params[i], fallback); }
+ private ip(e: IgesEntity, i: number, fallback = 0) { return int(e.params[i], fallback); }
+
+ /** The transform an entity's coordinates are placed with (its 124, after the parent's). */
+ private placed(e: IgesEntity, parent: Mat): Mat {
+ return e.transform > 0 ? compose(parent, this.matrix(e.transform)) : parent;
+ }
+
+ private matrix(de: number, depth = 0): Mat {
+ const hit = this.transforms.get(de);
+ if (hit) return hit;
+ const e = this.ent(de);
+ if (e.type !== 124 || depth > 50) return IDENT;
+ const v = Array.from({ length: 12 }, (_, i) => this.p(e, i, [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0][i]));
+ const m = e.transform > 0 && e.transform !== de ? compose(this.matrix(e.transform, depth + 1), v) : v;
+ this.transforms.set(de, m);
+ return m;
+ }
+
+ private note(p: Pt) {
+ for (const x of p) this.size = Math.max(this.size, Math.abs(x));
+ }
+
+ run(): IgesModel {
+ const all = [...this.file.entities.values()];
+ const units = scaleMat(this.file.unit);
+ const isRoot = (e: IgesEntity) => e.subordinate === 0 || e.subordinate === 2;
+ const visible = all.filter((e) => isRoot(e) && !e.blank);
+ // Everything blanked: take what there is (some systems blank whole models).
+ const roots = (visible.some((e) => FACE_TYPES.has(e.type)) ? visible : all.filter(isRoot)).filter((e) => e.use !== 5);
+ for (const e of roots) this.root(e, units, 0);
+ if (!this.faces.length && !this.breps.length) {
+ const curves = all.some((e) => [100, 102, 104, 106, 110, 112, 126].includes(e.type));
+ throw new IgesError(this.skipped
+ ? `None of the surfaces in this IGES file could be read (${this.problems[0] ?? 'unsupported entities'}).`
+ : curves ? 'This IGES file has only curves or points: there are no surfaces or solids to import.' : 'This IGES file has no surfaces or solids to import.');
+ }
+ return { faces: this.faces, breps: this.breps, skipped: this.skipped, problems: this.problems, resolution: (this.file.resolution || 0) * this.file.unit, size: this.size };
+ }
+
+ private fail(e: IgesEntity, err: unknown) {
+ this.skipped++;
+ const msg = err instanceof Error ? err.message : String(err);
+ if (this.problems.length < 20) this.problems.push(`${e.type}#${e.de}: ${msg}`);
+ }
+
+ private root(e: IgesEntity, m: Mat, depth: number) {
+ if (depth > 20) return;
+ try {
+ switch (e.type) {
+ case 144: this.trimmed(e, m); break;
+ case 143: this.bounded(e, m); break;
+ case 186: this.msbo(e, m); break;
+ case 108: if (e.form === 1) this.boundedPlane(e, m); break;
+ // An untrimmed surface on its own is a face over its whole domain.
+ case 128: case 118: case 120: case 122: case 114: this.untrimmed(e, m); break;
+ case 408: this.instance(e, m, depth); break;
+ default: break;
+ }
+ } catch (err) {
+ this.fail(e, err);
+ }
+ }
+
+ // ----- faces -----
+
+ private trimmed(e: IgesEntity, parent: Mat) {
+ const m = this.placed(e, parent);
+ const { surf, nurbs, sense } = this.surface(this.ip(e, 0), m);
+ const n1 = this.ip(e, 1), n2 = this.ip(e, 2);
+ const loops: Curve3[][] = [];
+ if (n1 === 0) {
+ if (!nurbs) throw new IgesError('an unbounded surface has no outer boundary');
+ loops.push(naturalLoop(nurbs, this.tol));
+ } else loops.push(this.curveOnSurface(this.ip(e, 3), m, nurbs));
+ for (let i = 0; i < n2; i++) loops.push(this.curveOnSurface(this.ip(e, 4 + i), m, nurbs));
+ this.addFace(surf, sense, loops);
+ }
+
+ private bounded(e: IgesEntity, parent: Mat) {
+ const m = this.placed(e, parent);
+ const { surf, sense } = this.surface(this.ip(e, 1), m);
+ const n = this.ip(e, 2);
+ const loops: Curve3[][] = [];
+ for (let i = 0; i < n; i++) {
+ const b = this.ent(this.ip(e, 3 + i));
+ const bm = this.placed(b, m);
+ const k = this.ip(b, 3);
+ const loop: Curve3[] = [];
+ let at = 4;
+ for (let j = 0; j < k; j++) {
+ const crv = this.ip(b, at), sense = this.ip(b, at + 1, 1), nk = this.ip(b, at + 2);
+ let cs = this.curves(crv, bm);
+ if (sense === 2) cs = cs.reverse().map(reverse);
+ loop.push(...cs);
+ at += 3 + nk;
+ }
+ loops.push(loop);
+ }
+ this.addFace(surf, sense, loops);
+ }
+
+ private boundedPlane(e: IgesEntity, parent: Mat) {
+ const m = this.placed(e, parent);
+ const { surf } = this.surface(e.de, parent);
+ const ptr = this.ip(e, 4);
+ if (!ptr) return;
+ this.addFace(surf, true, [this.curves(ptr, m)]);
+ }
+
+ private untrimmed(e: IgesEntity, m: Mat) {
+ const { surf, nurbs, sense } = this.surface(e.de, m);
+ if (!nurbs) throw new IgesError('an unbounded surface has no boundary');
+ this.addFace(surf, sense, [naturalLoop(nurbs, this.tol)]);
+ }
+
+ private addFace(surface: Surf, sense: boolean, loops: Curve3[][]) {
+ const clean = loops.map((l) => orientLoop(l.filter((c) => !isDegenerate(c, this.tol * 0.01)).map((c) => recogniseCurve(c, this.tol)), Math.max(this.tol * 10, 1e-4))).filter((l) => l.length);
+ if (!clean.length) throw new IgesError('the face has no boundary');
+ for (const l of clean) for (const c of l) this.note(curveStart(c));
+ this.faces.push({ surface, sense, loops: clean });
+ }
+
+ /** A 142's boundary as model-space curves; from the parameter-space curve when there is no model-space one. */
+ private curveOnSurface(de: number, parent: Mat, nurbs: NurbsSurface | null): Curve3[] {
+ const e = this.ent(de);
+ if (e.type !== 142) return this.curves(de, parent);
+ const m = this.placed(e, parent);
+ const bptr = this.ip(e, 2), cptr = this.ip(e, 3);
+ if (cptr) {
+ try {
+ return this.curves(cptr, m);
+ } catch (err) {
+ if (!bptr || !nurbs) throw err;
+ }
+ }
+ if (!bptr || !nurbs) throw new IgesError('a boundary has no curve');
+ return this.paramCurves(bptr).map((c2) => {
+ const [a, b] = curveDomain(c2);
+ const ev = (t: number) => { const q = curvePoint(c2, t); return surfacePoint(nurbs, q[0], q[1]); };
+ return { kind: 'nurbs', n: fitCurve(ev, a, b, Math.max(this.tol, 1e-7)) } as Curve3;
+ });
+ }
+
+ /** Curves in a surface's parameter space, as 2D NURBS. */
+ private paramCurves(de: number): NurbsCurve[] {
+ return this.curves(de, IDENT, true).map((c) => mapCurve(toNurbs(c), (p) => [p[0], p[1]]));
+ }
+
+ // ----- curves -----
+
+ /** Model-space curve pieces in order (composites flattened). */
+ curves(de: number, parent: Mat, param = false, depth = 0): Curve3[] {
+ const e = this.ent(de);
+ if (depth > 50) throw new IgesError('composite curves nest too deeply');
+ const m = param ? IDENT : this.placed(e, parent);
+ const s = scaleOf(m);
+ switch (e.type) {
+ case 110: return [{ kind: 'line', a: apply(m, [this.p(e, 0), this.p(e, 1), this.p(e, 2)]), b: apply(m, [this.p(e, 3), this.p(e, 4), this.p(e, 5)]) }];
+ case 100: {
+ const zt = this.p(e, 0);
+ const c = [this.p(e, 1), this.p(e, 2)], a = [this.p(e, 3), this.p(e, 4)], b = [this.p(e, 5), this.p(e, 6)];
+ const r = Math.hypot(a[0] - c[0], a[1] - c[1]);
+ const a0 = Math.atan2(a[1] - c[1], a[0] - c[0]);
+ let a1 = Math.atan2(b[1] - c[1], b[0] - c[0]);
+ if (Math.hypot(a[0] - b[0], a[1] - b[1]) <= 1e-9 * Math.max(1, r)) a1 = a0 + 2 * Math.PI;
+ while (a1 <= a0 + 1e-12) a1 += 2 * Math.PI;
+ const x = applyDir(m, [1, 0, 0]), y = applyDir(m, [0, 1, 0]);
+ return [{ kind: 'circle', c: apply(m, [c[0], c[1], zt]), x: unit(x), y: unit(y), r: r * s, a0, a1 }];
+ }
+ case 102: {
+ const n = this.ip(e, 0);
+ const out: Curve3[] = [];
+ for (let i = 0; i < n; i++) out.push(...this.curves(this.ip(e, 1 + i), m, param, depth + 1));
+ return out;
+ }
+ case 104: return [this.conic(e, m)];
+ case 106: return this.polyline(e, m);
+ case 112: return [{ kind: 'nurbs', n: mapCurve(this.parametricSpline(e), (p) => apply(m, p)) }];
+ case 126: {
+ const n = this.bspline(e);
+ return [{ kind: 'nurbs', n: param ? n : mapCurve(n, (p) => apply(m, p)) }];
+ }
+ case 116: throw new IgesError('a boundary is a single point');
+ default: throw new IgesError(`curve type ${e.type} is not supported`);
+ }
+ }
+
+ private bspline(e: IgesEntity): NurbsCurve {
+ const K = this.ip(e, 0), M = this.ip(e, 1);
+ const poly = this.ip(e, 4) === 1;
+ const nk = K + M + 2;
+ if (K < 0 || M < 1 || K + 1 < M || nk > 1e7) throw new IgesError('a B-spline curve has invalid sizes');
+ let at = 6;
+ const knots = Array.from({ length: nk }, (_, i) => this.p(e, at + i));
+ at += nk;
+ const weights = Array.from({ length: K + 1 }, (_, i) => this.p(e, at + i, 1));
+ at += K + 1;
+ const poles = Array.from({ length: K + 1 }, (_, i) => [this.p(e, at + 3 * i), this.p(e, at + 3 * i + 1), this.p(e, at + 3 * i + 2)]);
+ at += 3 * (K + 1);
+ const v0 = this.p(e, at, knots[M]), v1 = this.p(e, at + 1, knots[K + 1]);
+ const c: NurbsCurve = { degree: M, knots, poles, weights: poly || weights.every((w) => w === 1) ? null : weights };
+ if (c.weights && weights.some((w) => !(w > 0))) throw new IgesError('a B-spline curve has invalid weights');
+ return clampCurve(c, Math.min(v0, v1), Math.max(v0, v1));
+ }
+
+ private parametricSpline(e: IgesEntity): NurbsCurve {
+ const deg = 3, ndim = this.ip(e, 2), n = this.ip(e, 3);
+ if (n < 1 || n > 1e6) throw new IgesError('a parametric spline has no segments');
+ const T = Array.from({ length: n + 1 }, (_, i) => this.p(e, 4 + i));
+ let at = 5 + n;
+ const poles: Pt[] = [];
+ const knots: number[] = [T[0], T[0], T[0], T[0]];
+ for (let i = 0; i < n; i++) {
+ const h = T[i + 1] - T[i];
+ const co = Array.from({ length: 12 }, (_, k) => this.p(e, at + k));
+ at += 12;
+ // Power basis in s = t - T[i] to Bezier over [0, h].
+ const axis = (k: number) => {
+ const a = co[4 * k], b = co[4 * k + 1] * h, c = co[4 * k + 2] * h * h, d = co[4 * k + 3] * h * h * h;
+ return [a, a + b / 3, a + (2 * b) / 3 + c / 3, a + b + c + d];
+ };
+ const xs = axis(0), ys = axis(1), zs = ndim === 2 ? [0, 0, 0, 0] : axis(2);
+ const bez = [0, 1, 2, 3].map((k) => [xs[k], ys[k], zs[k]]);
+ if (i === 0) poles.push(bez[0]);
+ poles.push(bez[1], bez[2], bez[3]);
+ if (i < n - 1) knots.push(T[i + 1], T[i + 1], T[i + 1]);
+ }
+ knots.push(T[n], T[n], T[n], T[n]);
+ return { degree: deg, knots, poles, weights: null };
+ }
+
+ private conic(e: IgesEntity, m: Mat): Curve3 {
+ const [A, B, C, D, E, F, zt, x1, y1, x2, y2] = Array.from({ length: 11 }, (_, i) => this.p(e, i));
+ // Centre and axes of A x^2 + B xy + C y^2 + D x + E y + F = 0.
+ const det = 4 * A * C - B * B;
+ let theta = 0.5 * Math.atan2(B, A - C);
+ // The major axis along x' (the smaller coefficient there).
+ const along = (t: number) => A * Math.cos(t) ** 2 + B * Math.cos(t) * Math.sin(t) + C * Math.sin(t) ** 2;
+ if (Math.abs(along(theta)) > Math.abs(along(theta + Math.PI / 2))) theta += Math.PI / 2;
+ const cs = Math.cos(theta), sn = Math.sin(theta);
+ const local = (x: number, y: number, cx: number, cy: number) => [(x - cx) * cs + (y - cy) * sn, -(x - cx) * sn + (y - cy) * cs];
+ const s = scaleOf(m);
+ if (e.form === 1 || (e.form === 0 && det > 0)) {
+ const cx = (B * E - 2 * C * D) / det, cy = (B * D - 2 * A * E) / det;
+ const Fc = A * cx * cx + B * cx * cy + C * cy * cy + D * cx + E * cy + F;
+ const Ar = A * cs * cs + B * cs * sn + C * sn * sn, Cr = A * sn * sn - B * cs * sn + C * cs * cs;
+ const ra = Math.sqrt(-Fc / Ar), rb = Math.sqrt(-Fc / Cr);
+ if (!(ra > 0) || !(rb > 0)) throw new IgesError('an ellipse has invalid coefficients');
+ const [p0x, p0y] = local(x1, y1, cx, cy), [p1x, p1y] = local(x2, y2, cx, cy);
+ const a0 = Math.atan2(p0y / rb, p0x / ra);
+ let a1 = Math.atan2(p1y / rb, p1x / ra);
+ if (Math.hypot(x1 - x2, y1 - y2) <= 1e-9 * Math.max(ra, rb)) a1 = a0 + 2 * Math.PI;
+ while (a1 <= a0 + 1e-12) a1 += 2 * Math.PI;
+ const X = unit(applyDir(m, [cs, sn, 0])), Y = unit(applyDir(m, [-sn, cs, 0]));
+ const c = apply(m, [cx, cy, zt]);
+ if (Math.abs(ra - rb) <= 1e-12 * ra) return { kind: 'circle', c, x: X, y: Y, r: ra * s, a0, a1 };
+ return { kind: 'ellipse', c, x: X, y: Y, r1: ra * s, r2: rb * s, a0, a1 };
+ }
+ // Parabolas and hyperbolas: sampled along x' or y' between the end points.
+ const ev = (t: number): Pt => {
+ // Solve the conic for the other coordinate near the straight path between the ends.
+ const x = x1 + (x2 - x1) * t, y = y1 + (y2 - y1) * t;
+ // Newton along the conic's gradient from the chord point.
+ let px = x, py = y;
+ for (let k = 0; k < 30; k++) {
+ const f = A * px * px + B * px * py + C * py * py + D * px + E * py + F;
+ const gx = 2 * A * px + B * py + D, gy = B * px + 2 * C * py + E;
+ const g2 = gx * gx + gy * gy;
+ if (g2 < 1e-300) break;
+ px -= (f * gx) / g2; py -= (f * gy) / g2;
+ if (Math.abs(f) < 1e-14) break;
+ }
+ return apply(m, [px, py, zt]);
+ };
+ return { kind: 'nurbs', n: fitCurve(ev, 0, 1, Math.max(this.tol, 1e-7)) };
+ }
+
+ private polyline(e: IgesEntity, m: Mat): Curve3[] {
+ const ip = this.ip(e, 0), n = this.ip(e, 1);
+ if (n < 2 || n > 1e7) throw new IgesError('a polyline has too few points');
+ const pts: Pt[] = [];
+ if (ip === 1) {
+ const zt = this.p(e, 2);
+ for (let i = 0; i < n; i++) pts.push([this.p(e, 3 + 2 * i), this.p(e, 4 + 2 * i), zt]);
+ } else {
+ const stride = ip === 3 ? 6 : 3;
+ for (let i = 0; i < n; i++) pts.push([this.p(e, 2 + stride * i), this.p(e, 3 + stride * i), this.p(e, 4 + stride * i)]);
+ }
+ const w = pts.map((p) => apply(m, p));
+ if (e.form === 63 && !near(w[0], w[w.length - 1], 1e-12)) w.push(w[0]);
+ const out: Curve3[] = [];
+ for (let i = 0; i + 1 < w.length; i++) if (!near(w[i], w[i + 1], 1e-12)) out.push({ kind: 'line', a: w[i], b: w[i + 1] });
+ return out;
+ }
+
+ /** A curve entity as a single NURBS (composites joined). */
+ private singleCurve(de: number, m: Mat): { curve: Curve3; nurbs: NurbsCurve } {
+ const cs = orientLoop(this.curves(de, m), Math.max(this.tol * 10, 1e-6));
+ if (cs.length === 1) return { curve: cs[0], nurbs: toNurbs(cs[0]) };
+ const n = joinNurbs(cs.map(toNurbs));
+ return { curve: { kind: 'nurbs', n }, nurbs: n };
+ }
+
+ // ----- surfaces -----
+
+ /** A surface entity: its exact form for STEP, and NURBS where it has a parametrisation (for natural boundaries and parameter-space curves). */
+ private surface(de: number, parent: Mat): { surf: Surf; nurbs: NurbsSurface | null; sense: boolean } {
+ const e = this.ent(de);
+ const m = this.placed(e, parent);
+ const s = scaleOf(m);
+ switch (e.type) {
+ case 128: {
+ const n = mapSurface(this.bsplineSurface(e), (p) => apply(m, p));
+ return withSense(recogniseNurbs(n, this.tol), n);
+ }
+ case 108: {
+ const A = this.p(e, 0), B = this.p(e, 1), C = this.p(e, 2), D = this.p(e, 3);
+ const l2 = A * A + B * B + C * C;
+ if (!(l2 > 0)) throw new IgesError('a plane has no normal');
+ const n = [A, B, C];
+ const o = apply(m, mul(n, D / l2));
+ const z = unit(applyDir(m, n));
+ return { surf: { kind: 'plane', o, z, x: perpendicular(z) }, nurbs: null, sense: true };
+ }
+ case 190: case 192: case 194: case 196: case 198: return { surf: this.analytic(e, m, s), nurbs: null, sense: true };
+ case 118: {
+ const c0 = this.singleCurve(this.ip(e, 0), m).nurbs;
+ let c1 = this.singleCurve(this.ip(e, 1), m).nurbs;
+ if (this.ip(e, 2) === 1) c1 = reverseCurve(c1);
+ const n = ruledSurface(c0, c1);
+ if (!n) throw new IgesError('a ruled surface could not be built');
+ return withSense(recogniseNurbs(n, this.tol), n);
+ }
+ case 120: {
+ const axis = this.curves(this.ip(e, 0), m)[0];
+ if (axis?.kind !== 'line') throw new IgesError('a surface of revolution has no axis line');
+ const g = this.singleCurve(this.ip(e, 1), m);
+ const a0 = this.p(e, 2), a1 = this.p(e, 3, 2 * Math.PI);
+ const o = axis.a, z = unit(sub(axis.b, axis.a));
+ const n = revolveCurve(g.nurbs, o, z, Math.min(a0, a1), Math.max(a0, a1));
+ return withSense(revolution(g.curve, o, z, this.tol), n);
+ }
+ case 122: {
+ const g = this.singleCurve(this.ip(e, 0), m);
+ const end = apply(m, [this.p(e, 1), this.p(e, 2), this.p(e, 3)]);
+ const d = sub(end, curveStart(g.curve));
+ const n = extrudeCurve(reparamCurve(g.nurbs, 0, 1), d, 0, 1);
+ return withSense(extrusion(g.curve, d, this.tol), n);
+ }
+ case 114: {
+ const n = mapSurface(this.parametricSurface(e), (p) => apply(m, p));
+ return withSense(recogniseNurbs(n, this.tol), n);
+ }
+ case 140: throw new IgesError('offset surfaces are not supported');
+ default: throw new IgesError(`surface type ${e.type} is not supported`);
+ }
+ }
+
+ private bsplineSurface(e: IgesEntity): NurbsSurface {
+ const K1 = this.ip(e, 0), K2 = this.ip(e, 1), M1 = this.ip(e, 2), M2 = this.ip(e, 3);
+ const poly = this.ip(e, 6) === 1;
+ const n1 = K1 + M1 + 2, n2 = K2 + M2 + 2;
+ if (K1 < 0 || K2 < 0 || M1 < 1 || M2 < 1 || (K1 + 1) * (K2 + 1) > 4e6) throw new IgesError('a B-spline surface has invalid sizes');
+ let at = 9;
+ const knotsU = Array.from({ length: n1 }, (_, i) => this.p(e, at + i));
+ at += n1;
+ const knotsV = Array.from({ length: n2 }, (_, i) => this.p(e, at + i));
+ at += n2;
+ const nu = K1 + 1, nv = K2 + 1;
+ const weights: number[][] = Array.from({ length: nu }, () => new Array(nv).fill(1));
+ for (let j = 0; j < nv; j++) for (let i = 0; i < nu; i++) weights[i][j] = this.p(e, at + j * nu + i, 1);
+ at += nu * nv;
+ const poles: Pt[][] = Array.from({ length: nu }, () => new Array(nv));
+ for (let j = 0; j < nv; j++) {
+ for (let i = 0; i < nu; i++) {
+ const k = at + 3 * (j * nu + i);
+ poles[i][j] = [this.p(e, k), this.p(e, k + 1), this.p(e, k + 2)];
+ }
+ }
+ at += 3 * nu * nv;
+ const range: [number, number, number, number] = [this.p(e, at, knotsU[M1]), this.p(e, at + 1, knotsU[K1 + 1]), this.p(e, at + 2, knotsV[M2]), this.p(e, at + 3, knotsV[K2 + 1])];
+ const rational = !poly && weights.some((r) => r.some((w) => w !== 1));
+ if (rational && weights.some((r) => r.some((w) => !(w > 0)))) throw new IgesError('a B-spline surface has invalid weights');
+ const s: NurbsSurface = { degU: M1, degV: M2, knotsU, knotsV, poles, weights: rational ? weights : null };
+ return clampSurface(s, [Math.min(range[0], range[1]), Math.max(range[0], range[1]), Math.min(range[2], range[3]), Math.max(range[2], range[3])]);
+ }
+
+ /**
+ * 114: bicubic polynomial patches. Each patch has 16 coefficients per axis
+ * for s^k t^l (s = u - TU(i), t = v - TV(j)), listed with k varying
+ * fastest; patches are listed by u segment, then v segment, each list
+ * ending with an unused patch.
+ */
+ private parametricSurface(e: IgesEntity): NurbsSurface {
+ const M = this.ip(e, 2), N = this.ip(e, 3);
+ if (M < 1 || N < 1 || (M + 1) * (N + 1) > 1e6) throw new IgesError('a parametric spline surface has no patches');
+ const TU = Array.from({ length: M + 1 }, (_, i) => this.p(e, 4 + i));
+ const TV = Array.from({ length: N + 1 }, (_, i) => this.p(e, 5 + M + i));
+ let at = 6 + M + N;
+ const poles: Pt[][] = Array.from({ length: 3 * M + 1 }, () => new Array(3 * N + 1));
+ // Power basis to Bernstein for a cubic on [0, 1].
+ const P = [[1, 0, 0, 0], [1, 1 / 3, 0, 0], [1, 2 / 3, 1 / 3, 0], [1, 1, 1, 1]];
+ for (let i = 0; i <= M; i++) {
+ for (let j = 0; j <= N; j++) {
+ const base = at;
+ at += 48;
+ if (i === M || j === N) continue;
+ const hu = TU[i + 1] - TU[i], hv = TV[j + 1] - TV[j];
+ const coef = (ax: number, k: number, l: number) => this.p(e, base + ax * 16 + l * 4 + k) * hu ** k * hv ** l;
+ for (let r = 0; r < 4; r++) {
+ for (let c = 0; c < 4; c++) {
+ const pt = [0, 1, 2].map((ax) => {
+ let v = 0;
+ for (let k = 0; k < 4; k++) for (let l = 0; l < 4; l++) v += P[r][k] * P[c][l] * coef(ax, k, l);
+ return v;
+ });
+ poles[3 * i + r][3 * j + c] = pt;
+ }
+ }
+ }
+ }
+ const knots = (T: number[]) => [T[0], ...T.flatMap((t) => [t, t, t]), T[T.length - 1]];
+ return { degU: 3, degV: 3, knotsU: knots(TU), knotsV: knots(TV), poles, weights: null };
+ }
+
+ private analytic(e: IgesEntity, m: Mat, s: number): Surf {
+ const point = (de: number): Pt => { const q = this.ent(de); return apply(this.placed(q, m), [this.p(q, 0), this.p(q, 1), this.p(q, 2)]); };
+ const dir = (de: number): Pt => { const q = this.ent(de); return unit(applyDir(this.placed(q, m), [this.p(q, 0), this.p(q, 1), this.p(q, 2)])); };
+ const frame = (z: Pt, refPtr: number) => {
+ if (!refPtr) return perpendicular(z);
+ const r = dir(refPtr);
+ const x = sub(r, mul(z, dot(r, z)));
+ return norm(x) > 1e-12 ? unit(x) : perpendicular(z);
+ };
+ switch (e.type) {
+ case 190: { const z = dir(this.ip(e, 1)); return { kind: 'plane', o: point(this.ip(e, 0)), z, x: frame(z, e.form === 1 ? this.ip(e, 2) : 0) }; }
+ case 192: { const z = dir(this.ip(e, 1)); return { kind: 'cylinder', o: point(this.ip(e, 0)), z, x: frame(z, e.form === 1 ? this.ip(e, 3) : 0), r: this.p(e, 2) * s }; }
+ case 194: {
+ const z = dir(this.ip(e, 1));
+ return { kind: 'cone', o: point(this.ip(e, 0)), z, x: frame(z, e.form === 1 ? this.ip(e, 4) : 0), r: this.p(e, 2) * s, angle: (this.p(e, 3) * Math.PI) / 180 };
+ }
+ case 196: {
+ const z = e.form === 1 && this.ip(e, 2) ? dir(this.ip(e, 2)) : [0, 0, 1];
+ return { kind: 'sphere', o: point(this.ip(e, 0)), z, x: frame(z, e.form === 1 ? this.ip(e, 3) : 0), r: this.p(e, 1) * s };
+ }
+ default: {
+ const z = dir(this.ip(e, 1));
+ return { kind: 'torus', o: point(this.ip(e, 0)), z, x: frame(z, e.form === 1 ? this.ip(e, 4) : 0), R: this.p(e, 2) * s, r: this.p(e, 3) * s };
+ }
+ }
+ }
+
+ // ----- solids -----
+
+ private msbo(e: IgesEntity, parent: Mat) {
+ const m = this.placed(e, parent);
+ const brep: Brep = { vertices: [], edges: [], shells: [] };
+ const vIndex = new Map(), eIndex = new Map();
+ const vertex = (list: number, i: number) => {
+ const key = `${list}:${i}`;
+ let k = vIndex.get(key);
+ if (k == null) {
+ const v = this.ent(list);
+ const vm = this.placed(v, m);
+ const at = 1 + 3 * (i - 1);
+ const p = apply(vm, [this.p(v, at), this.p(v, at + 1), this.p(v, at + 2)]);
+ this.note(p);
+ k = brep.vertices.push(p) - 1;
+ vIndex.set(key, k);
+ }
+ return k;
+ };
+ const edge = (list: number, i: number) => {
+ const key = `${list}:${i}`;
+ let k = eIndex.get(key);
+ if (k == null) {
+ const el = this.ent(list);
+ const em = this.placed(el, m);
+ const at = 1 + 5 * (i - 1);
+ const cs = this.curves(this.ip(el, at), em);
+ const v0 = vertex(this.ip(el, at + 1), this.ip(el, at + 2)), v1 = vertex(this.ip(el, at + 3), this.ip(el, at + 4));
+ const curve = recogniseCurve(cs.length === 1 ? cs[0] : { kind: 'nurbs' as const, n: joinNurbs(orientLoop(cs, 1e-6).map(toNurbs)) }, this.tol);
+ k = brep.edges.push({ curve, v0, v1 }) - 1;
+ eIndex.set(key, k);
+ }
+ return k;
+ };
+ const shell = (de: number, sense: boolean): BrepFace[] => {
+ const sh = this.ent(de);
+ const sm = this.placed(sh, m);
+ const n = this.ip(sh, 0);
+ const out: BrepFace[] = [];
+ for (let i = 0; i < n; i++) {
+ const fd = this.ip(sh, 1 + 2 * i), of = this.ip(sh, 2 + 2 * i, 1) === 1;
+ try {
+ const f = this.ent(fd);
+ const fm = this.placed(f, sm);
+ const { surf, sense: same } = this.surface(this.ip(f, 0), fm);
+ const nl = this.ip(f, 1);
+ const loops: { e: number; fwd: boolean }[][] = [];
+ for (let l = 0; l < nl; l++) {
+ const lp = this.ent(this.ip(f, 3 + l));
+ const ne = this.ip(lp, 0);
+ const loop: { e: number; fwd: boolean }[] = [];
+ let at = 1;
+ for (let k = 0; k < ne; k++) {
+ const type = this.ip(lp, at), list = this.ip(lp, at + 1), ndx = this.ip(lp, at + 2), o = this.ip(lp, at + 3, 1);
+ const nk = this.ip(lp, at + 4);
+ at += 5 + 2 * nk;
+ if (type === 1) continue; // a vertex loop
+ loop.push({ e: edge(list, ndx), fwd: o === 1 });
+ }
+ if (loop.length) loops.push(loop);
+ }
+ if (loops.length) out.push({ surface: surf, sense: (of === sense) === same, loops });
+ } catch (err) {
+ this.fail(this.ent(fd), err);
+ }
+ }
+ return out;
+ };
+ brep.shells.push(shell(this.ip(e, 0), this.ip(e, 1, 1) === 1));
+ const nv = this.ip(e, 2);
+ for (let i = 0; i < nv; i++) brep.shells.push(shell(this.ip(e, 3 + 2 * i), this.ip(e, 4 + 2 * i, 1) === 1));
+ if (brep.shells[0].length) this.breps.push(brep);
+ }
+
+ private instance(e: IgesEntity, parent: Mat, depth: number) {
+ const def = this.ent(this.ip(e, 0));
+ if (def.type !== 308) return;
+ const sc = this.p(e, 4, 1) || 1;
+ const local: Mat = [sc, 0, 0, this.p(e, 1), 0, sc, 0, this.p(e, 2), 0, 0, sc, this.p(e, 3)];
+ const m = compose(this.placed(e, parent), local);
+ const n = this.ip(def, 2);
+ const dm = this.placed(def, m);
+ for (let i = 0; i < n; i++) {
+ const child = this.file.entities.get(this.ip(def, 3 + i));
+ if (child) this.root(child, dm, depth + 1);
+ }
+ }
+}
+
+const FACE_TYPES = new Set([144, 143, 186, 108, 128, 118, 120, 122, 114, 408]);
+
+/** The boundary of a NURBS surface's whole domain, without collapsed sides. */
+function naturalLoop(s: NurbsSurface, tol: number): Curve3[] {
+ const [u0, u1, v0, v1] = surfaceDomain(s);
+ const sides = [
+ isoCurve(s, 'u', v0),
+ isoCurve(s, 'v', u1),
+ reverseCurve(isoCurve(s, 'u', v1)),
+ reverseCurve(isoCurve(s, 'v', u0)),
+ ];
+ return sides.filter((c) => !c.poles.every((p) => distance(p, c.poles[0]) <= tol)).map((n) => ({ kind: 'nurbs', n }) as Curve3);
+}
+
+// ---------- recognising exact surfaces ----------
+
+/** The normal of an exact surface at a point on it (as the kernel orients it), or null where it has none. */
+function exactNormal(s: Surf, p: Pt): Pt | null {
+ if (s.kind === 'plane') return s.z;
+ if (s.kind !== 'cylinder' && s.kind !== 'cone' && s.kind !== 'sphere' && s.kind !== 'torus') return null;
+ const d = sub(p, s.o);
+ const h = dot(d, s.z);
+ const radial = sub(d, mul(s.z, h));
+ const rho = norm(radial);
+ if (s.kind === 'sphere') return norm(d) > 0 ? unit(d) : null;
+ if (!(rho > 0)) return null;
+ if (s.kind === 'cylinder') return mul(radial, 1 / rho);
+ if (s.kind === 'cone') return sub(mul(radial, Math.cos(s.angle) / rho), mul(s.z, Math.sin(s.angle)));
+ const n = sub(d, mul(radial, s.R / rho));
+ return norm(n) > 0 ? unit(n) : null;
+}
+
+/**
+ * An exact surface recognised from a NURBS one, and whether it faces the same
+ * way: boundaries run counterclockwise about the file's surface normal, and
+ * the exact surface's own orientation (its axis) may be the other way round.
+ */
+function withSense(surf: Surf, n: NurbsSurface): { surf: Surf; nurbs: NurbsSurface; sense: boolean } {
+ const [u0, u1, v0, v1] = surfaceDomain(n);
+ for (const [fu, fv] of [[0.5, 0.5], [0.31, 0.63], [0.71, 0.27]]) {
+ const u = u0 + (u1 - u0) * fu, v = v0 + (v1 - v0) * fv;
+ const hu = (u1 - u0) * 1e-6, hv = (v1 - v0) * 1e-6;
+ const su = sub(surfacePoint(n, u + hu, v), surfacePoint(n, u - hu, v));
+ const sv = sub(surfacePoint(n, u, v + hv), surfacePoint(n, u, v - hv));
+ const normal = cross(su, sv);
+ const want = exactNormal(surf, surfacePoint(n, u, v));
+ // Skip a point where the NURBS is degenerate (a pole) or the exact surface has no normal.
+ if (!want || !(norm(normal) > 1e-6 * norm(su) * norm(sv))) continue;
+ const c = dot(unit(normal), want);
+ if (Math.abs(c) > 0.5) return { surf, nurbs: n, sense: c > 0 };
+ }
+ return { surf, nurbs: n, sense: true };
+}
+
+/** A NURBS surface as a plane, cylinder, cone, sphere or torus when it is one (checked on a grid of points); else NURBS. */
+function recogniseNurbs(n: NurbsSurface, tol: number): Surf {
+ const pts = n.poles.flat();
+ const o = pts[0];
+ const size = Math.max(...pts.map((p) => distance(p, o)), 1e-9);
+ const eps = Math.max(tol, size * 1e-9);
+ let x: Pt | null = null, z: Pt | null = null;
+ for (const p of pts) {
+ const d = sub(p, o);
+ if (!x) { if (norm(d) > eps * 100) x = unit(d); continue; }
+ const c = cross(x, d);
+ if (norm(c) > eps * 100) { z = unit(c); break; }
+ }
+ if (!x) return { kind: 'nurbs', n };
+ // Coplanar control points: a plane.
+ if (!z || pts.every((p) => Math.abs(dot(sub(p, o), z!)) <= eps)) return z ? { kind: 'plane', o, z, x } : { kind: 'nurbs', n };
+ return revolved(n, eps) ?? { kind: 'nurbs', n };
+}
+
+/** The circle through three points: centre, unit normal, radius (null when they are in a line). */
+function circleThrough(a: Pt, b: Pt, c: Pt): { c: Pt; n: Pt; r: number } | null {
+ const ab = sub(b, a), ac = sub(c, a);
+ const nn = cross(ab, ac);
+ const l2 = dot(nn, nn);
+ if (l2 < 1e-24 * dot(ab, ab) * dot(ac, ac) || l2 === 0) return null;
+ const centre = add(a, mul(add(mul(cross(nn, ab), dot(ac, ac)), mul(cross(ac, nn), dot(ab, ab))), 1 / (2 * l2)));
+ return { c: centre, n: unit(nn), r: distance(centre, a) };
+}
+
+/**
+ * A NURBS curve as the line or circular arc it is (exporters write both as
+ * B-splines; the exact type keeps edges recognisable), else unchanged.
+ */
+export function recogniseCurve(c: Curve3, tol: number): Curve3 {
+ if (c.kind !== 'nurbs') return c;
+ const n = c.n;
+ const [t0, t1] = curveDomain(n);
+ const N = 16;
+ const pts = Array.from({ length: N + 1 }, (_, i) => curvePoint(n, t0 + ((t1 - t0) * i) / N));
+ const a = pts[0], b = pts[N];
+ const size = Math.max(...pts.map((p) => distance(p, a)), 1e-12);
+ const eps = Math.max(tol, size * 1e-9);
+ const chord = distance(a, b);
+ // A line: every point on the chord, in order.
+ if (chord > eps * 10) {
+ const d = unit(sub(b, a));
+ let along = -Infinity, straight = true;
+ for (const p of pts) {
+ const s = dot(sub(p, a), d);
+ if (norm(sub(sub(p, a), mul(d, s))) > eps || s < along - eps) { straight = false; break; }
+ along = s;
+ }
+ if (straight && n.poles.every((p) => norm(cross(sub(p, a), d)) <= eps * 10)) return { kind: 'line', a, b };
+ }
+ // A circle through three of the points (a third of the way apart, so a closed one works too).
+ const circle = circleThrough(pts[0], pts[Math.round(N / 3)], pts[Math.round((2 * N) / 3)]);
+ if (!circle || circle.r < eps * 100) return c;
+ const mids = Array.from({ length: 2 * N }, (_, i) => curvePoint(n, t0 + ((t1 - t0) * (i + 0.5)) / (2 * N)));
+ if ([...pts, ...mids].some((p) => Math.abs(distance(p, circle.c) - circle.r) > eps || Math.abs(dot(sub(p, circle.c), circle.n)) > eps)) return c;
+ // Turning direction: the normal makes the points go counterclockwise.
+ const x = unit(sub(a, circle.c));
+ let z = circle.n;
+ const turn = (p: Pt, q: Pt) => dot(cross(sub(p, circle.c), sub(q, circle.c)), z);
+ if (turn(pts[0], pts[1]) < 0) z = mul(z, -1);
+ const y = cross(z, x);
+ let angle = 0, prev = 0;
+ for (const p of pts.slice(1)) {
+ const d = sub(p, circle.c);
+ const t = Math.atan2(dot(d, y), dot(d, x));
+ let step = t - prev;
+ while (step < -Math.PI) step += 2 * Math.PI;
+ while (step > Math.PI) step -= 2 * Math.PI;
+ // Always turning one way.
+ if (step < -1e-9) return c;
+ angle += step;
+ prev = t;
+ }
+ if (angle < 1e-9) return c;
+ return { kind: 'circle', c: circle.c, x, y, r: circle.r, a0: 0, a1: Math.min(angle, 2 * Math.PI) };
+}
+
+/** Distance from a point to an exact surface of revolution. */
+function offSurface(s: Surf, p: Pt): number {
+ if (s.kind === 'plane' || s.kind === 'nurbs' || s.kind === 'revolution' || s.kind === 'extrusion') return Infinity;
+ const d = sub(p, s.o);
+ const h = dot(d, s.z);
+ const rho = norm(sub(d, mul(s.z, h)));
+ switch (s.kind) {
+ case 'cylinder': return Math.abs(rho - s.r);
+ case 'cone': return Math.abs((rho - (s.r + h * Math.tan(s.angle))) * Math.cos(s.angle));
+ case 'sphere': return Math.abs(norm(d) - s.r);
+ case 'torus': return Math.abs(Math.hypot(rho - s.R, h) - s.r);
+ }
+}
+
+/**
+ * A NURBS surface whose iso-curves one way are circles about one axis, as
+ * the cylinder, cone, sphere or torus it is (exporters write these as
+ * rational B-splines; the exact type keeps holes and fillets recognisable).
+ */
+function revolved(n: NurbsSurface, eps: number): Surf | null {
+ const [u0, u1, v0, v1] = surfaceDomain(n);
+ const at = (dir: 'u' | 'v', t: number, s: number) => (dir === 'u' ? surfacePoint(n, u0 + (u1 - u0) * t, v0 + (v1 - v0) * s) : surfacePoint(n, u0 + (u1 - u0) * s, v0 + (v1 - v0) * t));
+ const fracs = [0, 0.13, 0.31, 0.5, 0.69, 0.87, 1];
+ for (const dir of ['u', 'v'] as const) {
+ // Circles along `dir` at several positions across it.
+ const circles: { c: Pt; n: Pt; r: number }[] = [];
+ let ok = true;
+ for (const s of [0.07, 0.5, 0.93]) {
+ // Not the two ends: on a full circle they are one point.
+ const c = circleThrough(at(dir, 0.1, s), at(dir, 0.45, s), at(dir, 0.8, s));
+ if (!c || fracs.some((t) => Math.abs(distance(at(dir, t, s), c.c) - c.r) > eps) || fracs.some((t) => Math.abs(dot(sub(at(dir, t, s), c.c), c.n)) > eps)) { ok = false; break; }
+ circles.push(c);
+ }
+ if (!ok) continue;
+ const Z = circles[0].n;
+ if (circles.some((c) => norm(cross(c.n, Z)) > 1e-7)) continue;
+ const O = circles[0].c;
+ if (circles.some((c) => norm(cross(sub(c.c, O), Z)) > eps)) continue;
+ // The generatrix in (height along the axis, distance from it).
+ const gen = fracs.map((s) => {
+ const p = at(dir, 0, s);
+ const d = sub(p, O);
+ const h = dot(d, Z);
+ return { p, h, rho: norm(sub(d, mul(Z, h))) };
+ });
+ const radial = sub(gen[3].p, add(O, mul(Z, gen[3].h)));
+ const X = norm(radial) > eps ? unit(radial) : perpendicular(Z);
+ const foot = (h: number) => add(O, mul(Z, h));
+ let cand: Surf | null = null;
+ const first = gen[0], last = gen[gen.length - 1];
+ if (gen.every((g) => Math.abs(g.rho - first.rho) <= eps)) cand = { kind: 'cylinder', o: foot(first.h), z: Z, x: X, r: first.rho };
+ else if (Math.abs(last.h - first.h) > eps) {
+ const slope = (last.rho - first.rho) / (last.h - first.h);
+ if (gen.every((g) => Math.abs(first.rho + slope * (g.h - first.h) - g.rho) <= eps)) {
+ // The cone's axis points the way its radius grows.
+ cand = { kind: 'cone', o: foot(first.h), z: slope < 0 ? mul(Z, -1) : Z, x: X, r: first.rho, angle: Math.atan(Math.abs(slope)) };
+ }
+ }
+ if (!cand) {
+ // A circular generatrix: centred on the axis (sphere) or off it (torus).
+ const c2 = circleThrough([first.h, first.rho, 0], [gen[3].h, gen[3].rho, 0], [last.h, last.rho, 0]);
+ if (c2) {
+ const [hc, rc] = c2.c;
+ cand = Math.abs(rc) <= eps ? { kind: 'sphere', o: foot(hc), z: Z, x: X, r: c2.r } : { kind: 'torus', o: foot(hc), z: Z, x: X, R: rc, r: c2.r };
+ }
+ }
+ if (!cand) continue;
+ let good = true;
+ for (const a of fracs) for (const b of fracs) if (good && offSurface(cand, at(dir, a, b)) > eps * 10) good = false;
+ if (good) return cand;
+ }
+ return null;
+}
+
+/** A surface of revolution as a cylinder, cone, sphere or torus when its generatrix allows. */
+function revolution(g: Curve3, o: Pt, z: Pt, tol: number): Surf {
+ const toAxis = (p: Pt) => { const h = dot(sub(p, o), z); return { h, foot: add(o, mul(z, h)), r: distance(p, add(o, mul(z, h))) }; };
+ if (g.kind === 'line') {
+ const d = sub(g.b, g.a);
+ const L = norm(d);
+ const A = toAxis(g.a), B = toAxis(g.b);
+ // Coplanar with the axis (a meridian line).
+ const radial = sub(g.a, A.foot);
+ const xr = norm(radial) > tol ? unit(radial) : perpendicular(z);
+ const off = Math.abs(dot(d, cross(z, xr)));
+ if (L > tol && off <= tol * 10) {
+ if (Math.abs(A.r - B.r) <= tol) return A.r > tol ? { kind: 'cylinder', o: A.foot, z, x: xr, r: A.r } : { kind: 'revolution', curve: g, o, z };
+ if (Math.abs(A.h - B.h) <= tol) return { kind: 'plane', o: A.foot, z, x: xr };
+ // Radius grows along the cone's own axis.
+ const grows = (B.r - A.r) * (B.h - A.h) > 0;
+ const zz = grows ? z : mul(z, -1);
+ const angle = Math.atan2(Math.abs(B.r - A.r), Math.abs(B.h - A.h));
+ return { kind: 'cone', o: A.foot, z: zz, x: xr, r: A.r, angle };
+ }
+ }
+ if (g.kind === 'circle') {
+ const n = cross(g.x, g.y);
+ const C = toAxis(g.c);
+ // The circle's plane contains the axis.
+ if (Math.abs(dot(n, z)) <= 1e-9 && Math.abs(dot(sub(g.c, o), n)) <= tol) {
+ const radial = sub(g.c, C.foot);
+ const xr = norm(radial) > tol ? unit(radial) : perpendicular(z);
+ if (C.r <= tol) return { kind: 'sphere', o: C.foot, z, x: xr, r: g.r };
+ return { kind: 'torus', o: C.foot, z, x: xr, R: C.r, r: g.r };
+ }
+ }
+ return { kind: 'revolution', curve: g, o, z };
+}
+
+/** A tabulated cylinder as a plane or cylinder when its directrix allows. */
+function extrusion(g: Curve3, d: Pt, tol: number): Surf {
+ if (g.kind === 'line') {
+ const z = cross(sub(g.b, g.a), d);
+ if (norm(z) > tol * tol) return { kind: 'plane', o: g.a, z: unit(z), x: unit(sub(g.b, g.a)) };
+ }
+ if (g.kind === 'circle') {
+ const n = cross(g.x, g.y);
+ if (norm(cross(n, unit(d))) <= 1e-9) return { kind: 'cylinder', o: g.c, z: n, x: g.x, r: g.r };
+ }
+ return { kind: 'extrusion', curve: g, d };
+}
+
diff --git a/src/parametric/src/formats/iges/nurbs.ts b/src/parametric/src/formats/iges/nurbs.ts
new file mode 100644
index 0000000000..0a6ee20519
--- /dev/null
+++ b/src/parametric/src/formats/iges/nurbs.ts
@@ -0,0 +1,664 @@
+// NURBS curves and surfaces for the IGES translator: evaluation, exact
+// rational arcs and surfaces of revolution, reversal, clamping by knot
+// insertion, and cubic interpolation for geometry with no exact form.
+//
+// Points are plain number arrays (2D or 3D). Knot vectors are expanded
+// (each knot repeated by its multiplicity).
+
+export type Pt = number[];
+
+export interface NurbsCurve {
+ degree: number;
+ /** Expanded knot vector: poles.length + degree + 1 values. */
+ knots: number[];
+ poles: Pt[];
+ /** Null for a polynomial curve (all weights 1). */
+ weights: number[] | null;
+}
+
+export interface NurbsSurface {
+ degU: number;
+ degV: number;
+ knotsU: number[];
+ knotsV: number[];
+ /** poles[i][j]: i runs along U, j along V. */
+ poles: Pt[][];
+ weights: number[][] | null;
+}
+
+// ---------- basics ----------
+
+export const add = (a: Pt, b: Pt): Pt => a.map((x, i) => x + b[i]);
+export const sub = (a: Pt, b: Pt): Pt => a.map((x, i) => x - b[i]);
+export const mul = (a: Pt, s: number): Pt => a.map((x) => x * s);
+export const dot = (a: Pt, b: Pt): number => a.reduce((s, x, i) => s + x * b[i], 0);
+export const norm = (a: Pt): number => Math.sqrt(dot(a, a));
+export const distance = (a: Pt, b: Pt): number => norm(sub(a, b));
+export const cross = (a: Pt, b: Pt): Pt => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
+export const unit = (a: Pt): Pt => {
+ const l = norm(a);
+ return l > 0 ? mul(a, 1 / l) : a.slice();
+};
+
+/** The parameter range a curve is defined on. */
+export function curveDomain(c: NurbsCurve): [number, number] {
+ return [c.knots[c.degree], c.knots[c.poles.length]];
+}
+
+export function surfaceDomain(s: NurbsSurface): [number, number, number, number] {
+ return [s.knotsU[s.degU], s.knotsU[s.poles.length], s.knotsV[s.degV], s.knotsV[s.poles[0].length]];
+}
+
+/** Knot span index (The NURBS Book A2.1) for n control points. */
+export function findSpan(n: number, p: number, t: number, knots: number[]): number {
+ if (t >= knots[n]) {
+ let k = n - 1;
+ while (k > p && knots[k] >= knots[n]) k--;
+ return k;
+ }
+ if (t <= knots[p]) {
+ let k = p;
+ while (k < n - 1 && knots[k + 1] <= knots[p]) k++;
+ return k;
+ }
+ let lo = p, hi = n;
+ while (hi - lo > 1) {
+ const mid = (lo + hi) >> 1;
+ if (t < knots[mid]) hi = mid;
+ else lo = mid;
+ }
+ return lo;
+}
+
+/** The p+1 non-zero basis functions at t in span k (A2.2). */
+export function basisFuns(k: number, t: number, p: number, knots: number[]): number[] {
+ const N = new Array(p + 1).fill(0);
+ const left = new Array(p + 1).fill(0), right = new Array(p + 1).fill(0);
+ N[0] = 1;
+ for (let j = 1; j <= p; j++) {
+ left[j] = t - knots[k + 1 - j];
+ right[j] = knots[k + j] - t;
+ let saved = 0;
+ for (let r = 0; r < j; r++) {
+ const den = right[r + 1] + left[j - r];
+ const tmp = den === 0 ? 0 : N[r] / den;
+ N[r] = saved + right[r + 1] * tmp;
+ saved = left[j - r] * tmp;
+ }
+ N[j] = saved;
+ }
+ return N;
+}
+
+export function curvePoint(c: NurbsCurve, t: number): Pt {
+ const n = c.poles.length, p = c.degree, dim = c.poles[0].length;
+ const k = findSpan(n, p, t, c.knots);
+ const N = basisFuns(k, t, p, c.knots);
+ const out = new Array(dim).fill(0);
+ let w = 0;
+ for (let j = 0; j <= p; j++) {
+ const i = k - p + j;
+ const wi = c.weights ? c.weights[i] : 1;
+ const f = N[j] * wi;
+ for (let d = 0; d < dim; d++) out[d] += f * c.poles[i][d];
+ w += f;
+ }
+ return w === 0 ? out : out.map((x) => x / w);
+}
+
+export function surfacePoint(s: NurbsSurface, u: number, v: number): Pt {
+ const nu = s.poles.length, nv = s.poles[0].length;
+ const ku = findSpan(nu, s.degU, u, s.knotsU), kv = findSpan(nv, s.degV, v, s.knotsV);
+ const Nu = basisFuns(ku, u, s.degU, s.knotsU), Nv = basisFuns(kv, v, s.degV, s.knotsV);
+ const out = [0, 0, 0];
+ let w = 0;
+ for (let a = 0; a <= s.degU; a++) {
+ const i = ku - s.degU + a;
+ for (let b = 0; b <= s.degV; b++) {
+ const j = kv - s.degV + b;
+ const f = Nu[a] * Nv[b] * (s.weights ? s.weights[i][j] : 1);
+ const P = s.poles[i][j];
+ out[0] += f * P[0]; out[1] += f * P[1]; out[2] += f * P[2];
+ w += f;
+ }
+ }
+ return w === 0 ? out : out.map((x) => x / w);
+}
+
+/** Distinct knots and their multiplicities. */
+export function compressKnots(knots: number[]): { knots: number[]; mults: number[] } {
+ const k: number[] = [], m: number[] = [];
+ for (const t of knots) {
+ if (k.length && Math.abs(t - k[k.length - 1]) <= 1e-13 * (1 + Math.abs(t))) m[m.length - 1]++;
+ else { k.push(t); m.push(1); }
+ }
+ return { knots: k, mults: m };
+}
+
+export function expandKnots(knots: number[], mults: number[]): number[] {
+ const out: number[] = [];
+ knots.forEach((t, i) => { for (let m = 0; m < mults[i]; m++) out.push(t); });
+ return out;
+}
+
+const allOne = (w: number[] | null) => !w || w.every((x) => Math.abs(x - 1) < 1e-12);
+
+/** Drops weights that are all 1. */
+export function simplifyCurve(c: NurbsCurve): NurbsCurve {
+ return allOne(c.weights) ? { ...c, weights: null } : c;
+}
+
+export function simplifySurface(s: NurbsSurface): NurbsSurface {
+ return !s.weights || s.weights.every((r) => allOne(r)) ? { ...s, weights: null } : s;
+}
+
+// ---------- transforms ----------
+
+/** The same curve traversed the other way over the same parameter range. */
+export function reverseCurve(c: NurbsCurve): NurbsCurve {
+ const a = c.knots[0], b = c.knots[c.knots.length - 1];
+ return {
+ degree: c.degree,
+ knots: c.knots.map((t) => a + b - t).reverse(),
+ poles: c.poles.slice().reverse(),
+ weights: c.weights ? c.weights.slice().reverse() : null,
+ };
+}
+
+/** The surface with its U direction reversed: (u, v) maps to (a + b - u, v). */
+export function reverseSurfaceU(s: NurbsSurface): NurbsSurface {
+ const a = s.knotsU[0], b = s.knotsU[s.knotsU.length - 1];
+ return {
+ ...s,
+ knotsU: s.knotsU.map((t) => a + b - t).reverse(),
+ poles: s.poles.slice().reverse(),
+ weights: s.weights ? s.weights.slice().reverse() : null,
+ };
+}
+
+/** Swaps U and V. */
+export function transposeSurface(s: NurbsSurface): NurbsSurface {
+ const nu = s.poles.length, nv = s.poles[0].length;
+ const poles: Pt[][] = [], weights: number[][] | null = s.weights ? [] : null;
+ for (let j = 0; j < nv; j++) {
+ poles.push([]);
+ weights?.push([]);
+ for (let i = 0; i < nu; i++) {
+ poles[j].push(s.poles[i][j]);
+ weights?.[j].push(s.weights![i][j]);
+ }
+ }
+ return { degU: s.degV, degV: s.degU, knotsU: s.knotsV, knotsV: s.knotsU, poles, weights };
+}
+
+/** Applies a map to every pole (exact for affine maps). */
+export function mapCurve(c: NurbsCurve, f: (p: Pt) => Pt): NurbsCurve {
+ return { ...c, poles: c.poles.map(f) };
+}
+
+export function mapSurface(s: NurbsSurface, f: (p: Pt) => Pt): NurbsSurface {
+ return { ...s, poles: s.poles.map((row) => row.map(f)) };
+}
+
+/** Moves a curve's parameter range to [t0, t1] (an affine change of parameter). */
+export function reparamCurve(c: NurbsCurve, t0: number, t1: number): NurbsCurve {
+ const [a, b] = [c.knots[0], c.knots[c.knots.length - 1]];
+ const s = b > a ? (t1 - t0) / (b - a) : 1;
+ return { ...c, knots: c.knots.map((t) => t0 + (t - a) * s) };
+}
+
+// ---------- knot insertion and clamping ----------
+
+/** Homogeneous form: each pole times its weight, with the weight appended. */
+const toH = (c: NurbsCurve): Pt[] => c.poles.map((p, i) => {
+ const w = c.weights ? c.weights[i] : 1;
+ return [...p.map((x) => x * w), w];
+});
+
+const fromH = (degree: number, knots: number[], hp: Pt[], rational: boolean): NurbsCurve => {
+ const dim = hp[0].length - 1;
+ return {
+ degree,
+ knots,
+ poles: hp.map((h) => { const w = h[dim]; return h.slice(0, dim).map((x) => (w === 0 ? x : x / w)); }),
+ weights: rational ? hp.map((h) => h[dim]) : null,
+ };
+};
+
+/** Inserts knot t r times into homogeneous poles (The NURBS Book A5.1). */
+function insertKnotH(p: number, knots: number[], hp: Pt[], t: number, r: number): { knots: number[]; hp: Pt[] } {
+ const n = hp.length;
+ // The span with knots[k] <= t < knots[k + 1]; t must lie strictly inside the knot vector.
+ let k = -1;
+ for (let i = 0; i < knots.length; i++) if (knots[i] <= t) k = i;
+ if (k < p || k >= knots.length - 1) return { knots, hp };
+ let s = 0;
+ for (const x of knots) if (x === t) s++;
+ r = Math.min(r, p - s);
+ if (r <= 0) return { knots, hp };
+ const nk = [...knots.slice(0, k + 1), ...new Array(r).fill(t), ...knots.slice(k + 1)];
+ const Q: Pt[] = new Array(n + r);
+ for (let i = 0; i <= k - p; i++) Q[i] = hp[i];
+ for (let i = k - s; i < n; i++) Q[i + r] = hp[i];
+ const R: Pt[] = [];
+ for (let i = 0; i <= p - s; i++) R[i] = hp[k - p + i].slice();
+ let L = 0;
+ for (let j = 1; j <= r; j++) {
+ L = k - p + j;
+ for (let i = 0; i <= p - j - s; i++) {
+ const den = knots[i + k + 1] - knots[L + i];
+ const a = den === 0 ? 0 : (t - knots[L + i]) / den;
+ R[i] = R[i + 1].map((x, d) => a * x + (1 - a) * R[i][d]);
+ }
+ Q[L] = R[0];
+ Q[k + r - j - s] = R[p - j - s];
+ }
+ for (let i = L + 1; i < k - s; i++) Q[i] = R[i - L];
+ return { knots: nk, hp: Q };
+}
+
+const count = (knots: number[], t: number) => knots.reduce((n, x) => n + (x === t ? 1 : 0), 0);
+
+/** Drops what lies before t, leaving t as a clamped start (multiplicity p+1). */
+function cutStart(p: number, knots: number[], hp: Pt[], t: number): { knots: number[]; hp: Pt[] } {
+ if (count(knots, t) < p) ({ knots, hp } = insertKnotH(p, knots, hp, t, p - count(knots, t)));
+ const m = count(knots, t), i0 = knots.indexOf(t);
+ if (i0 < 0) return { knots, hp };
+ if (m >= p + 1) {
+ const start = i0 + (m - p - 1);
+ return { knots: knots.slice(start), hp: hp.slice(start) };
+ }
+ // Multiplicity p: pole i0-1 is the curve's point at t.
+ return { knots: [t, ...knots.slice(i0)], hp: hp.slice(i0 - 1) };
+}
+
+/** Drops what lies after t, leaving t as a clamped end. */
+function cutEnd(p: number, knots: number[], hp: Pt[], t: number): { knots: number[]; hp: Pt[] } {
+ if (count(knots, t) < p) ({ knots, hp } = insertKnotH(p, knots, hp, t, p - count(knots, t)));
+ const m = count(knots, t), last = knots.lastIndexOf(t);
+ if (last < 0) return { knots, hp };
+ if (m >= p + 1) {
+ const k = knots.slice(0, last + 1 - (m - p - 1));
+ return { knots: k, hp: hp.slice(0, k.length - p - 1) };
+ }
+ const i0 = last - p + 1;
+ return { knots: [...knots.slice(0, last + 1), t], hp: hp.slice(0, i0) };
+}
+
+/** Restricts homogeneous poles to [t0, t1] with clamped ends. */
+function clampH(p: number, knots: number[], hp: Pt[], t0: number, t1: number): { knots: number[]; hp: Pt[] } {
+ // Snap to existing knots so equality tests find them.
+ const snap = (t: number) => knots.find((x) => Math.abs(x - t) <= 1e-12 * (1 + Math.abs(t))) ?? t;
+ const a = cutStart(p, knots, hp, snap(t0));
+ return cutEnd(p, a.knots, a.hp, snap(t1));
+}
+
+/**
+ * The curve on [t0, t1] with clamped ends (first and last knots repeated
+ * degree+1 times), so its end poles are its end points.
+ */
+export function clampCurve(c: NurbsCurve, t0?: number, t1?: number): NurbsCurve {
+ const [a, b] = curveDomain(c);
+ const lo = Math.max(a, t0 ?? a), hi = Math.min(b, t1 ?? b);
+ const p = c.degree;
+ const clamped = c.knots.slice(0, p + 1).every((x) => x === lo) && c.knots.slice(-p - 1).every((x) => x === hi);
+ if (clamped && c.knots.length === c.poles.length + p + 1) return c;
+ const { knots, hp } = clampH(p, c.knots, toH(c), lo, hi);
+ return fromH(p, knots, hp, !!c.weights);
+}
+
+/** Surface U-direction rows as homogeneous curves whose "poles" are whole V-columns. */
+function surfaceRowsH(s: NurbsSurface): Pt[] {
+ return s.poles.map((row, i) => row.flatMap((p, j) => {
+ const w = s.weights ? s.weights[i][j] : 1;
+ return [p[0] * w, p[1] * w, p[2] * w, w];
+ }));
+}
+
+function surfaceFromRowsH(s: NurbsSurface, knotsU: number[], rows: Pt[]): NurbsSurface {
+ const nv = rows[0].length / 4;
+ const poles: Pt[][] = [], weights: number[][] = [];
+ for (const r of rows) {
+ const pr: Pt[] = [], wr: number[] = [];
+ for (let j = 0; j < nv; j++) {
+ const w = r[4 * j + 3];
+ pr.push([r[4 * j], r[4 * j + 1], r[4 * j + 2]].map((x) => (w === 0 ? x : x / w)));
+ wr.push(w);
+ }
+ poles.push(pr);
+ weights.push(wr);
+ }
+ return { ...s, knotsU, poles, weights: s.weights ? weights : null };
+}
+
+/** The surface on the given range with clamped knots in both directions. */
+export function clampSurface(s: NurbsSurface, range?: [number, number, number, number]): NurbsSurface {
+ const [u0, u1, v0, v1] = surfaceDomain(s);
+ const r = range ?? [u0, u1, v0, v1];
+ const lo = (x: number, a: number, b: number) => Math.min(Math.max(x, a), b);
+ const U0 = lo(r[0], u0, u1), U1 = lo(r[1], u0, u1), V0 = lo(r[2], v0, v1), V1 = lo(r[3], v0, v1);
+ let out = s;
+ const p = s.degU;
+ const clampedU = s.knotsU.slice(0, p + 1).every((x) => x === U0) && s.knotsU.slice(-p - 1).every((x) => x === U1);
+ if (!clampedU) {
+ const { knots, hp } = clampH(p, s.knotsU, surfaceRowsH(s), U0, U1);
+ out = surfaceFromRowsH(s, knots, hp);
+ }
+ const q = out.degV;
+ const clampedV = out.knotsV.slice(0, q + 1).every((x) => x === V0) && out.knotsV.slice(-q - 1).every((x) => x === V1);
+ if (!clampedV) {
+ const t = transposeSurface(out);
+ const { knots, hp } = clampH(q, t.knotsU, surfaceRowsH(t), V0, V1);
+ out = transposeSurface(surfaceFromRowsH(t, knots, hp));
+ }
+ return out;
+}
+
+/** The iso-curve of a surface at constant v (along U), or at constant u (along V). */
+export function isoCurve(s: NurbsSurface, dir: 'u' | 'v', at: number): NurbsCurve {
+ // An iso-curve along U at v: combine the V-direction basis per U row.
+ const src = dir === 'u' ? s : transposeSurface(s);
+ const nv = src.poles[0].length, q = src.degV;
+ const k = findSpan(nv, q, at, src.knotsV);
+ const N = basisFuns(k, at, q, src.knotsV);
+ const hp = src.poles.map((row, i) => {
+ const h = [0, 0, 0, 0];
+ for (let b = 0; b <= q; b++) {
+ const j = k - q + b;
+ const w = src.weights ? src.weights[i][j] : 1;
+ h[0] += N[b] * row[j][0] * w; h[1] += N[b] * row[j][1] * w; h[2] += N[b] * row[j][2] * w; h[3] += N[b] * w;
+ }
+ return h;
+ });
+ return fromH(src.degU, src.knotsU, hp, !!src.weights);
+}
+
+// ---------- exact arcs and swept surfaces ----------
+
+/** How a circular arc from a0 to a1 is split into rational quadratic pieces of at most 90 degrees. */
+function arcPieces(a0: number, a1: number): number {
+ return Math.max(1, Math.ceil((a1 - a0) / (Math.PI / 2) - 1e-9));
+}
+
+/**
+ * An exact rational arc c + cos(t) e1 + sin(t) e2 for t in [a0, a1] (an
+ * ellipse when e1 and e2 differ in length). The knots are the angles at the
+ * piece boundaries, so the arc's parameter agrees with the angle there;
+ * angleToParam gives it everywhere.
+ */
+export function arcCurve(c: Pt, e1: Pt, e2: Pt, a0: number, a1: number): NurbsCurve {
+ const n = arcPieces(a0, a1);
+ const d = (a1 - a0) / n;
+ const w = Math.cos(d / 2);
+ const at = (t: number) => add(c, add(mul(e1, Math.cos(t)), mul(e2, Math.sin(t))));
+ const poles: Pt[] = [at(a0)], weights = [1], knots = [a0, a0, a0];
+ for (let i = 0; i < n; i++) {
+ const s = a0 + i * d, e = s + d, m = s + d / 2;
+ poles.push(add(c, mul(add(mul(e1, Math.cos(m)), mul(e2, Math.sin(m))), 1 / w)), at(e));
+ weights.push(w, 1);
+ if (i < n - 1) knots.push(e, e);
+ }
+ knots.push(a1, a1, a1);
+ return { degree: 2, knots, poles, weights };
+}
+
+/** The parameter of arcCurve(..., a0, a1) at angle t (tangent half-angle within each piece). */
+export function angleToParam(a0: number, a1: number, t: number): number {
+ const n = arcPieces(a0, a1);
+ const d = (a1 - a0) / n;
+ let i = Math.floor((t - a0) / d);
+ i = Math.min(Math.max(i, 0), n - 1);
+ const s = a0 + i * d;
+ const tau = Math.tan((t - (s + d / 2)) / 2) / Math.tan(d / 4);
+ return s + d * (1 + tau) / 2;
+}
+
+/** The angle at which arcCurve(..., a0, a1) has parameter u: the inverse of angleToParam. */
+export function paramToAngle(a0: number, a1: number, u: number): number {
+ const n = arcPieces(a0, a1);
+ const d = (a1 - a0) / n;
+ let i = Math.floor((u - a0) / d);
+ i = Math.min(Math.max(i, 0), n - 1);
+ const s = a0 + i * d;
+ const tau = (2 * (u - s)) / d - 1;
+ return s + d / 2 + 2 * Math.atan(tau * Math.tan(d / 4));
+}
+
+/**
+ * Revolves a generatrix about an axis through angles [a0, a1]: U is the
+ * angle direction (with arcCurve's parameter), V the generatrix's. `handed`
+ * is -1 to turn the other way around the axis (a left-handed frame).
+ */
+export function revolveCurve(gen: NurbsCurve, O: Pt, Z: Pt, a0: number, a1: number, handed = 1): NurbsSurface {
+ const z = unit(Z);
+ const cols = gen.poles.map((Q) => {
+ const c = add(O, mul(z, dot(sub(Q, O), z)));
+ const e1 = sub(Q, c);
+ const e2 = mul(cross(z, e1), handed);
+ return arcCurve(c, e1, e2, a0, a1);
+ });
+ const arc = cols[0];
+ const poles: Pt[][] = arc.poles.map((_, i) => cols.map((col) => col.poles[i]));
+ const weights: number[][] = arc.poles.map((_, i) => gen.poles.map((__, j) => arc.weights![i] * (gen.weights ? gen.weights[j] : 1)));
+ return { degU: 2, degV: gen.degree, knotsU: arc.knots, knotsV: gen.knots, poles, weights };
+}
+
+/** Sweeps a curve (U) along a vector: P(u, v) = C(u) + v d for v in [v0, v1]. */
+export function extrudeCurve(c: NurbsCurve, d: Pt, v0: number, v1: number): NurbsSurface {
+ return {
+ degU: c.degree,
+ degV: 1,
+ knotsU: c.knots,
+ knotsV: [v0, v0, v1, v1],
+ poles: c.poles.map((p) => [add(p, mul(d, v0)), add(p, mul(d, v1))]),
+ weights: c.weights ? c.weights.map((w) => [w, w]) : null,
+ };
+}
+
+/** A straight segment as a degree-1 curve on [t0, t1]. */
+export function lineCurve(a: Pt, b: Pt, t0 = 0, t1 = 1): NurbsCurve {
+ return { degree: 1, knots: [t0, t0, t1, t1], poles: [a, b], weights: null };
+}
+
+/** The ruled surface between two curves (U along the curves, V from c0 to c1). */
+export function ruledSurface(c0: NurbsCurve, c1: NurbsCurve): NurbsSurface | null {
+ const [a, b] = compatible(c0, c1);
+ if (!a) return null;
+ return {
+ degU: a.degree,
+ degV: 1,
+ knotsU: a.knots,
+ knotsV: [0, 0, 1, 1],
+ poles: a.poles.map((p, i) => [p, b!.poles[i]]),
+ weights: a.weights || b!.weights ? a.poles.map((_, i) => [a.weights ? a.weights[i] : 1, b!.weights ? b!.weights[i] : 1]) : null,
+ };
+}
+
+/** Two curves on [0, 1] with the same degree and knots (by degree elevation and knot insertion), or [null, null]. */
+function compatible(c0: NurbsCurve, c1: NurbsCurve): [NurbsCurve | null, NurbsCurve | null] {
+ let a = reparamCurve(clampCurve(c0), 0, 1), b = reparamCurve(clampCurve(c1), 0, 1);
+ while (a.degree < b.degree) a = elevateDegree(a);
+ while (b.degree < a.degree) b = elevateDegree(b);
+ const merged = mergeKnots(a.knots, b.knots);
+ a = refine(a, merged);
+ b = refine(b, merged);
+ if (a.poles.length !== b.poles.length) return [null, null];
+ // Ruled surfaces need one weight per pole pair to stay exact; mismatched weights are approximated.
+ if (a.weights && b.weights && a.weights.some((w, i) => Math.abs(w - b.weights![i]) > 1e-12)) return [null, null];
+ return [a, b];
+}
+
+function mergeKnots(k0: number[], k1: number[]): number[] {
+ const a = compressKnots(k0), b = compressKnots(k1);
+ const out = new Map();
+ const put = (t: number, m: number) => {
+ for (const [k, v] of out) if (Math.abs(k - t) < 1e-10) { out.set(k, Math.max(v, m)); return; }
+ out.set(t, m);
+ };
+ a.knots.forEach((t, i) => put(t, a.mults[i]));
+ b.knots.forEach((t, i) => put(t, b.mults[i]));
+ return [...out.entries()].sort((x, y) => x[0] - y[0]).flatMap(([t, m]) => new Array(m).fill(t));
+}
+
+/** Inserts knots until the curve's knot vector contains `target`. */
+function refine(c: NurbsCurve, target: number[]): NurbsCurve {
+ let knots = c.knots, hp = toH(c);
+ const T = compressKnots(target);
+ T.knots.forEach((t, i) => {
+ const have = knots.filter((x) => Math.abs(x - t) < 1e-10).length;
+ const snapped = knots.find((x) => Math.abs(x - t) < 1e-10) ?? t;
+ if (T.mults[i] > have) ({ knots, hp } = insertKnotH(c.degree, knots, hp, snapped, T.mults[i] - have));
+ });
+ return fromH(c.degree, knots, hp, !!c.weights);
+}
+
+/** Raises a clamped curve's degree by one, exactly (via Bezier pieces). */
+export function elevateDegree(c: NurbsCurve): NurbsCurve {
+ const p = c.degree;
+ // Split into Bezier pieces by raising every interior knot to multiplicity p.
+ const { knots: ks, mults } = compressKnots(c.knots);
+ let knots = c.knots, hp = toH(c);
+ for (let i = 1; i < ks.length - 1; i++) if (mults[i] < p) ({ knots, hp } = insertKnotH(p, knots, hp, ks[i], p - mults[i]));
+ const pieces = ks.length - 1;
+ const outH: Pt[] = [];
+ for (let s = 0; s < pieces; s++) {
+ const seg = hp.slice(s * p, s * p + p + 1);
+ const el: Pt[] = [seg[0]];
+ for (let i = 1; i <= p; i++) {
+ const a = i / (p + 1);
+ el.push(seg[i - 1].map((x, d) => a * x + (1 - a) * seg[i][d]));
+ }
+ el.push(seg[p]);
+ if (s > 0) el.shift();
+ outH.push(...el);
+ }
+ const outKnots: number[] = [];
+ ks.forEach((t, i) => {
+ const m = i === 0 || i === ks.length - 1 ? p + 2 : p + 1;
+ for (let j = 0; j < m; j++) outKnots.push(t);
+ });
+ return fromH(p + 1, outKnots, outH, !!c.weights);
+}
+
+// ---------- interpolation ----------
+
+/**
+ * Solves A x = B for a banded matrix whose row i has non-zeros only in
+ * columns [i - w, i + w] (B-spline collocation matrices are totally
+ * positive, so no pivoting is needed). Each B row is a vector.
+ */
+function solveBanded(A: number[][], B: number[][], w: number): number[][] {
+ const n = A.length;
+ const a = A.map((r) => r.slice());
+ const b = B.map((r) => r.slice());
+ for (let c = 0; c < n; c++) {
+ const piv = a[c][c];
+ if (Math.abs(piv) < 1e-300) throw new Error('Singular interpolation system');
+ for (let r = c + 1; r <= Math.min(n - 1, c + w); r++) {
+ const f = a[r][c] / piv;
+ if (f === 0) continue;
+ for (let k = c; k <= Math.min(n - 1, c + w); k++) a[r][k] -= f * a[c][k];
+ for (let d = 0; d < b[r].length; d++) b[r][d] -= f * b[c][d];
+ }
+ }
+ for (let r = n - 1; r >= 0; r--) {
+ for (let k = r + 1; k <= Math.min(n - 1, r + w); k++) {
+ const f = a[r][k];
+ if (f === 0) continue;
+ for (let d = 0; d < b[r].length; d++) b[r][d] -= f * b[k][d];
+ }
+ for (let d = 0; d < b[r].length; d++) b[r][d] /= a[r][r];
+ }
+ return b;
+}
+
+/** Knots for interpolation at the given parameters by averaging (The NURBS Book 9.8). */
+function averagedKnots(params: number[], p: number): number[] {
+ const n = params.length;
+ const knots = new Array(n + p + 1).fill(0);
+ for (let i = 0; i <= p; i++) { knots[i] = params[0]; knots[n + i] = params[n - 1]; }
+ for (let j = 1; j < n - p; j++) {
+ let s = 0;
+ for (let i = j; i < j + p; i++) s += params[i];
+ knots[j + p] = s / p;
+ }
+ return knots;
+}
+
+/** Global interpolation (A9.1): a polynomial curve through the points at the parameters. */
+export function interpolate(points: Pt[], params: number[], degree = 3): NurbsCurve {
+ const n = points.length;
+ const p = Math.min(degree, n - 1);
+ const knots = averagedKnots(params, p);
+ const A: number[][] = [];
+ for (let r = 0; r < n; r++) {
+ const row = new Array(n).fill(0);
+ const k = findSpan(n, p, params[r], knots);
+ const N = basisFuns(k, params[r], p, knots);
+ for (let j = 0; j <= p; j++) row[k - p + j] = N[j];
+ A.push(row);
+ }
+ const poles = solveBanded(A, points, p);
+ return { degree: p, knots, poles, weights: null };
+}
+
+const uniform = (t0: number, t1: number, n: number) => Array.from({ length: n }, (_, i) => (i === n - 1 ? t1 : t0 + ((t1 - t0) * i) / (n - 1)));
+
+/**
+ * A cubic curve through samples of `ev` on [t0, t1], keeping the parameter
+ * (the result at t is close to ev(t)), refined until it is within tol
+ * halfway between samples.
+ */
+export function fitCurve(ev: (t: number) => Pt, t0: number, t1: number, tol: number, maxPoints = 2049): NurbsCurve {
+ let n = 9;
+ let best: NurbsCurve | null = null;
+ for (;;) {
+ const params = uniform(t0, t1, n);
+ const c = interpolate(params.map(ev), params);
+ let err = 0;
+ for (let i = 0; i + 1 < n && err <= tol; i++) {
+ const t = (params[i] + params[i + 1]) / 2;
+ err = Math.max(err, distance(curvePoint(c, t), ev(t)));
+ }
+ best = c;
+ if (err <= tol || n >= maxPoints) return best;
+ n = Math.min(maxPoints, 2 * n - 1);
+ }
+}
+
+/**
+ * A bicubic surface through samples of `ev` on [u0, u1] x [v0, v1], keeping
+ * the parameters, refined until it is within tol between samples.
+ */
+export function fitSurface(ev: (u: number, v: number) => Pt, u0: number, u1: number, v0: number, v1: number, tol: number, maxPoints = 129): NurbsSurface {
+ let nu = 9, nv = 9;
+ for (;;) {
+ const us = uniform(u0, u1, nu), vs = uniform(v0, v1, nv);
+ const grid = us.map((u) => vs.map((v) => ev(u, v)));
+ // Interpolate along V for each u, then the resulting columns along U.
+ const rows = grid.map((row) => interpolate(row, vs));
+ const p = Math.min(3, nu - 1);
+ const nvp = rows[0].poles.length;
+ const cols: Pt[][] = [];
+ for (let j = 0; j < nvp; j++) cols.push(interpolate(rows.map((r) => r.poles[j]), us).poles);
+ const knotsU = averagedKnots(us, p);
+ const s: NurbsSurface = { degU: p, degV: rows[0].degree, knotsU, knotsV: rows[0].knots, poles: us.map((_, i) => cols.map((c) => c[i])), weights: null };
+ let errU = 0, errV = 0;
+ for (let i = 0; i + 1 < nu; i++) {
+ for (let j = 0; j < nv; j++) {
+ const u = (us[i] + us[i + 1]) / 2;
+ errU = Math.max(errU, distance(surfacePoint(s, u, vs[j]), ev(u, vs[j])));
+ }
+ }
+ for (let i = 0; i < nu; i++) {
+ for (let j = 0; j + 1 < nv; j++) {
+ const v = (vs[j] + vs[j + 1]) / 2;
+ errV = Math.max(errV, distance(surfacePoint(s, us[i], v), ev(us[i], v)));
+ }
+ }
+ const doneU = errU <= tol || nu >= maxPoints, doneV = errV <= tol || nv >= maxPoints;
+ if (doneU && doneV) return s;
+ if (!doneU) nu = Math.min(maxPoints, 2 * nu - 1);
+ if (!doneV) nv = Math.min(maxPoints, 2 * nv - 1);
+ }
+}
diff --git a/src/parametric/src/formats/iges/parse.ts b/src/parametric/src/formats/iges/parse.ts
new file mode 100644
index 0000000000..bbad4d9409
--- /dev/null
+++ b/src/parametric/src/formats/iges/parse.ts
@@ -0,0 +1,141 @@
+// Reads the sections of an IGES file (ASCII fixed format): the global
+// parameters, the directory entries and each entity's parameters.
+
+export class IgesError extends Error {}
+
+export interface IgesEntity {
+ /** Directory entry pointer (its odd line number in the D section). */
+ de: number;
+ type: number;
+ form: number;
+ /** Pointer to a 124 transformation, or 0. */
+ transform: number;
+ /** A colour number (1-8), a negative pointer to a 314 colour, or 0. */
+ color: number;
+ blank: boolean;
+ /** 0 independent, 1 physically dependent, 2 logically dependent, 3 both. */
+ subordinate: number;
+ /** 0 geometry, 1 annotation, 2 definition, 3 other, 4 logical, 5 2D parametric, 6 construction. */
+ use: number;
+ label: string;
+ /** The parameters after the entity type, as raw tokens. */
+ readonly params: string[];
+}
+
+export interface IgesFile {
+ global: string[];
+ entities: Map;
+ /** Millimetres per model unit. */
+ unit: number;
+ /** The file's resolution (smallest distinguishable distance), in model units. */
+ resolution: number;
+}
+
+/** Splits a free-format record into tokens (Hollerith strings kept whole). */
+export function tokenize(text: string, pd = ',', rd = ';'): string[] {
+ const out: string[] = [];
+ let i = 0;
+ const n = text.length;
+ while (i < n) {
+ while (i < n && text[i] === ' ') i++;
+ // A Hollerith string: digits, 'H', then that many characters.
+ const m = /^(\d+)H/.exec(text.slice(i, i + 12));
+ if (m) {
+ const len = Number(m[1]);
+ const start = i + m[0].length;
+ out.push(`${m[0]}${text.slice(start, start + len)}`);
+ i = start + len;
+ while (i < n && text[i] === ' ') i++;
+ if (text[i] === rd) return out;
+ if (text[i] === pd) i++;
+ continue;
+ }
+ let j = i;
+ while (j < n && text[j] !== pd && text[j] !== rd) j++;
+ out.push(text.slice(i, j).trim());
+ if (j >= n || text[j] === rd) return out;
+ i = j + 1;
+ }
+ return out;
+}
+
+export function holleriths(tok: string | undefined): string {
+ const m = /^(\d+)H([\s\S]*)$/.exec(tok ?? '');
+ return m ? m[2].slice(0, Number(m[1])) : '';
+}
+
+export function num(tok: string | undefined, fallback = 0): number {
+ if (tok == null) return fallback;
+ const t = tok.trim();
+ if (!t) return fallback;
+ const v = Number(t.replace(/[dD]/, 'E'));
+ return Number.isFinite(v) ? v : fallback;
+}
+
+export function int(tok: string | undefined, fallback = 0): number {
+ return Math.trunc(num(tok, fallback));
+}
+
+const UNITS: Record = { 1: 25.4, 2: 1, 4: 304.8, 5: 1609344, 6: 1000, 7: 1e6, 8: 0.0254, 9: 0.001, 10: 10, 11: 2.54e-5 };
+const UNIT_NAMES: Record = { IN: 25.4, INCH: 25.4, MM: 1, FT: 304.8, MI: 1609344, M: 1000, KM: 1e6, MIL: 0.0254, UM: 0.001, MICRON: 0.001, CM: 10, UIN: 2.54e-5 };
+
+export function parseIges(text: string): IgesFile {
+ if (/^\x00|\x00/.test(text.slice(0, 200))) throw new IgesError('This is a binary IGES file, which Parametric cannot read. Save it as ASCII IGES.');
+ const lines = text.split(/\r\n|\r|\n/);
+ const sections: Record = { S: [], G: [], D: [], P: [], T: [], C: [] };
+ for (const raw of lines) {
+ if (!raw.trim()) continue;
+ const line = raw.length < 80 ? raw.padEnd(80) : raw;
+ const s = line[72];
+ if (s in sections) sections[s].push(line);
+ }
+ if (sections.C.length || (!sections.D.length && /^.{72}C/m.test(text))) throw new IgesError('This is a compressed IGES file, which Parametric cannot read. Save it as uncompressed IGES.');
+ if (!sections.D.length || !sections.P.length) throw new IgesError('This is not an IGES file, or it has no entities.');
+
+ // Global section: the delimiters come first.
+ const gtext = sections.G.map((l) => l.slice(0, 72)).join('');
+ // The first two parameters name them ("1H," and "1H;"), or are empty for the defaults.
+ let pd = ',', rd = ';';
+ let i = gtext.search(/\S/);
+ if (i < 0) i = 0;
+ if (gtext.startsWith('1H', i)) { pd = gtext[i + 2]; i += 3; }
+ while (gtext[i] === ' ') i++;
+ if (gtext[i] === pd) i++;
+ while (gtext[i] === ' ') i++;
+ if (gtext.startsWith('1H', i)) rd = gtext[i + 2];
+ const global = tokenize(gtext, pd, rd);
+
+ const entities = new Map();
+ const P = sections.P;
+ const field = (l: string, k: number) => l.slice(k * 8, k * 8 + 8);
+ for (let i = 0; i + 1 < sections.D.length; i += 2) {
+ const a = sections.D[i], b = sections.D[i + 1];
+ const de = i + 1;
+ const type = int(field(a, 0));
+ const ptr = int(field(a, 1));
+ const status = field(a, 8).replace(/ /g, '0').padStart(8, '0');
+ const count = int(field(b, 3));
+ const form = int(field(b, 4));
+ // Parameters are split into tokens when first read (large files have many unused entities).
+ let cache: string[] | null = null;
+ const params = () => {
+ if (!cache) cache = ptr > 0 && count > 0 ? tokenize(P.slice(ptr - 1, ptr - 1 + count).map((l) => l.slice(0, 64)).join(''), pd, rd).slice(1) : [];
+ return cache;
+ };
+ entities.set(de, {
+ de, type, form,
+ transform: int(field(a, 6)),
+ color: int(field(b, 2)),
+ blank: status.slice(0, 2) === '01',
+ subordinate: int(status.slice(2, 4)),
+ use: int(status.slice(4, 6)),
+ label: field(b, 7).trim(),
+ get params() { return params(); },
+ });
+ }
+ const unitFlag = int(global[13], 2);
+ const unitName = holleriths(global[14]).trim().toUpperCase();
+ const unit = UNITS[unitFlag] ?? UNIT_NAMES[unitName] ?? 1;
+ const resolution = num(global[18], 0);
+ return { global, entities, unit, resolution };
+}
diff --git a/src/parametric/src/formats/iges/step.ts b/src/parametric/src/formats/iges/step.ts
new file mode 100644
index 0000000000..2204721050
--- /dev/null
+++ b/src/parametric/src/formats/iges/step.ts
@@ -0,0 +1,185 @@
+// Writes converted IGES faces as STEP (AP214) for the geometry kernel's STEP
+// reader, which builds the faces' topology and parameter-space curves and
+// repairs small gaps. Trimmed surfaces become faces of an open shell (sewn
+// together afterwards); IGES B-rep solids keep their shared edges.
+
+import { type NurbsCurve, type NurbsSurface, type Pt, compressKnots, cross, curveDomain, curvePoint, distance, norm, simplifyCurve, simplifySurface, unit } from './nurbs';
+import { type Brep, type Curve3, type IgesModel, type Surf, curveEnd, curveStart } from './convert';
+import { asciiOnly, igesReal as real } from './write';
+
+const ref = (id: number) => `#${id}`;
+const list = (ids: number[]) => `(${ids.map(ref).join(',')})`;
+const reals = (xs: number[]) => `(${xs.map(real).join(',')})`;
+const ints = (xs: number[]) => `(${xs.join(',')})`;
+const str = (s: string) => `'${asciiOnly(s).replace(/'/g, "''").replace(/\\/g, '\\\\')}'`;
+
+class StepWriter {
+ lines: string[] = [];
+ private n = 0;
+ add(body: string): number {
+ this.lines.push(`#${++this.n}=${body};`);
+ return this.n;
+ }
+ point(p: Pt) { return this.add(`CARTESIAN_POINT('',${reals([p[0], p[1], p[2] ?? 0])})`); }
+ dir(d: Pt) { return this.add(`DIRECTION('',${reals(unit(d))})`); }
+ axis2(o: Pt, z: Pt, x: Pt) { return this.add(`AXIS2_PLACEMENT_3D('',${ref(this.point(o))},${ref(this.dir(z))},${ref(this.dir(x))})`); }
+
+ bsplineCurve(c0: NurbsCurve): number {
+ const c = simplifyCurve(c0);
+ const { knots, mults } = compressKnots(c.knots);
+ const pts = list(c.poles.map((p) => this.point(p)));
+ if (!c.weights) return this.add(`B_SPLINE_CURVE_WITH_KNOTS('',${c.degree},${pts},.UNSPECIFIED.,.F.,.F.,${ints(mults)},${reals(knots)},.UNSPECIFIED.)`);
+ return this.add(`(BOUNDED_CURVE()B_SPLINE_CURVE(${c.degree},${pts},.UNSPECIFIED.,.F.,.F.)B_SPLINE_CURVE_WITH_KNOTS(${ints(mults)},${reals(knots)},.UNSPECIFIED.)CURVE()GEOMETRIC_REPRESENTATION_ITEM()RATIONAL_B_SPLINE_CURVE(${reals(c.weights)})REPRESENTATION_ITEM(''))`);
+ }
+
+ bsplineSurface(s0: NurbsSurface): number {
+ const s = simplifySurface(s0);
+ const u = compressKnots(s.knotsU), v = compressKnots(s.knotsV);
+ const net = `(${s.poles.map((row) => list(row.map((p) => this.point(p)))).join(',')})`;
+ if (!s.weights) return this.add(`B_SPLINE_SURFACE_WITH_KNOTS('',${s.degU},${s.degV},${net},.UNSPECIFIED.,.F.,.F.,.F.,${ints(u.mults)},${ints(v.mults)},${reals(u.knots)},${reals(v.knots)},.UNSPECIFIED.)`);
+ const w = `(${s.weights.map((r) => reals(r)).join(',')})`;
+ return this.add(`(BOUNDED_SURFACE()B_SPLINE_SURFACE(${s.degU},${s.degV},${net},.UNSPECIFIED.,.F.,.F.,.F.)B_SPLINE_SURFACE_WITH_KNOTS(${ints(u.mults)},${ints(v.mults)},${reals(u.knots)},${reals(v.knots)},.UNSPECIFIED.)GEOMETRIC_REPRESENTATION_ITEM()RATIONAL_B_SPLINE_SURFACE(${w})REPRESENTATION_ITEM('')SURFACE())`);
+ }
+
+ /** A curve's unbounded geometry (edges are bounded by their vertices). */
+ curve(c: Curve3): number {
+ switch (c.kind) {
+ case 'line': {
+ const d = [c.b[0] - c.a[0], c.b[1] - c.a[1], c.b[2] - c.a[2]];
+ return this.add(`LINE('',${ref(this.point(c.a))},${ref(this.add(`VECTOR('',${ref(this.dir(d))},${real(norm(d) || 1)})`))})`);
+ }
+ case 'circle': return this.add(`CIRCLE('',${ref(this.axis2(c.c, cross(c.x, c.y), c.x))},${real(c.r)})`);
+ case 'ellipse': {
+ // STEP ellipses have the major axis along x.
+ if (c.r1 >= c.r2) return this.add(`ELLIPSE('',${ref(this.axis2(c.c, cross(c.x, c.y), c.x))},${real(c.r1)},${real(c.r2)})`);
+ return this.add(`ELLIPSE('',${ref(this.axis2(c.c, cross(c.x, c.y), c.y))},${real(c.r2)},${real(c.r1)})`);
+ }
+ case 'nurbs': return this.bsplineCurve(c.n);
+ }
+ }
+
+ surface(s: Surf): number {
+ switch (s.kind) {
+ case 'plane': return this.add(`PLANE('',${ref(this.axis2(s.o, s.z, s.x))})`);
+ case 'cylinder': return this.add(`CYLINDRICAL_SURFACE('',${ref(this.axis2(s.o, s.z, s.x))},${real(s.r)})`);
+ case 'cone': return this.add(`CONICAL_SURFACE('',${ref(this.axis2(s.o, s.z, s.x))},${real(s.r)},${real(s.angle)})`);
+ case 'sphere': return this.add(`SPHERICAL_SURFACE('',${ref(this.axis2(s.o, s.z, s.x))},${real(s.r)})`);
+ case 'torus': return this.add(`TOROIDAL_SURFACE('',${ref(this.axis2(s.o, s.z, s.x))},${real(s.R)},${real(s.r)})`);
+ case 'revolution': {
+ const ax = this.add(`AXIS1_PLACEMENT('',${ref(this.point(s.o))},${ref(this.dir(s.z))})`);
+ return this.add(`SURFACE_OF_REVOLUTION('',${ref(this.curve(s.curve))},${ref(ax)})`);
+ }
+ case 'extrusion': return this.add(`SURFACE_OF_LINEAR_EXTRUSION('',${ref(this.curve(s.curve))},${ref(this.add(`VECTOR('',${ref(this.dir(s.d))},${real(norm(s.d) || 1)})`))})`);
+ case 'nurbs': return this.bsplineSurface(s.n);
+ }
+ }
+}
+
+/** A point halfway along a curve's parameter range (for matching seams). */
+function midPoint(c: Curve3): Pt {
+ switch (c.kind) {
+ case 'line': return c.a.map((x, i) => (x + c.b[i]) / 2);
+ case 'circle': { const t = (c.a0 + c.a1) / 2; return c.c.map((x, i) => x + c.r * (Math.cos(t) * c.x[i] + Math.sin(t) * c.y[i])); }
+ case 'ellipse': { const t = (c.a0 + c.a1) / 2; return c.c.map((x, i) => x + c.r1 * Math.cos(t) * c.x[i] + c.r2 * Math.sin(t) * c.y[i]); }
+ case 'nurbs': { const [a, b] = curveDomain(c.n); return curvePoint(c.n, (a + b) / 2); }
+ }
+}
+
+/**
+ * A trimmed face: each loop gets its own vertices (joined where pieces meet)
+ * and edges. A piece that runs back along an earlier piece of the loop (the
+ * seam of a closed surface) reuses that edge the other way round.
+ */
+function trimmedFace(w: StepWriter, surface: Surf, sense: boolean, loops: Curve3[][], tol: number): number {
+ const surf = w.surface(surface);
+ const bounds = loops.map((loop, li) => {
+ const n = loop.length;
+ // The vertex between piece i-1 and piece i: the middle of the two ends.
+ const pts: Pt[] = [];
+ for (let i = 0; i < n; i++) {
+ const prevEnd = curveEnd(loop[(i + n - 1) % n]), start = curveStart(loop[i]);
+ pts.push(distance(prevEnd, start) <= tol * 100 ? prevEnd.map((x, k) => (x + start[k]) / 2) : start);
+ }
+ // Ends that meet are one vertex (a seam's ends are shared with the pieces around it).
+ const vid: number[] = [];
+ const made: { p: Pt; id: number }[] = [];
+ for (const p of pts) {
+ const hit = made.find((m) => distance(m.p, p) <= tol * 10);
+ if (hit) { vid.push(hit.id); continue; }
+ const id = w.add(`VERTEX_POINT('',${ref(w.point(p))})`);
+ made.push({ p, id });
+ vid.push(id);
+ }
+ const mids = loop.map(midPoint);
+ const edges: { id: number; a: number; b: number; mid: Pt }[] = [];
+ const oes = loop.map((c, i) => {
+ const a = vid[i], b = vid[(i + 1) % n];
+ const back = edges.find((e) => e.a === b && e.b === a && distance(e.mid, mids[i]) <= tol * 10);
+ if (back) return w.add(`ORIENTED_EDGE('',*,*,${ref(back.id)},.F.)`);
+ const id = w.add(`EDGE_CURVE('',${ref(a)},${ref(b)},${ref(w.curve(c))},.T.)`);
+ edges.push({ id, a, b, mid: mids[i] });
+ return w.add(`ORIENTED_EDGE('',*,*,${ref(id)},.T.)`);
+ });
+ const el = w.add(`EDGE_LOOP('',${list(oes)})`);
+ return w.add(`${li === 0 ? 'FACE_OUTER_BOUND' : 'FACE_BOUND'}('',${ref(el)},.T.)`);
+ });
+ return w.add(`ADVANCED_FACE('',${list(bounds)},${ref(surf)},${sense ? '.T.' : '.F.'})`);
+}
+
+function brepSolid(w: StepWriter, b: Brep): number {
+ const verts = b.vertices.map((p) => w.add(`VERTEX_POINT('',${ref(w.point(p))})`));
+ const edges = b.edges.map((e) => w.add(`EDGE_CURVE('',${ref(verts[e.v0])},${ref(verts[e.v1])},${ref(w.curve(e.curve))},.T.)`));
+ const shells = b.shells.map((faces) => {
+ const ids = faces.map((f) => {
+ const surf = w.surface(f.surface);
+ const bounds = f.loops.map((loop, li) => {
+ const oes = loop.map((x) => w.add(`ORIENTED_EDGE('',*,*,${ref(edges[x.e])},${x.fwd ? '.T.' : '.F.'})`));
+ return w.add(`${li === 0 ? 'FACE_OUTER_BOUND' : 'FACE_BOUND'}('',${ref(w.add(`EDGE_LOOP('',${list(oes)})`))},.T.)`);
+ });
+ return w.add(`ADVANCED_FACE('',${list(bounds)},${ref(surf)},${f.sense ? '.T.' : '.F.'})`);
+ });
+ return w.add(`CLOSED_SHELL('',${list(ids)})`);
+ });
+ if (shells.length === 1) return w.add(`MANIFOLD_SOLID_BREP('',${ref(shells[0])})`);
+ const voids = shells.slice(1).map((s) => w.add(`ORIENTED_CLOSED_SHELL('',*,${ref(s)},.F.)`));
+ return w.add(`BREP_WITH_VOIDS('',${ref(shells[0])},${list(voids)})`);
+}
+
+/** STEP text of the converted model, in millimetres. */
+export function modelToStep(model: IgesModel, name: string, tol: number): string {
+ const w = new StepWriter();
+ const appCtx = w.add(`APPLICATION_CONTEXT('core data for automotive mechanical design processes')`);
+ w.add(`APPLICATION_PROTOCOL_DEFINITION('international standard','automotive_design',2000,${ref(appCtx)})`);
+ const prodCtx = w.add(`PRODUCT_CONTEXT('',${ref(appCtx)},'mechanical')`);
+ const prod = w.add(`PRODUCT(${str(name)},${str(name)},'',(${ref(prodCtx)}))`);
+ const pdf = w.add(`PRODUCT_DEFINITION_FORMATION('','',${ref(prod)})`);
+ const pdc = w.add(`PRODUCT_DEFINITION_CONTEXT('part definition',${ref(appCtx)},'design')`);
+ const pd = w.add(`PRODUCT_DEFINITION('design','',${ref(pdf)},${ref(pdc)})`);
+ const pds = w.add(`PRODUCT_DEFINITION_SHAPE('','',${ref(pd)})`);
+ const lu = w.add(`(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.MILLI.,.METRE.))`);
+ const au = w.add(`(NAMED_UNIT(*)PLANE_ANGLE_UNIT()SI_UNIT($,.RADIAN.))`);
+ const su = w.add(`(NAMED_UNIT(*)SI_UNIT($,.STERADIAN.)SOLID_ANGLE_UNIT())`);
+ const unc = w.add(`UNCERTAINTY_MEASURE_WITH_UNIT(LENGTH_MEASURE(${real(tol)}),${ref(lu)},'distance_accuracy_value','')`);
+ const gctx = w.add(`(GEOMETRIC_REPRESENTATION_CONTEXT(3)GLOBAL_UNCERTAINTY_ASSIGNED_CONTEXT((${ref(unc)}))GLOBAL_UNIT_ASSIGNED_CONTEXT((${ref(lu)},${ref(au)},${ref(su)}))REPRESENTATION_CONTEXT('',''))`);
+ const items: number[] = [w.axis2([0, 0, 0], [0, 0, 1], [1, 0, 0])];
+ for (const b of model.breps) items.push(brepSolid(w, b));
+ if (model.faces.length) {
+ const faces = model.faces.map((f) => trimmedFace(w, f.surface, f.sense, f.loops, tol));
+ items.push(w.add(`SHELL_BASED_SURFACE_MODEL('',(${ref(w.add(`OPEN_SHELL('',${list(faces)})`))}))`));
+ }
+ const rep = w.add(`ADVANCED_BREP_SHAPE_REPRESENTATION('',${list(items)},${ref(gctx)})`);
+ w.add(`SHAPE_DEFINITION_REPRESENTATION(${ref(pds)},${ref(rep)})`);
+ return [
+ 'ISO-10303-21;',
+ 'HEADER;',
+ `FILE_DESCRIPTION(('IGES model'),'2;1');`,
+ `FILE_NAME(${str(name)},'',(''),(''),'Parametric','Parametric','');`,
+ `FILE_SCHEMA(('AUTOMOTIVE_DESIGN { 1 0 10303 214 1 1 1 1 }'));`,
+ 'ENDSEC;',
+ 'DATA;',
+ ...w.lines,
+ 'ENDSEC;',
+ 'END-ISO-10303-21;',
+ '',
+ ].join('\n');
+}
diff --git a/src/parametric/src/formats/iges/write.ts b/src/parametric/src/formats/iges/write.ts
new file mode 100644
index 0000000000..ce28ba90b8
--- /dev/null
+++ b/src/parametric/src/formats/iges/write.ts
@@ -0,0 +1,258 @@
+// Writes IGES 5.3 files: trimmed NURBS surfaces (144 over 128) bounded by
+// curves on the surface (142) that carry both the model-space edge curves
+// (110 lines and 126 B-splines) and the same boundary in the surface's
+// parameter space. Bodies of an assembly become named, coloured groups (402).
+
+import { type NurbsCurve, type NurbsSurface, type Pt, curveDomain, distance, simplifyCurve, simplifySurface, surfaceDomain } from './nurbs';
+
+/** A model-space boundary piece: a straight segment or a curve. */
+export type EdgeCurve = { line: [Pt, Pt] } | { curve: NurbsCurve };
+
+export interface IgesLoop {
+ /** Model-space pieces in order, head to tail. */
+ model: EdgeCurve[];
+ /** The same loop in the surface's (u, v) space, or null to leave it to the reader. */
+ param: NurbsCurve[] | null;
+}
+
+export interface IgesFace {
+ surface: NurbsSurface;
+ /** The outer loop first, then holes. */
+ loops: IgesLoop[];
+}
+
+export interface IgesBody {
+ name?: string;
+ /** RGB in 0..1. */
+ color?: [number, number, number];
+ faces: IgesFace[];
+}
+
+export interface IgesWriteOptions {
+ /** The model's name, written as the sending product's name. */
+ name: string;
+ fileName: string;
+ /** Distances closer than this are the same point (millimetres). */
+ resolution: number;
+ date?: Date;
+ /** Put each body in a named group (for assemblies). */
+ groups?: boolean;
+}
+
+// ---------- formatting ----------
+
+/** An IGES real: always with a decimal point, shortest round-trip digits. */
+export function igesReal(x: number): string {
+ if (!Number.isFinite(x) || x === 0) return '0.';
+ let s = String(x);
+ if (s.includes('e')) {
+ const [m, e] = s.split('e');
+ s = `${m.includes('.') ? m : `${m}.`}E${e.replace('+', '')}`;
+ } else if (!s.includes('.')) s += '.';
+ return s;
+}
+
+/** IGES text is 7-bit: accents are dropped and anything else becomes '_'. */
+export function asciiOnly(s: string): string {
+ return s.normalize('NFKD').replace(/[̀-ͯ]/g, '').replace(/[^\x20-\x7e]/g, '_');
+}
+
+export const hollerith = (s: string) => {
+ const a = asciiOnly(s);
+ return `${a.length}H${a}`;
+};
+
+type Param = number | string | { real: number };
+
+const fmt = (p: Param): string => (typeof p === 'number' ? (Number.isInteger(p) ? String(p) : igesReal(p)) : typeof p === 'string' ? p : igesReal(p.real));
+const R = (x: number): Param => ({ real: x });
+
+const pad = (s: string | number, w: number) => String(s).padStart(w, ' ');
+const seq = (letter: string, n: number) => `${letter}${String(n).padStart(7, '0')}`;
+
+interface Entry {
+ type: number;
+ form: number;
+ params: Param[];
+ status: string;
+ color: number;
+ label: string;
+}
+
+/** Collects entities and writes the five sections of an IGES file. */
+export class IgesWriter {
+ private entries: Entry[] = [];
+ private maxCoord = 0;
+
+ /** Adds an entity; returns its directory entry pointer. */
+ add(type: number, params: Param[], opts: { form?: number; status?: string; color?: number; label?: string } = {}): number {
+ this.entries.push({ type, form: opts.form ?? 0, params, status: opts.status ?? '00000000', color: opts.color ?? 0, label: opts.label ?? '' });
+ return this.entries.length * 2 - 1;
+ }
+
+ /** Sets one entity's status (after it is known to be grouped). */
+ setStatus(de: number, status: string) {
+ this.entries[(de - 1) / 2].status = status;
+ }
+
+ note(p: Pt) {
+ for (const x of p) this.maxCoord = Math.max(this.maxCoord, Math.abs(x));
+ }
+
+ toString(o: IgesWriteOptions): string {
+ const lines: string[] = [];
+ // Start section.
+ const start = ['Parametric IGES export: trimmed NURBS surfaces.'];
+ start.forEach((s, i) => lines.push(`${asciiOnly(s).slice(0, 72).padEnd(72)}${seq('S', i + 1)}`));
+ // Global section.
+ const d = o.date ?? new Date();
+ const two = (n: number) => String(n).padStart(2, '0');
+ const stamp = `${d.getUTCFullYear()}${two(d.getUTCMonth() + 1)}${two(d.getUTCDate())}.${two(d.getUTCHours())}${two(d.getUTCMinutes())}${two(d.getUTCSeconds())}`;
+ const global: Param[] = [
+ '1H,', '1H;', hollerith(o.name), hollerith(o.fileName), hollerith('Parametric'), hollerith('Parametric IGES 1.0'),
+ 32, 308, 15, 308, 15, hollerith(o.name), R(1), 2, hollerith('MM'), 1, R(0.01), hollerith(stamp),
+ R(o.resolution), R(this.maxCoord || 1), '', '', 11, 0, hollerith(stamp),
+ ];
+ const g = this.pack(global, 72);
+ g.forEach((s, i) => lines.push(`${s.padEnd(72)}${seq('G', i + 1)}`));
+ // Parameter data first, to know each entity's pointer and line count.
+ const pd: string[] = [];
+ const ptr: number[] = [], count: number[] = [];
+ this.entries.forEach((e, i) => {
+ const de = i * 2 + 1;
+ const body = this.pack([e.type, ...e.params], 64);
+ ptr.push(pd.length + 1);
+ count.push(body.length);
+ for (const s of body) pd.push(`${s.padEnd(64)} ${String(de).padStart(7, '0')}${seq('P', pd.length + 1)}`);
+ });
+ const dir: string[] = [];
+ this.entries.forEach((e, i) => {
+ const n = i * 2 + 1;
+ dir.push(`${pad(e.type, 8)}${pad(ptr[i], 8)}${pad(0, 8)}${pad(0, 8)}${pad(0, 8)}${pad(0, 8)}${pad(0, 8)}${pad(0, 8)}${e.status}${seq('D', n)}`);
+ dir.push(`${pad(e.type, 8)}${pad(0, 8)}${pad(e.color, 8)}${pad(count[i], 8)}${pad(e.form, 8)}${' '.repeat(16)}${pad(asciiOnly(e.label).slice(0, 8), 8)}${pad(0, 8)}${seq('D', n + 1)}`);
+ });
+ lines.push(...dir, ...pd);
+ lines.push(`${seq('S', start.length)}${seq('G', g.length)}${seq('D', dir.length)}${seq('P', pd.length)}`.padEnd(72) + seq('T', 1));
+ return lines.join('\n') + '\n';
+ }
+
+ /**
+ * Splits a record into lines of at most `width` characters. Parameters are
+ * never split across lines, except strings longer than a line.
+ */
+ private pack(params: Param[], width: number): string[] {
+ const out: string[] = [];
+ let cur = '';
+ params.forEach((p, i) => {
+ let tok = fmt(p) + (i === params.length - 1 ? ';' : ',');
+ if (cur.length + tok.length <= width) { cur += tok; return; }
+ if (cur) out.push(cur);
+ cur = '';
+ while (tok.length > width) { out.push(tok.slice(0, width)); tok = tok.slice(width); }
+ cur = tok;
+ });
+ if (cur) out.push(cur);
+ return out;
+ }
+}
+
+// ---------- entities ----------
+
+const DEP = '00010000'; // physically dependent geometry
+const DEP_PARAM = '00010500'; // physically dependent, in a parameter space
+
+function closedCurve(c: NurbsCurve): boolean {
+ const [a, b] = curveDomain(c);
+ const p0 = c.poles[0], p1 = c.poles[c.poles.length - 1];
+ return a < b && distance(p0, p1) < 1e-9 * (1 + Math.abs(p0[0]) + Math.abs(p0[1]));
+}
+
+/** 126: a rational B-spline curve; 2D curves are written in the z = 0 plane. */
+function bsplineCurve(w: IgesWriter, curve: NurbsCurve, status: string): number {
+ const c = simplifyCurve(curve);
+ const n = c.poles.length, p = c.degree;
+ const planar = c.poles[0].length === 2;
+ const params: Param[] = [n - 1, p, planar ? 1 : 0, closedCurve(c) ? 1 : 0, c.weights ? 0 : 1, 0];
+ for (const k of c.knots) params.push(R(k));
+ for (let i = 0; i < n; i++) params.push(R(c.weights ? c.weights[i] : 1));
+ for (const q of c.poles) {
+ if (!planar) w.note(q);
+ params.push(R(q[0]), R(q[1]), R(planar ? 0 : q[2]));
+ }
+ const [t0, t1] = curveDomain(c);
+ params.push(R(t0), R(t1), R(0), R(0), R(planar ? 1 : 0));
+ return w.add(126, params, { status });
+}
+
+function lineEntity(w: IgesWriter, a: Pt, b: Pt): number {
+ w.note(a);
+ w.note(b);
+ return w.add(110, [R(a[0]), R(a[1]), R(a[2]), R(b[0]), R(b[1]), R(b[2])], { status: DEP });
+}
+
+/** 128: a rational B-spline surface. */
+function bsplineSurface(w: IgesWriter, surface: NurbsSurface): number {
+ const s = simplifySurface(surface);
+ const nu = s.poles.length, nv = s.poles[0].length;
+ const closedU = s.poles[0].every((p, j) => distance(p, s.poles[nu - 1][j]) < 1e-9);
+ const closedV = s.poles.every((row) => distance(row[0], row[nv - 1]) < 1e-9);
+ const params: Param[] = [nu - 1, nv - 1, s.degU, s.degV, closedU ? 1 : 0, closedV ? 1 : 0, s.weights ? 0 : 1, 0, 0];
+ for (const k of s.knotsU) params.push(R(k));
+ for (const k of s.knotsV) params.push(R(k));
+ // Weights and poles with U varying fastest.
+ for (let j = 0; j < nv; j++) for (let i = 0; i < nu; i++) params.push(R(s.weights ? s.weights[i][j] : 1));
+ for (let j = 0; j < nv; j++) {
+ for (let i = 0; i < nu; i++) {
+ const q = s.poles[i][j];
+ w.note(q);
+ params.push(R(q[0]), R(q[1]), R(q[2]));
+ }
+ }
+ const [u0, u1, v0, v1] = surfaceDomain(s);
+ params.push(R(u0), R(u1), R(v0), R(v1));
+ return w.add(128, params, { status: DEP });
+}
+
+/** One curve, or a 102 composite of several. */
+function composite(w: IgesWriter, des: number[], status: string): number {
+ return des.length === 1 ? des[0] : w.add(102, [des.length, ...des], { status });
+}
+
+function trimmedFace(w: IgesWriter, f: IgesFace, status: string, color: number): number {
+ const srf = bsplineSurface(w, f.surface);
+ const bounds = f.loops.map((loop) => {
+ const model = composite(w, loop.model.map((e) => ('line' in e ? lineEntity(w, e.line[0], e.line[1]) : bsplineCurve(w, e.curve, DEP))), DEP);
+ const param = loop.param?.length ? composite(w, loop.param.map((c) => bsplineCurve(w, c, DEP_PARAM)), DEP_PARAM) : 0;
+ // Created by projection (1); both representations are equally good (3), else the model curve (2).
+ return w.add(142, [1, srf, param, model, param ? 3 : 2], { status: DEP_PARAM });
+ });
+ return w.add(144, [srf, 1, bounds.length - 1, bounds[0], ...bounds.slice(1)], { status, color });
+}
+
+/** The IGES text of bodies made of trimmed faces. */
+export function writeIges(bodies: IgesBody[], o: IgesWriteOptions): string {
+ const w = new IgesWriter();
+ const colors = new Map();
+ const colorOf = (rgb?: [number, number, number]) => {
+ if (!rgb) return 0;
+ const key = rgb.map((x) => Math.round(x * 1000)).join(',');
+ let de = colors.get(key);
+ if (!de) {
+ de = w.add(314, rgb.map((x) => R(Math.round(Math.min(1, Math.max(0, x)) * 10000) / 100)), { status: '00000200' });
+ colors.set(key, de);
+ }
+ return -de;
+ };
+ for (const b of bodies) {
+ if (!b.faces.length) continue;
+ const color = colorOf(b.color);
+ const faces = b.faces.filter((f) => f.loops.length && f.loops[0].model.length).map((f) => trimmedFace(w, f, o.groups ? '00020000' : '00000000', color));
+ if (o.groups && faces.length) {
+ const props: Param[] = [];
+ if (b.name) props.push(0, 1, w.add(406, [1, hollerith(b.name)], { form: 15, status: '00010000' }));
+ w.add(402, [faces.length, ...faces, ...props], { form: 7, color, label: b.name ?? '' });
+ }
+ }
+ return w.toString(o);
+}
+
diff --git a/src/parametric/src/kernel/assembly.ts b/src/parametric/src/kernel/assembly.ts
index 2ab885be1d..087e8aef78 100644
--- a/src/parametric/src/kernel/assembly.ts
+++ b/src/parametric/src/kernel/assembly.ts
@@ -5,7 +5,7 @@
// meshes itself, so moving a component never needs the worker; the worker
// keeps the current placement of every component (the scene) for what needs
// the exact solids: measuring between components, interference, mass
-// properties, drawing projections and STEP and STL export.
+// properties, drawing projections and STEP, IGES and STL export.
import * as R from 'replicad';
import type { Vec3 } from '../math/vec';
@@ -13,6 +13,7 @@ import { add, dist, scale, sub } from '../math/vec';
import type { Feature, Id } from '../model/types';
import { ModelBuilder, eigenSym3 } from './build';
import { cutOutlines, halfOf } from './drawing-section';
+import { exportIges } from './iges';
import { type Sh, bbox, common, compound, getOc, gdir, meshShape, pnt, projectShape, subShapes, volumeOf, wrap, xyz } from './occ';
import type { BuildResult, EdgeInfo, FaceInfo, FeatureStatus, MassProperties, MeasureResult, MeasureTarget, MeshData, ProjectionRequest, ProjectionResult } from './protocol';
@@ -368,6 +369,13 @@ export class AssemblyBuilder {
}
}
+ /** An IGES file with every component as a named, coloured group of its own. */
+ exportIges(name?: string): Uint8Array {
+ const list = this.shapes();
+ if (!list.length) throw new Error('There is no geometry to export');
+ return exportIges(list.map(({ i, shape }) => ({ shape, name: this.scene[i].name, color: this.scene[i].color })), name ?? 'Assembly', { groups: true });
+ }
+
/** Binary STL of all components where they are placed. */
exportStl(quality: number): Uint8Array {
const list = this.bodies();
diff --git a/src/parametric/src/kernel/build.ts b/src/parametric/src/kernel/build.ts
index 4ab3c28677..6c017c3cc7 100644
--- a/src/parametric/src/kernel/build.ts
+++ b/src/parametric/src/kernel/build.ts
@@ -40,10 +40,12 @@ import {
} from './occ';
import { SurfaceKit, bodyEdges, type SurfaceBody, type SurfState } from './surfaces';
import { SURFACE_TYPES, type SurfaceFeature } from '../model/surfaces';
+import { FeatureError } from './errors';
+import { readStep, stepString, writeStepShape } from './stepfile';
+import { exportIges } from './iges';
export { BASE_FRAMES };
-
-export class FeatureError extends Error {}
+export { FeatureError, stepString };
// STL holds closed meshes for printing: surface bodies are left out of it.
const STL_SOLIDS_ONLY = 'STL files hold solids only, and this part has only surfaces. Thicken or knit the surfaces into a solid, or export STEP to keep them.';
@@ -1790,22 +1792,14 @@ export class ModelBuilder {
// Surface bodies go into the file as shells beside the solid.
const body = this.current.surfaces.length ? this.surf.allShapes(this.current) : this.current.body;
if (!body) throw new FeatureError('There is no geometry to export');
- const oc = getOc();
- const writer = new oc.STEPControl_Writer();
- oc.Interface_Static.SetIVal('write.step.schema', 5);
- oc.Interface_Static.SetCVal('write.step.unit', 'MM');
- const progress = new oc.Message_ProgressRange();
- try {
- writer.Transfer(body.wrapped, oc.STEPControl_StepModelType.STEPControl_AsIs, true, progress);
- const done = writer.Write('/export.step');
- if (done !== oc.IFSelect_ReturnStatus.IFSelect_RetDone) throw new FeatureError('STEP export failed');
- const data: Uint8Array = oc.FS.readFile('/export.step');
- oc.FS.unlink('/export.step');
- return name ? namedStep(data, name) : data;
- } finally {
- writer.delete();
- progress.delete();
- }
+ return writeStepShape(body, name);
+ }
+
+ /** An IGES file of the current body (and surface bodies), named `name`. */
+ exportIges(name?: string): Uint8Array {
+ const body = this.current.surfaces.length ? this.surf.allShapes(this.current) : this.current.body;
+ if (!body) throw new FeatureError('There is no geometry to export');
+ return exportIges([{ shape: body }], name ?? 'Part');
}
/**
@@ -1940,36 +1934,6 @@ export class ModelBuilder {
}
}
-/**
- * The writer names the product (and the file) after itself ("Open CASCADE
- * STEP translator 8.0 1"), which other CAD systems then show as the part's
- * name. Only the header and the product entity carry these strings.
- */
-function namedStep(data: Uint8Array, name: string): Uint8Array {
- const text = new TextDecoder().decode(data);
- const value = stepString(name);
- const named = text
- .replace(/'Open CASCADE STEP translator [^']*'/g, () => value)
- .replace(/FILE_NAME\('Open CASCADE Shape Model',('[^']*'),\('Author'\)/, (_m, time: string) => `FILE_NAME(${value},${time},('')`);
- return new TextEncoder().encode(named);
-}
-
-/** A STEP string literal: quotes and backslashes doubled, other than printable ASCII as \X2\ (UTF-16) hex. */
-export function stepString(s: string): string {
- let out = '';
- let wide = '';
- const flush = () => { if (wide) { out += `\\X2\\${wide}\\X0\\`; wide = ''; } };
- for (let i = 0; i < s.length; i++) {
- const c = s.charCodeAt(i);
- if (c >= 0x20 && c <= 0x7e) {
- flush();
- out += c === 0x27 ? "''" : c === 0x5c ? '\\\\' : s[i];
- } else if (c >= 0x20) wide += c.toString(16).toUpperCase().padStart(4, '0');
- }
- flush();
- return `'${out}'`;
-}
-
/**
* Recently read STEP files by content. Checking an import reads the file,
* and the build that follows reuses that shape instead of reading it again
@@ -1997,25 +1961,6 @@ export async function checkStep(text: string): Promise {
}
}
-async function readStep(text: string): Promise {
- const oc = getOc();
- const name = `/import-${Date.now()}.step`;
- oc.FS.writeFile(name, text);
- const reader = new oc.STEPControl_Reader();
- const progress = new oc.Message_ProgressRange();
- try {
- if (reader.ReadFile(name) !== oc.IFSelect_ReturnStatus.IFSelect_RetDone) throw new FeatureError('The STEP file could not be read');
- reader.TransferRoots(progress);
- const shape = wrap(reader.OneShape());
- if (isEmpty(shape)) throw new FeatureError('The STEP file contains no geometry');
- return shape;
- } finally {
- reader.delete();
- progress.delete();
- try { oc.FS.unlink(name); } catch { /* already removed */ }
- }
-}
-
/** A WebAssembly trap or abort: the OpenCascade module can no longer be used. */
export function isFatal(e: unknown): boolean {
return typeof WebAssembly !== 'undefined' && e instanceof WebAssembly.RuntimeError;
diff --git a/src/parametric/src/kernel/client.ts b/src/parametric/src/kernel/client.ts
index 60b1c6b505..f9a7f2ed01 100644
--- a/src/parametric/src/kernel/client.ts
+++ b/src/parametric/src/kernel/client.ts
@@ -8,6 +8,7 @@
// KernelRestartError instead of waiting forever.
import type { SolidWorksImport } from '../formats/sldprt';
+import type { IgesImport } from './iges';
import type { Id } from '../model/types';
import type { AsmPartBuild, AsmRequest, AsmSceneItem } from './assembly';
import type { BuildRequest, BuildResult, FeaSurface, FlatPatternResult, MassProperties, MeasureResult, MeasureTarget, MeshData, ProjectionRequest, ProjectionResult, WeldVolumes, WorkerRequest, WorkerResponse } from './protocol';
@@ -286,8 +287,8 @@ export class KernelClient {
return this.call({ type: 'measure', a, b });
}
- /** `name` is the part's name, written into a STEP file as its product's name. */
- exportFile(format: 'step' | 'stl', quality = 1, name?: string): Promise {
+ /** `name` is the part's name, written into a STEP or IGES file as its product's name. */
+ exportFile(format: 'step' | 'iges' | 'stl', quality = 1, name?: string): Promise {
return this.call({ type: 'export', format, quality, name });
}
@@ -305,6 +306,11 @@ export class KernelClient {
return this.call({ type: 'convertSolidWorks', data, name });
}
+ /** Converts an IGES file to STEP text. Rejects with a readable message. */
+ convertIges(text: string, name: string): Promise {
+ return this.call({ type: 'convertIges', text, name });
+ }
+
/** Returns null when the STEP text imports cleanly, else an error message. */
checkImport(text: string): Promise {
return this.call({ type: 'checkImport', format: 'step', text });
diff --git a/src/parametric/src/kernel/errors.ts b/src/parametric/src/kernel/errors.ts
new file mode 100644
index 0000000000..4ea3b661ca
--- /dev/null
+++ b/src/parametric/src/kernel/errors.ts
@@ -0,0 +1,2 @@
+/** A feature (or file) the kernel cannot build, with a message for the user. */
+export class FeatureError extends Error {}
diff --git a/src/parametric/src/kernel/iges.ts b/src/parametric/src/kernel/iges.ts
new file mode 100644
index 0000000000..4035acc078
--- /dev/null
+++ b/src/parametric/src/kernel/iges.ts
@@ -0,0 +1,693 @@
+/* eslint-disable @typescript-eslint/no-explicit-any */
+// IGES export from the geometry kernel's B-rep, and the kernel half of IGES
+// import (reading the converted faces, sewing them into solids).
+//
+// Export writes every face as a trimmed NURBS surface. Planes, cylinders,
+// cones, spheres, tori and surfaces of revolution and extrusion become exact
+// rational B-spline surfaces; B-spline surfaces are copied; anything else
+// (offset surfaces) is interpolated within a tight tolerance. Each boundary is
+// written twice, as model-space curves and as curves in the surface's
+// parameter space, so readers can use either.
+
+import { type Sh, bbox, common, compound, cut, getOc, subShapes, volumeOf, wrap, xyz } from './occ';
+import { FeatureError } from './errors';
+import { readStep, writeStepShape } from './stepfile';
+import { IgesError, parseIges } from '../formats/iges/parse';
+import { convertIges } from '../formats/iges/convert';
+import { modelToStep } from '../formats/iges/step';
+import {
+ type NurbsCurve, type NurbsSurface, type Pt, add, angleToParam, arcCurve, cross, curvePoint, distance, dot, extrudeCurve, fitCurve, fitSurface,
+ lineCurve, mapCurve, mul, reverseCurve, reverseSurfaceU, revolveCurve, sub, surfaceDomain, surfacePoint, unit,
+} from '../formats/iges/nurbs';
+import { type EdgeCurve, type IgesBody, type IgesFace, type IgesLoop, writeIges } from '../formats/iges/write';
+
+// ---------- reading OpenCascade geometry ----------
+
+function expanded(n: number, knot: (i: number) => number, mult: (i: number) => number): number[] {
+ const out: number[] = [];
+ for (let i = 1; i <= n; i++) for (let m = mult(i); m > 0; m--) out.push(knot(i));
+ return out;
+}
+
+/** A Geom_BSplineCurve's data, unfolded when periodic. */
+function curveData(bc: any, dim: 2 | 3): NurbsCurve {
+ const oc = getOc();
+ let c = bc, copy = null;
+ if (bc.IsPeriodic()) {
+ copy = dim === 3 ? new oc.Geom_BSplineCurve(bc) : new oc.Geom2d_BSplineCurve(bc);
+ copy.SetNotPeriodic();
+ c = copy;
+ }
+ try {
+ const n = c.NbPoles();
+ const poles: Pt[] = [];
+ for (let i = 1; i <= n; i++) {
+ const p = c.Pole(i);
+ poles.push(dim === 3 ? xyz(p) : [p.X(), p.Y()]);
+ p.delete();
+ }
+ const weights = c.IsRational() ? Array.from({ length: n }, (_, i) => c.Weight(i + 1)) : null;
+ return { degree: c.Degree(), knots: expanded(c.NbKnots(), (i) => c.Knot(i), (i) => c.Multiplicity(i)), poles, weights };
+ } finally {
+ copy?.delete();
+ }
+}
+
+/** A Geom_BSplineSurface's data, unfolded when periodic (on a copy: the model's surface is left alone). */
+function surfaceData(bs: any): NurbsSurface {
+ const oc = getOc();
+ let s = bs, copy = null;
+ if (bs.IsUPeriodic() || bs.IsVPeriodic()) {
+ copy = new oc.Geom_BSplineSurface(bs);
+ if (copy.IsUPeriodic()) copy.SetUNotPeriodic();
+ if (copy.IsVPeriodic()) copy.SetVNotPeriodic();
+ s = copy;
+ }
+ try {
+ const nu = s.NbUPoles(), nv = s.NbVPoles();
+ const rational = s.IsURational() || s.IsVRational();
+ const poles: Pt[][] = [], weights: number[][] = [];
+ for (let i = 1; i <= nu; i++) {
+ const row: Pt[] = [], wr: number[] = [];
+ for (let j = 1; j <= nv; j++) {
+ const p = s.Pole(i, j);
+ row.push(xyz(p));
+ p.delete();
+ wr.push(rational ? s.Weight(i, j) : 1);
+ }
+ poles.push(row);
+ weights.push(wr);
+ }
+ return {
+ degU: s.UDegree(), degV: s.VDegree(),
+ knotsU: expanded(s.NbUKnots(), (i) => s.UKnot(i), (i) => s.UMultiplicity(i)),
+ knotsV: expanded(s.NbVKnots(), (i) => s.VKnot(i), (i) => s.VMultiplicity(i)),
+ poles, weights: rational ? weights : null,
+ };
+ } finally {
+ copy?.delete();
+ }
+}
+
+/** A curve with a map from the original parameter to the NURBS parameter. */
+interface MappedCurve { c: NurbsCurve; map: (t: number) => number; affine: boolean; breaks?: number[] }
+
+const identity = (t: number) => t;
+
+/**
+ * An adaptor curve (an edge's, or a swept surface's basis curve) on [t0, t1]
+ * as NURBS whose parameter is known: lines and B-splines keep theirs, arcs
+ * get the tangent half-angle map, anything else is interpolated.
+ */
+function adaptorCurve(ad: any, t0: number, t1: number, tol: number): MappedCurve {
+ const oc = getOc();
+ const gc = oc.GeomAbs_CurveType;
+ const ev = (t: number): Pt => { const p = ad.Value(t); const r = xyz(p); p.delete(); return r; };
+ const type = ad.GetType();
+ try {
+ if (type === gc.GeomAbs_Line) return { c: lineCurve(ev(t0), ev(t1), t0, t1), map: identity, affine: true };
+ if (type === gc.GeomAbs_Circle || type === gc.GeomAbs_Ellipse) {
+ // From points: c + cos(t) e1 + sin(t) e2 is exact for both.
+ const c = mul(add(ev(0), ev(Math.PI)), 0.5);
+ const e1 = sub(ev(0), c), e2 = sub(ev(Math.PI / 2), c);
+ return { c: arcCurve(c, e1, e2, t0, t1), map: (t) => angleToParam(t0, t1, t), affine: false, breaks: arcBreaks(t0, t1) };
+ }
+ if (type === gc.GeomAbs_BSplineCurve) {
+ const bc = ad.BSpline();
+ try { return { c: curveData(bc, 3), map: identity, affine: true }; } finally { bc.delete?.(); }
+ }
+ } catch {
+ // Fall through to interpolation.
+ }
+ return { c: fitCurve(ev, t0, t1, tol), map: identity, affine: true };
+}
+
+/** A face's surface as NURBS with the maps from its (u, v) to the NURBS parameters. */
+interface MappedSurface {
+ s: NurbsSurface;
+ mu: (u: number) => number;
+ mv: (v: number) => number;
+ affineU: boolean;
+ affineV: boolean;
+ /** Where the maps are only C1 (arc piece boundaries): curves are interpolated piecewise between them. */
+ breaksU?: number[];
+ breaksV?: number[];
+}
+
+/** The angles where arcCurve(..., a0, a1) changes piece. */
+function arcBreaks(a0: number, a1: number): number[] {
+ const n = Math.max(1, Math.ceil((a1 - a0) / (Math.PI / 2) - 1e-9));
+ return Array.from({ length: n - 1 }, (_, i) => a0 + ((a1 - a0) * (i + 1)) / n);
+}
+
+/** Joins clamped cubic curves end to end (C0 joins). */
+function joinCurves(parts: NurbsCurve[]): NurbsCurve {
+ if (parts.length === 1) return parts[0];
+ const p = parts[0].degree;
+ const poles = [...parts[0].poles], knots = parts[0].knots.slice(0, -1);
+ for (const c of parts.slice(1)) {
+ poles.push(...c.poles.slice(1));
+ knots.push(...c.knots.slice(p + 1, -1));
+ }
+ knots.push(parts[parts.length - 1].knots[parts[parts.length - 1].knots.length - 1]);
+ return { degree: p, knots, poles, weights: null };
+}
+
+/**
+ * Interpolates a mapped parameter-space curve, split where it crosses the
+ * maps' piece boundaries so each piece is smooth.
+ */
+function fitPieces(raw: (t: number) => Pt, map: (p: Pt) => Pt, m: MappedSurface, f: number, l: number, ptol: number): NurbsCurve {
+ const cuts: number[] = [];
+ const N = 64;
+ const samples = Array.from({ length: N + 1 }, (_, i) => raw(f + ((l - f) * i) / N));
+ for (const [k, breaks] of [[0, m.breaksU ?? []], [1, m.breaksV ?? []]] as const) {
+ for (const b of breaks) {
+ for (let i = 0; i < N; i++) {
+ const x0 = samples[i][k] - b, x1 = samples[i + 1][k] - b;
+ if (x0 === 0 || x0 * x1 >= 0) continue;
+ let lo = f + ((l - f) * i) / N, hi = f + ((l - f) * (i + 1)) / N;
+ const sLo = Math.sign(x0);
+ for (let it = 0; it < 60; it++) {
+ const mid = (lo + hi) / 2;
+ if (Math.sign(raw(mid)[k] - b) === sLo) lo = mid;
+ else hi = mid;
+ }
+ cuts.push((lo + hi) / 2);
+ }
+ }
+ }
+ const ts = [f, ...cuts.filter((t) => t > f + (l - f) * 1e-9 && t < l - (l - f) * 1e-9).sort((a, b) => a - b), l];
+ const parts: NurbsCurve[] = [];
+ for (let i = 0; i + 1 < ts.length; i++) {
+ if (ts[i + 1] - ts[i] <= (l - f) * 1e-9) continue;
+ parts.push(fitCurve((t) => map(raw(t)), ts[i], ts[i + 1], ptol, 513));
+ }
+ return joinCurves(parts);
+}
+
+function faceSurface(face: any, u0: number, u1: number, v0: number, v1: number, tol: number): MappedSurface {
+ const oc = getOc();
+ const ga = oc.GeomAbs_SurfaceType;
+ const ad = new oc.BRepAdaptor_Surface(face, true);
+ const P = (u: number, v: number): Pt => { const p = ad.Value(u, v); const r = xyz(p); p.delete(); return r; };
+ const handedness = (X: Pt, Y: Pt, Z: Pt) => (dot(Y, cross(Z, X)) < 0 ? -1 : 1);
+ const angular = (a: number, b: number) => (t: number) => angleToParam(a, b, t);
+ const frame = (ax3: any) => {
+ const o = ax3.Location(), x = ax3.XDirection(), y = ax3.YDirection(), z = ax3.Direction();
+ const r = { O: xyz(o), X: xyz(x), Y: xyz(y), Z: xyz(z) };
+ o.delete(); x.delete(); y.delete(); z.delete();
+ return r;
+ };
+ const exact = (): MappedSurface | null => {
+ const t = ad.GetType();
+ if (t === ga.GeomAbs_Plane) {
+ const pl = ad.Plane(), pos = pl.Position();
+ const { O, X, Y } = frame(pos);
+ pos.delete(); pl.delete();
+ const at = (u: number, v: number) => add(O, add(mul(X, u), mul(Y, v)));
+ const s: NurbsSurface = { degU: 1, degV: 1, knotsU: [u0, u0, u1, u1], knotsV: [v0, v0, v1, v1], poles: [[at(u0, v0), at(u0, v1)], [at(u1, v0), at(u1, v1)]], weights: null };
+ return { s, mu: identity, mv: identity, affineU: true, affineV: true };
+ }
+ if (t === ga.GeomAbs_Cylinder || t === ga.GeomAbs_Sphere) {
+ const g = t === ga.GeomAbs_Cylinder ? ad.Cylinder() : ad.Sphere();
+ const pos = g.Position();
+ const { O, X, Y, Z } = frame(pos);
+ const R = g.Radius();
+ pos.delete(); g.delete();
+ const h = handedness(X, Y, Z);
+ if (t === ga.GeomAbs_Cylinder) {
+ const gen = lineCurve(add(O, add(mul(X, R), mul(Z, v0))), add(O, add(mul(X, R), mul(Z, v1))), v0, v1);
+ return { s: revolveCurve(gen, O, Z, u0, u1, h), mu: angular(u0, u1), mv: identity, affineU: false, affineV: true, breaksU: arcBreaks(u0, u1) };
+ }
+ const gen = arcCurve(O, mul(X, R), mul(Z, R), v0, v1);
+ return { s: revolveCurve(gen, O, Z, u0, u1, h), mu: angular(u0, u1), mv: angular(v0, v1), affineU: false, affineV: false, breaksU: arcBreaks(u0, u1), breaksV: arcBreaks(v0, v1) };
+ }
+ if (t === ga.GeomAbs_Cone) {
+ // gp_Cone is not in the bindings: the frame comes from points on the surface.
+ const centre = (v: number) => mul(add(P(0, v), P(Math.PI, v)), 0.5);
+ const Ca = centre(v0), Cb = centre(v1);
+ const Z = unit(sub(Cb, Ca));
+ const va = distance(P(0, v0), Ca) > distance(P(0, v1), Cb) ? v0 : v1;
+ const C = centre(va);
+ const X = unit(sub(P(0, va), C)), Y = unit(sub(P(Math.PI / 2, va), C));
+ const gen = lineCurve(P(0, v0), P(0, v1), v0, v1);
+ return { s: revolveCurve(gen, C, Z, u0, u1, handedness(X, Y, Z)), mu: angular(u0, u1), mv: identity, affineU: false, affineV: true, breaksU: arcBreaks(u0, u1) };
+ }
+ if (t === ga.GeomAbs_Torus) {
+ const A = P(0, 0), B = P(Math.PI, 0);
+ const O = mul(add(A, B), 0.5);
+ const X = unit(sub(A, O)), Y = unit(sub(P(Math.PI / 2, 0), O));
+ const outer = distance(A, O), inner = dot(sub(P(0, Math.PI), O), X);
+ const R = (outer + inner) / 2, r = (outer - inner) / 2;
+ const Z = unit(sub(P(0, Math.PI / 2), add(O, mul(X, R))));
+ const gen = arcCurve(add(O, mul(X, R)), mul(X, r), mul(Z, r), v0, v1);
+ return { s: revolveCurve(gen, O, Z, u0, u1, handedness(X, Y, Z)), mu: angular(u0, u1), mv: angular(v0, v1), affineU: false, affineV: false, breaksU: arcBreaks(u0, u1), breaksV: arcBreaks(v0, v1) };
+ }
+ if (t === ga.GeomAbs_SurfaceOfRevolution) {
+ const ax = ad.AxeOfRevolution();
+ const lo = ax.Location(), di = ax.Direction();
+ const O = xyz(lo), Z = xyz(di);
+ lo.delete(); di.delete(); ax.delete();
+ const basis = ad.BasisCurve();
+ try {
+ const g = adaptorCurve(basis, v0, v1, tol);
+ return { s: revolveCurve(g.c, O, Z, u0, u1, 1), mu: angular(u0, u1), mv: g.map, affineU: false, affineV: g.affine, breaksU: arcBreaks(u0, u1), breaksV: g.breaks };
+ } finally { basis.delete?.(); }
+ }
+ if (t === ga.GeomAbs_SurfaceOfExtrusion) {
+ const d = ad.Direction();
+ const D = xyz(d);
+ d.delete();
+ const basis = ad.BasisCurve();
+ try {
+ const g = adaptorCurve(basis, u0, u1, tol);
+ return { s: extrudeCurve(g.c, D, v0, v1), mu: g.map, mv: identity, affineU: g.affine, affineV: true, breaksU: g.breaks };
+ } finally { basis.delete?.(); }
+ }
+ if (t === ga.GeomAbs_BSplineSurface) {
+ const bs = ad.BSpline();
+ try { return { s: surfaceData(bs), mu: identity, mv: identity, affineU: true, affineV: true }; } finally { bs.delete?.(); }
+ }
+ if (t === ga.GeomAbs_BezierSurface) {
+ const bs = oc.GeomConvert.SurfaceToBSplineSurface(oc.BRep_Tool.Surface(face));
+ try { return { s: surfaceData(bs), mu: identity, mv: identity, affineU: true, affineV: true }; } finally { bs.delete?.(); }
+ }
+ return null;
+ };
+ try {
+ let m: MappedSurface | null = null;
+ try { m = exact(); } catch { m = null; }
+ // The conversion must reproduce the face's surface (located faces of
+ // swept surfaces, and anything unexpected, fall back to interpolation).
+ if (m) {
+ const um = (u0 + u1) / 2, vm = (v0 + v1) / 2;
+ for (const [u, v] of [[u0, v0], [u1, v1], [um, vm], [u0 * 0.3 + u1 * 0.7, v0 * 0.8 + v1 * 0.2], [u0 * 0.9 + u1 * 0.1, v0 * 0.4 + v1 * 0.6]]) {
+ if (distance(surfacePoint(m.s, m.mu(u), m.mv(v)), P(u, v)) > tol * 10) { m = null; break; }
+ }
+ }
+ return m ?? { s: fitSurface(P, u0, u1, v0, v1, tol), mu: identity, mv: identity, affineU: true, affineV: true };
+ } finally {
+ ad.delete();
+ }
+}
+
+const isReversed = (s: any) => s.Orientation() === getOc().TopAbs_Orientation.TopAbs_REVERSED;
+
+/** An edge's model-space curve along its own parameter. */
+function edgeCurve(edge: any, tol: number): EdgeCurve {
+ const oc = getOc();
+ const ad = new oc.BRepAdaptor_Curve(edge);
+ try {
+ const f = ad.FirstParameter(), l = ad.LastParameter();
+ const ev = (t: number): Pt => { const p = ad.Value(t); const r = xyz(p); p.delete(); return r; };
+ if (ad.GetType() === oc.GeomAbs_CurveType.GeomAbs_Line) return { line: [ev(f), ev(l)] };
+ let c: NurbsCurve | null = null;
+ try {
+ const r = oc.BRep_Tool.Curve(edge, 0, 0);
+ const tc = new oc.Geom_TrimmedCurve(r.returnValue, f, l, true, true);
+ const bc = oc.GeomConvert.CurveToBSplineCurve(tc);
+ c = curveData(bc, 3);
+ bc.delete?.(); tc.delete();
+ // Located edges and unexpected curves: the result must run between the edge's ends.
+ if (distance(c.poles[0], ev(f)) > tol * 10 || distance(c.poles[c.poles.length - 1], ev(l)) > tol * 10) c = null;
+ } catch {
+ c = null;
+ }
+ return { curve: c ?? fitCurve(ev, f, l, tol) };
+ } finally {
+ ad.delete();
+ }
+}
+
+/** An edge's curve in the face's parameter space, mapped into the NURBS surface's parameters, along the edge's own parameter. */
+function edgePcurve(edge: any, face: any, m: MappedSurface, ptol: number): { c: NurbsCurve; a: Pt; b: Pt } {
+ const oc = getOc();
+ // (BRep_Tool.CurveOnSurface with a face does not bind; the adaptor picks a seam's side the same way.)
+ const ad = new oc.BRepAdaptor_Curve2d(edge, face);
+ const f = ad.FirstParameter(), l = ad.LastParameter();
+ const c2 = ad.Curve();
+ try {
+ const raw = (t: number): Pt => { const p = ad.Value(t); const out = [p.X(), p.Y()]; p.delete(); return out; };
+ const map = (p: Pt): Pt => [m.mu(p[0]), m.mv(p[1])];
+ const ev = (t: number) => map(raw(t));
+ const a = ev(f), b = ev(l);
+ const gc = oc.GeomAbs_CurveType;
+ const type = ad.GetType();
+ if (type === gc.GeomAbs_Line) {
+ const p = raw(f), q = raw(l);
+ // The map acts on u and v separately: lines along u or v, and any line under affine maps, stay straight.
+ const straight = Math.abs(p[0] - q[0]) < 1e-12 || Math.abs(p[1] - q[1]) < 1e-12 || (m.affineU && m.affineV);
+ if (straight) return { c: lineCurve(a, b, f, l), a, b };
+ } else if (m.affineU && m.affineV) {
+ try {
+ const tc = new oc.Geom2d_TrimmedCurve(c2, f, l, true, true);
+ const bc = oc.Geom2dConvert.CurveToBSplineCurve(tc);
+ const c = mapCurve(curveData(bc, 2), map);
+ bc.delete?.(); tc.delete();
+ if (distance(curvePoint(c, c.knots[0]), a) < ptol && distance(curvePoint(c, c.knots[c.knots.length - 1]), b) < ptol) return { c, a, b };
+ } catch {
+ // Interpolate below.
+ }
+ }
+ return { c: fitPieces(raw, map, m, f, l, ptol), a, b };
+ } finally {
+ ad.delete();
+ c2.delete?.();
+ }
+}
+
+interface LoopEdge { model: EdgeCurve | null; param: NurbsCurve; a: Pt; b: Pt }
+
+/** Orders a wire's edges head to tail in the parameter plane (exploration order is not guaranteed). */
+function chain(edges: LoopEdge[], tol: number): LoopEdge[] {
+ if (edges.length < 2) return edges;
+ const rest = edges.slice(1);
+ const out = [edges[0]];
+ while (rest.length) {
+ const tail = out[out.length - 1].b;
+ let best = -1, bestD = Infinity;
+ rest.forEach((e, i) => { const d = distance(e.a, tail); if (d < bestD) { bestD = d; best = i; } });
+ if (bestD > tol) return edges;
+ out.push(rest.splice(best, 1)[0]);
+ }
+ return out;
+}
+
+function reverseEdge(e: EdgeCurve): EdgeCurve {
+ return 'line' in e ? { line: [e.line[1], e.line[0]] } : { curve: reverseCurve(e.curve) };
+}
+
+function convertFace(face: any, tol: number): IgesFace {
+ const oc = getOc();
+ const { UMin, UMax, VMin, VMax } = oc.BRepTools.UVBounds(face, 0, 0, 0, 0);
+ if (!(UMax > UMin) || !(VMax > VMin)) throw new FeatureError('A face has no area');
+ const m = faceSurface(face, UMin, UMax, VMin, VMax, tol);
+ const span = Math.max(UMax - UMin, VMax - VMin);
+ const ptol = span * 1e-8;
+ const outer = oc.BRepTools.OuterWire(face);
+ const loops: { outer: boolean; edges: LoopEdge[] }[] = [];
+ const wires = subShapesOriented(face, oc.TopAbs_ShapeEnum.TopAbs_WIRE);
+ for (const w of wires) {
+ const edges: LoopEdge[] = [];
+ for (const e of subShapesOriented(w, oc.TopAbs_ShapeEnum.TopAbs_EDGE)) {
+ const rev = isReversed(e);
+ const pc = edgePcurve(e, face, m, ptol);
+ const model = oc.BRep_Tool.Degenerated(e) ? null : edgeCurve(e, tol);
+ edges.push(rev
+ ? { model: model && reverseEdge(model), param: reverseCurve(pc.c), a: pc.b, b: pc.a }
+ : { model, param: pc.c, a: pc.a, b: pc.b });
+ e.delete();
+ }
+ loops.push({ outer: !outer.IsNull() && w.IsSame(outer), edges: chain(edges, span * 1e-6) });
+ w.delete();
+ }
+ outer.delete();
+ loops.sort((x, y) => Number(y.outer) - Number(x.outer));
+ let s = m.s;
+ let fix = (c: NurbsCurve) => c;
+ // A reversed face's normal is the surface's turned over: reverse U so the
+ // written surface faces outwards (mirroring the loops back to counterclockwise).
+ if (isReversed(face)) {
+ const [a, b] = surfaceDomain(s);
+ s = reverseSurfaceU(s);
+ fix = (c) => mapCurve(c, (p) => [a + b - p[0], p[1]]);
+ }
+ const out: IgesLoop[] = loops.filter((l) => l.edges.length).map((l) => ({
+ model: l.edges.flatMap((e) => (e.model ? [e.model] : [])),
+ param: l.edges.map((e) => fix(e.param)),
+ }));
+ return { surface: s, loops: out };
+}
+
+/** Sub-shapes with their orientation composed from the parent (seam edges appear twice). */
+function subShapesOriented(shape: any, kind: any): any[] {
+ const oc = getOc();
+ const out: any[] = [];
+ const ex = new oc.TopExp_Explorer(shape, kind, oc.TopAbs_ShapeEnum.TopAbs_SHAPE);
+ const cast = kind === oc.TopAbs_ShapeEnum.TopAbs_WIRE ? oc.TopoDS.Wire : oc.TopoDS.Edge;
+ try {
+ for (; ex.More(); ex.Next()) out.push(cast(ex.Current()));
+ } finally {
+ ex.delete();
+ }
+ return out;
+}
+
+function sizeOf(shapes: Sh[]): number {
+ let d = 0;
+ for (const s of shapes) {
+ const b = bbox(s);
+ if (b) d = Math.max(d, distance(b.min, b.max));
+ }
+ return d || 1;
+}
+
+function maxTolerance(shape: Sh): number {
+ const oc = getOc();
+ let t = 0;
+ for (const v of subShapes(shape, 'vertex')) t = Math.max(t, oc.BRep_Tool.Tolerance(v.wrapped));
+ return t;
+}
+
+export interface IgesExportItem { shape: Sh; name?: string; color?: string }
+
+const hexColor = (c?: string): [number, number, number] | undefined => {
+ const m = /^#?([0-9a-f]{6})$/i.exec(c ?? '');
+ if (!m) return undefined;
+ const n = parseInt(m[1], 16);
+ return [(n >> 16) / 255, ((n >> 8) & 255) / 255, (n & 255) / 255];
+};
+
+/** An IGES file of the given bodies (millimetres). Assemblies put each body in a named group. */
+export function exportIges(items: IgesExportItem[], name: string, opts: { groups?: boolean; date?: Date } = {}): Uint8Array {
+ if (!items.length) throw new FeatureError('There is no geometry to export');
+ const size = sizeOf(items.map((i) => i.shape));
+ const tol = Math.max(1e-7, size * 1e-8);
+ let resolution = 1e-6;
+ const bodies: IgesBody[] = items.map((it) => {
+ resolution = Math.max(resolution, maxTolerance(it.shape));
+ const faces = subShapes(it.shape, 'face').map((f) => convertFace(f.wrapped, tol));
+ return { name: it.name, color: hexColor(it.color), faces };
+ });
+ const safe = name.trim() || 'Part';
+ const text = writeIges(bodies, { name: safe, fileName: `${safe}.igs`, resolution: Math.min(resolution, 0.01), groups: opts.groups, date: opts.date });
+ return new TextEncoder().encode(text);
+}
+
+
+// ---------- import ----------
+
+export interface IgesImport {
+ /** The model as STEP text, for the regular import path. */
+ step: string;
+ solids: number;
+ /** Surface bodies (open shells) that could not be closed into solids. */
+ sheets: number;
+ faces: number;
+ /** Faces that could not be read. */
+ skipped: number;
+ problems: string[];
+}
+
+/** Sews faces into shells at a tolerance; the shells, and how many edges were left unmatched. */
+function sew(faces: Sh[], tol: number): { shape: Sh; free: number } {
+ const oc = getOc();
+ const sewing = new oc.BRepBuilderAPI_Sewing(tol, true, true, true, false);
+ const progress = new oc.Message_ProgressRange();
+ try {
+ for (const f of faces) sewing.Add(f.wrapped);
+ sewing.Perform(progress);
+ return { shape: wrap(sewing.SewedShape()), free: sewing.NbFreeEdges() };
+ } finally {
+ sewing.delete();
+ progress.delete();
+ }
+}
+
+function faceArea(face: Sh): number {
+ const oc = getOc();
+ const p = new oc.GProp_GProps();
+ try {
+ oc.BRepGProp.SurfaceProperties(face.wrapped, p, false, false);
+ return Math.abs(p.Mass());
+ } finally {
+ p.delete();
+ }
+}
+
+/** Shells of a sewn result (a lone face becomes a shell of its own). */
+function shellsOf(shape: Sh): Sh[] {
+ const oc = getOc();
+ const shells = subShapes(shape, 'shell');
+ const loose = subShapes(shape, 'face', 'shell');
+ for (const f of loose) {
+ const b = new oc.TopoDS_Builder();
+ const sh = new oc.TopoDS_Shell();
+ b.MakeShell(sh);
+ b.Add(sh, f.wrapped);
+ b.delete();
+ shells.push(wrap(sh));
+ }
+ return shells;
+}
+
+/** A closed shell as a solid facing outwards, or null when the shell is open. */
+function solidOf(shell: Sh): Sh | null {
+ const oc = getOc();
+ if (!oc.BRep_Tool.IsClosed(shell.wrapped)) return null;
+ const fix = new oc.ShapeFix_Solid();
+ try {
+ const solid = wrap(fix.SolidFromShell(oc.TopoDS.Shell(shell.wrapped)));
+ return volumeOf(solid) > 0 ? solid : null;
+ } catch {
+ return null;
+ } finally {
+ fix.delete();
+ }
+}
+
+/**
+ * Closed shells as solids: a shell inside another one is a hollow in it (its
+ * faces were written as loose surfaces, with nothing saying which side is
+ * material), and a shell inside a hollow is a solid again.
+ */
+function nestSolids(solids: Sh[], tol: number): Sh[] {
+ if (solids.length < 2) return solids;
+ const items = solids.map((s) => ({ s, v: volumeOf(s), box: bbox(s) })).sort((a, b) => b.v - a.v);
+ const inside = (a: typeof items[number]['box'], b: typeof items[number]['box']) =>
+ !!a && !!b && a.min.every((x, k) => x >= b.min[k] - 1e-9) && a.max.every((x, k) => x <= b.max[k] + 1e-9);
+ const parent = items.map(() => -1);
+ for (let i = 1; i < items.length; i++) {
+ // The smallest larger shell around it.
+ for (let j = i - 1; j >= 0; j--) {
+ if (!inside(items[i].box, items[j].box)) continue;
+ let within = enclosed(items[i].s, items[j].s, tol);
+ if (within === null) {
+ let shared = 0;
+ try { shared = volumeOf(common(items[j].s, items[i].s)); } catch { shared = 0; }
+ within = shared > items[i].v * 0.999;
+ }
+ if (within) { parent[i] = j; break; }
+ }
+ }
+ const depth = (i: number): number => (parent[i] < 0 ? 0 : 1 + depth(parent[i]));
+ const out: Sh[] = [];
+ items.forEach((it, i) => {
+ if (depth(i) % 2) return;
+ const holes = items.filter((_, k) => parent[k] === i);
+ out.push(holes.length ? hollowed(it.s, it.v, holes) : it.s);
+ });
+ return out;
+}
+
+/** Whether a point (a vertex) is inside or on a solid: the distance between them is zero then. */
+function holds(solid: Sh, point: Sh, tol: number): boolean {
+ const oc = getOc();
+ const ext = new oc.BRepExtrema_DistShapeShape();
+ const progress = new oc.Message_ProgressRange();
+ try {
+ ext.LoadS1(solid.wrapped);
+ ext.LoadS2(point.wrapped);
+ ext.Perform(progress);
+ return ext.IsDone() && ext.Value() <= tol;
+ } finally {
+ ext.delete();
+ progress.delete();
+ }
+}
+
+/**
+ * Whether one closed shell lies inside another, from some of its vertices
+ * (closed shells of one model do not cross); null when it has none.
+ */
+function enclosed(inner: Sh, outer: Sh, tol: number): boolean | null {
+ const vs = subShapes(inner, 'vertex');
+ if (!vs.length) return null;
+ const n = Math.min(vs.length, 8);
+ for (let k = 0; k < n; k++) if (!holds(outer, vs[Math.floor((k * vs.length) / n)], tol)) return false;
+ return true;
+}
+
+/**
+ * A solid with hollows: its shell, and each hollow's shell turned inwards (no
+ * boolean, which is slow on spline surfaces and loses accuracy there).
+ */
+function hollowed(solid: Sh, volume: number, holes: { s: Sh; v: number }[]): Sh {
+ const oc = getOc();
+ const want = volume - holes.reduce((s, h) => s + h.v, 0);
+ const mk = new oc.BRepBuilderAPI_MakeSolid(oc.TopoDS.Solid(solid.wrapped));
+ try {
+ for (const h of holes) for (const sh of subShapes(h.s, 'shell')) mk.Add(oc.TopoDS.Shell(sh.wrapped.Reversed()));
+ const out = wrap(mk.Solid());
+ if (Math.abs(volumeOf(out) - want) <= 1e-6 * volume) return out;
+ } catch {
+ // Cut them out below.
+ } finally {
+ mk.delete();
+ }
+ let body = solid;
+ for (const h of holes) body = cut(body, h.s);
+ return body;
+}
+
+/**
+ * Reads an IGES file into STEP text: its faces are read by the kernel's STEP
+ * reader (which repairs small gaps), sewn into shells, and closed shells
+ * become solids.
+ */
+export async function importIges(text: string, name: string): Promise {
+ let model;
+ try {
+ model = convertIges(parseIges(text));
+ } catch (e) {
+ if (e instanceof IgesError) throw new FeatureError(e.message);
+ throw e;
+ }
+ const size = model.size > 0 ? model.size : 1;
+ // Sew at the file's resolution where it gives a sensible one, else 0.1 micrometre; a gap of
+ // up to 0.1 mm (and 0.1% of the model) is closed if the finer tolerances leave open edges.
+ // Neither is more than 0.1% of the model: a small part's file can give a resolution
+ // close to the size of its smaller edges, which would then be merged away.
+ const coarse = Math.min(0.1, size * 1e-3);
+ const fine = Math.min(Math.max(model.resolution, 1e-4), 0.01, coarse);
+ const read = await readStep(modelToStep(model, name, fine));
+ const solids = subShapes(read, 'solid');
+ // Faces with no area (slivers some modellers leave where blends meet) bound
+ // nothing: kept, they would come in as surfaces or specks of solid of their own.
+ const loose = subShapes(read, 'face', 'solid').filter((f) => faceArea(f) > fine * fine);
+ const parts: Sh[] = [...solids];
+ let sheets = 0;
+ if (loose.length) {
+ let best = sew(loose, fine);
+ let tried = fine;
+ for (let t = fine * 10; best.free > 0 && t <= coarse * 1.0001; t *= 10) {
+ const next = sew(loose, t);
+ tried = t;
+ if (next.free < best.free) best = next;
+ }
+ // The coarsest tolerance, unless the steps above ended on it.
+ if (best.free > 0 && coarse > tried * 1.0001) {
+ const next = sew(loose, coarse);
+ if (next.free < best.free) best = next;
+ }
+ const closed: Sh[] = [];
+ for (const sh of shellsOf(best.shape)) {
+ const solid = solidOf(sh);
+ if (solid) closed.push(solid);
+ else { parts.push(sh); sheets++; }
+ }
+ parts.unshift(...nestSolids(closed, fine));
+ }
+ if (!parts.length) throw new FeatureError('The IGES file contains no geometry that could be read');
+ const result = parts.length === 1 ? parts[0] : compound(parts);
+ const step = new TextDecoder().decode(writeStepShape(result, name));
+ return {
+ step,
+ solids: parts.length - sheets,
+ sheets,
+ faces: subShapes(result, 'face').length,
+ skipped: model.skipped,
+ problems: model.problems,
+ };
+}
diff --git a/src/parametric/src/kernel/protocol.ts b/src/parametric/src/kernel/protocol.ts
index d6f25a6837..a244d3311c 100644
--- a/src/parametric/src/kernel/protocol.ts
+++ b/src/parametric/src/kernel/protocol.ts
@@ -217,11 +217,13 @@ export type WorkerRequest =
| { id: number; type: 'weldVolumes' }
| { id: number; type: 'project'; views: ProjectionRequest[] }
| { id: number; type: 'measure'; a: MeasureTarget; b: MeasureTarget }
- | { id: number; type: 'export'; format: 'step' | 'stl' | 'brep'; quality: number; name?: string }
+ | { id: number; type: 'export'; format: 'step' | 'iges' | 'stl' | 'brep'; quality: number; name?: string }
| { id: number; type: 'checkImport'; format: 'step'; text: string }
/** The solid's boundary for the stress analysis mesher, at a chordal tolerance (mm). */
| { id: number; type: 'feaSurface'; tolerance: number }
| { id: number; type: 'convertSolidWorks'; data: Uint8Array; name: string }
+ /** Reads an IGES file into STEP text for the regular import path. */
+ | { id: number; type: 'convertIges'; text: string; name: string }
/** Assemblies: building their parts and the placed components (see assembly.ts). */
| { id: number; type: 'asm'; req: AsmRequest }
/** Development builds only: fail on purpose to test recovery. */
diff --git a/src/parametric/src/kernel/stepfile.ts b/src/parametric/src/kernel/stepfile.ts
new file mode 100644
index 0000000000..e73c6979ff
--- /dev/null
+++ b/src/parametric/src/kernel/stepfile.ts
@@ -0,0 +1,74 @@
+// Reading and writing STEP text with the geometry kernel's translators.
+
+import { FeatureError } from './errors';
+import { type Sh, getOc, isEmpty, wrap } from './occ';
+
+/** A STEP file of a shape (millimetres); its product is named `name`. */
+export function writeStepShape(shape: Sh, name?: string): Uint8Array {
+ const oc = getOc();
+ const writer = new oc.STEPControl_Writer();
+ oc.Interface_Static.SetIVal('write.step.schema', 5);
+ oc.Interface_Static.SetCVal('write.step.unit', 'MM');
+ const progress = new oc.Message_ProgressRange();
+ try {
+ writer.Transfer(shape.wrapped, oc.STEPControl_StepModelType.STEPControl_AsIs, true, progress);
+ const done = writer.Write('/export.step');
+ if (done !== oc.IFSelect_ReturnStatus.IFSelect_RetDone) throw new FeatureError('STEP export failed');
+ const data: Uint8Array = oc.FS.readFile('/export.step');
+ oc.FS.unlink('/export.step');
+ return name ? namedStep(data, name) : data;
+ } finally {
+ writer.delete();
+ progress.delete();
+ }
+}
+
+/**
+ * The writer names the product (and the file) after itself ("Open CASCADE
+ * STEP translator 8.0 1"), which other CAD systems then show as the part's
+ * name. Only the header and the product entity carry these strings.
+ */
+function namedStep(data: Uint8Array, name: string): Uint8Array {
+ const text = new TextDecoder().decode(data);
+ const value = stepString(name);
+ const named = text
+ .replace(/'Open CASCADE STEP translator [^']*'/g, () => value)
+ .replace(/FILE_NAME\('Open CASCADE Shape Model',('[^']*'),\('Author'\)/, (_m, time: string) => `FILE_NAME(${value},${time},('')`);
+ return new TextEncoder().encode(named);
+}
+
+/** A STEP string literal: quotes and backslashes doubled, other than printable ASCII as \X2\ (UTF-16) hex. */
+export function stepString(s: string): string {
+ let out = '';
+ let wide = '';
+ const flush = () => { if (wide) { out += `\\X2\\${wide}\\X0\\`; wide = ''; } };
+ for (let i = 0; i < s.length; i++) {
+ const c = s.charCodeAt(i);
+ if (c >= 0x20 && c <= 0x7e) {
+ flush();
+ out += c === 0x27 ? "''" : c === 0x5c ? '\\\\' : s[i];
+ } else if (c >= 0x20) wide += c.toString(16).toUpperCase().padStart(4, '0');
+ }
+ flush();
+ return `'${out}'`;
+}
+
+/** The shape in STEP text. */
+export async function readStep(text: string): Promise {
+ const oc = getOc();
+ const name = `/import-${Date.now()}.step`;
+ oc.FS.writeFile(name, text);
+ const reader = new oc.STEPControl_Reader();
+ const progress = new oc.Message_ProgressRange();
+ try {
+ if (reader.ReadFile(name) !== oc.IFSelect_ReturnStatus.IFSelect_RetDone) throw new FeatureError('The STEP file could not be read');
+ reader.TransferRoots(progress);
+ const shape = wrap(reader.OneShape());
+ if (isEmpty(shape)) throw new FeatureError('The STEP file contains no geometry');
+ return shape;
+ } finally {
+ reader.delete();
+ progress.delete();
+ try { oc.FS.unlink(name); } catch { /* already removed */ }
+ }
+}
diff --git a/src/parametric/src/kernel/worker.ts b/src/parametric/src/kernel/worker.ts
index d3d6136f10..9844cf987a 100644
--- a/src/parametric/src/kernel/worker.ts
+++ b/src/parametric/src/kernel/worker.ts
@@ -6,6 +6,7 @@ import init from 'replicad-opencascadejs';
import wasmUrl from 'replicad-opencascadejs/wasm?url';
import { solidWorksToStep } from '../formats/sldprt';
import { ModelBuilder, checkStep, errorText, isFatal } from './build';
+import { importIges } from './iges';
import { AssemblyBuilder, asmTransfers } from './assembly';
import { setOc } from './occ';
import type { BuildResult, MeshData, WorkerRequest, WorkerResponse } from './protocol';
@@ -115,12 +116,12 @@ async function handle(ev: MessageEvent) {
return;
case 'export': {
if (assembly.active && msg.format !== 'brep') {
- const data = msg.format === 'step' ? await assembly.exportStep() : assembly.exportStl(msg.quality);
+ const data = msg.format === 'step' ? await assembly.exportStep() : msg.format === 'iges' ? assembly.exportIges(msg.name) : assembly.exportStl(msg.quality);
reply({ id: msg.id, ok: true, result: data }, [data.buffer as ArrayBuffer]);
return;
}
if (msg.format === 'brep') { reply({ id: msg.id, ok: true, result: builder.exportBrep() }); return; }
- const data = msg.format === 'step' ? builder.exportStep(msg.name) : builder.exportStl(msg.quality);
+ const data = msg.format === 'step' ? builder.exportStep(msg.name) : msg.format === 'iges' ? builder.exportIges(msg.name) : builder.exportStl(msg.quality);
reply({ id: msg.id, ok: true, result: data }, [data.buffer as ArrayBuffer]);
return;
}
@@ -148,6 +149,9 @@ async function handle(ev: MessageEvent) {
case 'convertSolidWorks':
reply({ id: msg.id, ok: true, result: await solidWorksToStep(msg.data, msg.name) });
return;
+ case 'convertIges':
+ reply({ id: msg.id, ok: true, result: await importIges(msg.text, msg.name) });
+ return;
case 'debugFail':
if (!import.meta.env.DEV) throw new Error('Not available');
if (msg.mode === 'hang') for (;;) { /* never answers */ }
diff --git a/src/parametric/src/platform/files.ts b/src/parametric/src/platform/files.ts
index eaa12cf4b1..8ff8110c4a 100644
--- a/src/parametric/src/platform/files.ts
+++ b/src/parametric/src/platform/files.ts
@@ -9,8 +9,9 @@ import { cloudAvailable, isMissing, puter, toMs } from './puter';
export const EXT = '.parametric';
/** Files that open as an imported body rather than as a part document. */
-export const IMPORT_EXTS = ['.step', '.stp', '.sldprt'];
+export const IMPORT_EXTS = ['.step', '.stp', '.igs', '.iges', '.sldprt'];
export const isStepFile = (name: string) => /\.(step|stp)$/i.test(name);
+export const isIgesFile = (name: string) => /\.(igs|iges)$/i.test(name);
export const isSolidWorksFile = (name: string) => /\.(sldprt|sldasm|slddrw)$/i.test(name);
export const CLOUD_DIR = 'Parts';
/** A part file's name, whatever the case of its extension. */
@@ -544,7 +545,7 @@ export function forgetRecent(location: Location) {
export const locationLabel = (loc?: Location | null) =>
!loc ? 'Not saved' : loc.type === 'cloud' ? loc.path.replace(/^.*\/AppData\/[^/]+\//, '') : 'This browser';
-/** Opens a file chosen from Puter storage: a part, or a STEP or SolidWorks file to import. */
+/** Opens a file chosen from Puter storage: a part, or a STEP, IGES or SolidWorks file to import. */
export async function pickCloudFile(): Promise<{ blob: Blob; fileName: string; location: Location; name: string; version: FileVersion | null } | null> {
const p = puter();
if (!p?.ui?.showOpenFilePicker) return null;
@@ -574,6 +575,7 @@ export function acceptList(exts: string[]): string {
for (const ext of exts) {
if (ext === EXT || ext === '.json') types.add('application/json');
if (isStepFile(`x${ext}`)) { types.add('model/step'); types.add('application/step'); }
+ if (isIgesFile(`x${ext}`)) { types.add('model/iges'); types.add('application/iges'); }
}
// iPhone and iPad pickers grey out files of types they do not know
// (.parametric, .sldprt): there, any file can be picked and is checked after.
diff --git a/src/parametric/tests/e2e/assembly.spec.ts b/src/parametric/tests/e2e/assembly.spec.ts
index c0ae893f88..75fc1c2e99 100644
--- a/src/parametric/tests/e2e/assembly.spec.ts
+++ b/src/parametric/tests/e2e/assembly.spec.ts
@@ -1,5 +1,6 @@
import { type Page, expect, test } from '@playwright/test';
import { chooseTheme, openApp } from './helpers';
+import { IgesWriter } from '../../src/formats/iges/write';
type A = import('../../src/app/app').App;
@@ -576,6 +577,30 @@ test('Insert Components refuses the assembly itself, another assembly and a file
expect(errors).toEqual([]);
});
+test('Insert Components reads an IGES file, saying when its surfaces do not close into a solid', async ({ page }) => {
+ const errors = await openApp(page);
+ await page.getByRole('button', { name: /New part/ }).click();
+ await page.waitForFunction(() => (window as unknown as { __parametric?: A }).__parametric?.kernelReady);
+ await makePart(page, 'Block', BLOCK);
+ await page.evaluate(() => { void (window as unknown as { __parametric: A }).__parametric.commands.run('newAssembly'); });
+ await insert(page, 'Block');
+ // One square surface: an open sheet.
+ const w = new IgesWriter();
+ const srf = w.add(128, [1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 10, 0, 0, 0, 10, 0, 10, 10, 0, 0, 1, 0, 1], { status: '00010000' });
+ const corners = [[0, 0, 0], [10, 0, 0], [10, 10, 0], [0, 10, 0]];
+ const sides = corners.map((p, i) => w.add(110, [...p, ...corners[(i + 1) % 4]], { status: '00010000' }));
+ w.add(144, [srf, 1, 0, w.add(142, [1, srf, 0, w.add(102, [4, ...sides], { status: '00010000' }), 2], { status: '00010000' })]);
+ const iges = w.toString({ name: 'Sheet', fileName: 'sheet.igs', resolution: 1e-6 });
+ void page.evaluate(() => { (window as unknown as { __parametric: A }).__parametric.commands.run('insertComponent'); });
+ const dlg = page.getByRole('dialog', { name: 'Insert Components' });
+ const chooser = page.waitForEvent('filechooser');
+ await dlg.getByRole('button', { name: 'From device...' }).click();
+ await (await chooser).setFiles({ name: 'sheet.igs', mimeType: 'model/iges', buffer: (globalThis as unknown as { Buffer: { from(s: string): never } }).Buffer.from(iges) });
+ await expect(page.getByRole('region', { name: 'Notifications' })).toContainText('The surfaces of sheet.igs do not close into a solid, so they are imported as surfaces.');
+ await expect(page.getByRole('tree', { name: 'Assembly design tree' }).getByRole('treeitem', { name: /sheet<1>/ })).toBeVisible();
+ expect(errors).toEqual([]);
+});
+
test('every assembly operation undoes and redoes, also when the keys are pressed in quick succession', async ({ page }) => {
const errors = await openApp(page);
await page.getByRole('button', { name: /New part/ }).click();
diff --git a/src/parametric/tests/e2e/exports.spec.ts b/src/parametric/tests/e2e/exports.spec.ts
index 41cabb2ac6..da2e551701 100644
--- a/src/parametric/tests/e2e/exports.spec.ts
+++ b/src/parametric/tests/e2e/exports.spec.ts
@@ -1,11 +1,14 @@
import { expect, test } from '@playwright/test';
import { openApp, waitForFeature } from './helpers';
-for (const format of ['step', 'stl'] as const) for (const stage of ['rebuild', 'export'] as const) test(`${format} export waiting for ${stage} is cancelled when another part opens`, async ({ page }) => {
+const COMMAND = { step: 'exportStep', iges: 'exportIges', stl: 'exportStl' } as const;
+const EXTENSION = { step: 'step', iges: 'igs', stl: 'stl' } as const;
+
+for (const format of ['step', 'iges', 'stl'] as const) for (const stage of ['rebuild', 'export'] as const) test(`${format} export waiting for ${stage} is cancelled when another part opens`, async ({ page }) => {
const errors = await openApp(page);
await page.getByRole('button', { name: /Mounting Bracket/ }).click();
await waitForFeature(page, 'Fillet1');
- await page.evaluate(async ({ format, stage }) => {
+ await page.evaluate(async ({ command, stage }) => {
type W = { __parametric: import('../../src/app/app').App; started: boolean; releaseExport: () => void; pendingExport: Promise; downloads: string[] };
const w = window as unknown as W, app = w.__parametric;
await app.whenBuilt();
@@ -21,8 +24,8 @@ for (const format of ['step', 'stl'] as const) for (const stage of ['rebuild', '
const exportFile = app.kernel.exportFile.bind(app.kernel);
app.kernel.exportFile = async (...args) => { const data = await exportFile(...args); w.started = true; await gate; return data; };
}
- w.pendingExport = Promise.resolve(app.commands.get(format === 'step' ? 'exportStep' : 'exportStl')!.run());
- }, { format, stage });
+ w.pendingExport = Promise.resolve(app.commands.get(command)!.run());
+ }, { command: COMMAND[format], stage });
await page.waitForFunction(() => (window as unknown as { started: boolean }).started);
const downloads = await page.evaluate(async () => {
type W = { __parametric: import('../../src/app/app').App; releaseExport: () => void; pendingExport: Promise; downloads: string[] };
@@ -39,27 +42,27 @@ for (const format of ['step', 'stl'] as const) for (const stage of ['rebuild', '
});
expect(downloads).toEqual([]);
const downloaded = page.waitForEvent('download');
- await page.evaluate((format) => (window as unknown as { __parametric: import('../../src/app/app').App }).__parametric.commands.run(format === 'step' ? 'exportStep' : 'exportStl'), format);
- expect((await downloaded).suggestedFilename()).toBe(`Replacement.${format}`);
+ await page.evaluate((command) => (window as unknown as { __parametric: import('../../src/app/app').App }).__parametric.commands.run(command), COMMAND[format]);
+ expect((await downloaded).suggestedFilename()).toBe(`Replacement.${EXTENSION[format]}`);
expect(errors).toEqual([]);
});
-for (const format of ['step', 'stl'] as const) test(`${format} export while editing a sketch has the whole part, not the rolled-back one`, async ({ page }) => {
+for (const format of ['step', 'iges', 'stl'] as const) test(`${format} export while editing a sketch has the whole part, not the rolled-back one`, async ({ page }) => {
const errors = await openApp(page);
await page.getByRole('button', { name: /Mounting Bracket/ }).click();
await waitForFeature(page, 'Fillet1');
- const exported = () => page.evaluate(async (format) => {
+ const exported = () => page.evaluate(async (command) => {
const app = (window as unknown as { __parametric: import('../../src/app/app').App }).__parametric;
const click = HTMLAnchorElement.prototype.click;
let url = '';
HTMLAnchorElement.prototype.click = function () { url = this.href; };
try {
- await app.commands.get(format === 'step' ? 'exportStep' : 'exportStl')!.run();
+ await app.commands.get(command)!.run();
} finally {
HTMLAnchorElement.prototype.click = click;
}
return url ? (await (await fetch(url)).arrayBuffer()).byteLength : 0;
- }, format);
+ }, COMMAND[format]);
const whole = await exported();
expect(whole).toBeGreaterThan(0);
// Sketch2 places the holes: editing it rolls the model back to before them.
diff --git a/src/parametric/tests/e2e/files.spec.ts b/src/parametric/tests/e2e/files.spec.ts
index e14fd8b2cb..5316f20ebb 100644
--- a/src/parametric/tests/e2e/files.spec.ts
+++ b/src/parametric/tests/e2e/files.spec.ts
@@ -1280,7 +1280,7 @@ for (const change of ['edits', 'a new part'] as const) test(`saving before New k
expect(errors).toEqual([]);
});
-for (const command of ['importStep', 'openDevice'] as const) for (const stage of ['convertSolidWorks', 'checkImport'] as const) test(`a ${command} finishing ${stage} after New does not modify the new part`, async ({ page }) => {
+for (const command of ['importStep', 'openDevice'] as const) for (const stage of ['convertSolidWorks', 'convertIges', 'checkImport'] as const) test(`a ${command} finishing ${stage} after New does not modify the new part`, async ({ page }) => {
const errors = await openApp(page);
await page.getByRole('button', { name: /New part/ }).click();
await app(page);
@@ -1291,6 +1291,9 @@ for (const command of ['importStep', 'openDevice'] as const) for (const stage of
if (stage === 'convertSolidWorks') {
const convert = w.__parametric.kernel.convertSolidWorks.bind(w.__parametric.kernel);
w.__parametric.kernel.convertSolidWorks = async (...args) => { const result = await convert(...args); w.importStarted = true; await gate; return result; };
+ } else if (stage === 'convertIges') {
+ const convert = w.__parametric.kernel.convertIges.bind(w.__parametric.kernel);
+ w.__parametric.kernel.convertIges = async (...args) => { const result = await convert(...args); w.importStarted = true; await gate; return result; };
} else {
const check = w.__parametric.kernel.checkImport.bind(w.__parametric.kernel);
w.__parametric.kernel.checkImport = async (...args) => { const result = await check(...args); w.importStarted = true; await gate; return result; };
@@ -1301,7 +1304,7 @@ for (const command of ['importStep', 'openDevice'] as const) for (const stage of
const w = window as unknown as { __parametric: import('../../src/app/app').App; pendingImport: Promise };
w.pendingImport = Promise.resolve(w.__parametric.commands.get(command)!.run());
}, command);
- const path = decodeURIComponent(new URL('../fixtures/sldprt/cube-hole-sw2022.sldprt', import.meta.url).pathname);
+ const path = decodeURIComponent(new URL(stage === 'convertIges' ? '../fixtures/iges/plate-brep.igs' : '../fixtures/sldprt/cube-hole-sw2022.sldprt', import.meta.url).pathname);
await (await chooser).setFiles(path);
await page.waitForFunction(() => (window as unknown as { importStarted: boolean }).importStarted);
await page.evaluate(async () => { await (window as unknown as { __parametric: import('../../src/app/app').App }).__parametric.commands.get('new')!.run(); });
@@ -2154,7 +2157,7 @@ test('device file pickers name the media types of the files they open, and accep
const chooser = page.waitForEvent('filechooser');
await page.evaluate((c) => { void (window as unknown as { __parametric: AppHandle }).__parametric.commands.run(c); }, command);
const accept = (await (await chooser).element().getAttribute('accept'))!.split(',');
- expect(accept).toEqual(expect.arrayContaining(['.step', '.stp', '.sldprt', 'model/step']));
+ expect(accept).toEqual(expect.arrayContaining(['.step', '.stp', '.igs', '.iges', '.sldprt', 'model/step', 'model/iges']));
if (command === 'openDevice') expect(accept).toEqual(expect.arrayContaining(['.parametric', 'application/json']));
expect(accept.includes('application/octet-stream')).toBe(ios);
}
diff --git a/src/parametric/tests/e2e/imports.spec.ts b/src/parametric/tests/e2e/imports.spec.ts
index 30bf4e08dd..072ee2fddf 100644
--- a/src/parametric/tests/e2e/imports.spec.ts
+++ b/src/parametric/tests/e2e/imports.spec.ts
@@ -111,7 +111,7 @@ test('a body imported while a sketch is open stays when the sketch changes are d
expect(errors).toEqual([]);
});
-test('Import refuses a file that is not a STEP or SolidWorks model, saying what it takes', async ({ page }) => {
+test('Import refuses a file that is not a STEP, IGES or SolidWorks model, saying what it takes', async ({ page }) => {
type A = import('../../src/app/app').App;
const errors = await openApp(page);
await page.getByRole('button', { name: /New part/ }).click();
@@ -120,7 +120,7 @@ test('Import refuses a file that is not a STEP or SolidWorks model, saying what
await page.evaluate(() => (window as unknown as { __parametric: A }).__parametric.commands.run('importStep'));
const text = JSON.stringify({ format: 'parametric-part', version: 1, name: 'Other', units: 'MMGS', features: [] });
await (await chooser).setFiles({ name: 'Other.parametric', mimeType: 'application/json', buffer: (globalThis as unknown as { Buffer: { from(s: string): never } }).Buffer.from(text) });
- await expect(page.getByRole('region', { name: 'Notifications' })).toContainText('Other.parametric is not a STEP file (.step, .stp) or a SolidWorks part (.sldprt). To work on a part file, open it with Open.');
+ await expect(page.getByRole('region', { name: 'Notifications' })).toContainText('Other.parametric is not a STEP file (.step, .stp), an IGES file (.igs, .iges) or a SolidWorks part (.sldprt). To work on a part file, open it with Open.');
expect(await page.evaluate(() => (window as unknown as { __parametric: A }).__parametric.store.doc.features.length)).toBe(0);
expect(errors).toEqual([]);
});
@@ -133,6 +133,68 @@ test('Open from device refuses a file Parametric does not open, saying which fil
const chooser = page.waitForEvent('filechooser');
await page.evaluate(() => (window as unknown as { __parametric: A }).__parametric.commands.run('openDevice'));
await (await chooser).setFiles({ name: 'bracket.stl', mimeType: 'model/stl', buffer: (globalThis as unknown as { Buffer: { from(s: string): never } }).Buffer.from('solid x\nendsolid x\n') });
- await expect(page.getByRole('region', { name: 'Notifications' })).toContainText('bracket.stl is not a file Parametric opens. Choose a part (.parametric), a STEP file (.step, .stp) or a SolidWorks part (.sldprt).');
+ await expect(page.getByRole('region', { name: 'Notifications' })).toContainText('bracket.stl is not a file Parametric opens. Choose a part (.parametric), a STEP file (.step, .stp), an IGES file (.igs, .iges) or a SolidWorks part (.sldprt).');
+ expect(errors).toEqual([]);
+});
+
+test('an IGES export opened again makes a new part with the same solid', async ({ page }) => {
+ type A = import('../../src/app/app').App;
+ const errors = await openApp(page);
+ await page.getByRole('button', { name: /Mounting Bracket/ }).click();
+ await expect(page.getByRole('treeitem', { name: 'Fillet1' })).toBeVisible();
+ const { iges, volume } = await page.evaluate(async () => {
+ const app = (window as unknown as { __parametric: A }).__parametric;
+ await app.whenBuilt();
+ const iges = new TextDecoder().decode(await app.kernel.exportFile('iges', 1, app.store.doc.name));
+ return { iges, volume: (await app.kernel.massProperties())!.volume };
+ });
+ expect(iges).toMatch(/^.{72}S0000001$/m);
+ expect(iges).toContain('16HMounting Bracket');
+ const chooser = page.waitForEvent('filechooser');
+ await page.evaluate(() => (window as unknown as { __parametric: A }).__parametric.commands.run('openDevice'));
+ await (await chooser).setFiles({ name: 'bracket.IGS', mimeType: 'model/iges', buffer: (globalThis as unknown as { Buffer: { from(s: string): never } }).Buffer.from(iges) });
+ await expect(page).toHaveTitle('* bracket - Parametric');
+ await expect(page.getByRole('treeitem', { name: 'Imported1' })).toBeVisible();
+ const reopened = await page.evaluate(async () => {
+ const app = (window as unknown as { __parametric: A }).__parametric;
+ await app.whenBuilt();
+ const f = app.store.doc.features[0];
+ return { volume: (await app.kernel.massProperties())!.volume, fileName: f.type === 'import' ? f.fileName : '', format: f.type === 'import' ? f.format : '' };
+ });
+ expect(reopened.fileName).toBe('bracket.IGS');
+ expect(reopened.format).toBe('step');
+ expect(reopened.volume).toBeCloseTo(volume, 1);
+ await expect(page.locator('.ti.error')).toHaveCount(0);
+ expect(errors).toEqual([]);
+});
+
+test('Import inserts an IGES model written in inches as a body in millimetres', async ({ page }) => {
+ type A = import('../../src/app/app').App;
+ const errors = await openApp(page);
+ await page.getByRole('button', { name: /New part/ }).click();
+ const chooser = page.waitForEvent('filechooser');
+ await page.evaluate(() => (window as unknown as { __parametric: A }).__parametric.commands.run('importStep'));
+ await (await chooser).setFiles(decodeURIComponent(new URL('../fixtures/iges/plate-faces-inch.igs', import.meta.url).pathname));
+ await expect(page.getByRole('treeitem', { name: 'Imported1' })).toBeVisible();
+ const volume = await page.evaluate(async () => {
+ const app = (window as unknown as { __parametric: A }).__parametric;
+ await app.whenBuilt();
+ return (await app.kernel.massProperties())!.volume;
+ });
+ // A 30 x 20 x 10 plate with a 6 mm hole and one edge rounded at 4 mm.
+ expect(volume).toBeCloseTo(6000 - Math.PI * 9 * 10 - 10 * (16 - 4 * Math.PI), 2);
+ await expect(page.locator('.ti.error')).toHaveCount(0);
+ expect(errors).toEqual([]);
+});
+
+test('an IGES file with no surfaces is refused with the reason, and the part is left alone', async ({ page }) => {
+ type A = import('../../src/app/app').App;
+ const errors = await openApp(page);
+ await page.getByRole('button', { name: /New part/ }).click();
+ const chooser = page.waitForEvent('filechooser');
+ await page.evaluate(() => (window as unknown as { __parametric: A }).__parametric.commands.run('importStep'));
+ await (await chooser).setFiles({ name: 'notes.iges', mimeType: 'model/iges', buffer: (globalThis as unknown as { Buffer: { from(s: string): never } }).Buffer.from('just some text\n') });
+ await expect(page.getByRole('region', { name: 'Notifications' })).toContainText('This is not an IGES file, or it has no entities.');
+ expect(await page.evaluate(() => (window as unknown as { __parametric: A }).__parametric.store.doc.features.length)).toBe(0);
expect(errors).toEqual([]);
});
diff --git a/src/parametric/tests/fixtures/iges/loft-faces.igs b/src/parametric/tests/fixtures/iges/loft-faces.igs
new file mode 100644
index 0000000000..16ceec1d90
--- /dev/null
+++ b/src/parametric/tests/fixtures/iges/loft-faces.igs
@@ -0,0 +1,239 @@
+ S0000001
+,,31HOpen CASCADE IGES processor 7.7,13HFilename.iges, G0000001
+16HOpen CASCADE 7.7,31HOpen CASCADE IGES processor 7.7,32,308,15,308,15,G0000002
+,1.,2,2HMM,1,0.01,15H20261130.111936,1E-07,30.,2Hnj,,11,0, G0000003
+15H20261130.111936,; G0000004
+ 402 1 0 0 0 0 0 000000000D0000001
+ 402 0 0 1 1 0D0000002
+ 144 2 0 0 0 0 0 000020000D0000003
+ 144 0 0 1 0 0D0000004
+ 128 3 0 0 0 0 0 000010000D0000005
+ 128 0 0 24 0 0D0000006
+ 142 27 0 0 0 0 0 000010500D0000007
+ 142 0 0 1 0 0D0000008
+ 102 28 0 0 0 0 0 000010000D0000009
+ 102 0 0 1 0 0D0000010
+ 110 29 0 0 0 0 0 000010000D0000011
+ 110 0 0 1 0 0D0000012
+ 110 30 0 0 0 0 0 000010000D0000013
+ 110 0 0 1 0 0D0000014
+ 110 31 0 0 0 0 0 000010000D0000015
+ 110 0 0 1 0 0D0000016
+ 110 32 0 0 0 0 0 000010000D0000017
+ 110 0 0 1 0 0D0000018
+ 102 33 0 0 0 0 0 000010000D0000019
+ 102 0 0 1 0 0D0000020
+ 126 34 0 0 0 0 0 000010000D0000021
+ 126 0 0 8 0 0D0000022
+ 126 42 0 0 0 0 0 000010000D0000023
+ 126 0 0 3 0 0D0000024
+ 126 45 0 0 0 0 0 000010000D0000025
+ 126 0 0 9 0 0D0000026
+ 126 54 0 0 0 0 0 000010000D0000027
+ 126 0 0 3 0 0D0000028
+ 144 57 0 0 0 0 0 000020000D0000029
+ 144 0 0 1 0 0D0000030
+ 128 58 0 0 0 0 0 000010000D0000031
+ 128 0 0 24 0 0D0000032
+ 142 82 0 0 0 0 0 000010500D0000033
+ 142 0 0 1 0 0D0000034
+ 102 83 0 0 0 0 0 000010000D0000035
+ 102 0 0 1 0 0D0000036
+ 110 84 0 0 0 0 0 000010000D0000037
+ 110 0 0 1 0 0D0000038
+ 110 85 0 0 0 0 0 000010000D0000039
+ 110 0 0 1 0 0D0000040
+ 110 86 0 0 0 0 0 000010000D0000041
+ 110 0 0 1 0 0D0000042
+ 110 87 0 0 0 0 0 000010000D0000043
+ 110 0 0 1 0 0D0000044
+ 102 88 0 0 0 0 0 000010000D0000045
+ 102 0 0 1 0 0D0000046
+ 126 89 0 0 0 0 0 000010000D0000047
+ 126 0 0 9 0 0D0000048
+ 126 98 0 0 0 0 0 000010000D0000049
+ 126 0 0 3 0 0D0000050
+ 126 101 0 0 0 0 0 000010000D0000051
+ 126 0 0 9 0 0D0000052
+ 126 110 0 0 0 0 0 000010000D0000053
+ 126 0 0 3 0 0D0000054
+ 144 113 0 0 0 0 0 000020000D0000055
+ 144 0 0 1 0 0D0000056
+ 108 114 0 0 0 0 0 000010000D0000057
+ 108 0 0 1 0 0D0000058
+ 142 115 0 0 0 0 0 000010500D0000059
+ 142 0 0 1 0 0D0000060
+ 102 116 0 0 0 0 0 000010000D0000061
+ 102 0 0 1 0 0D0000062
+ 126 117 0 0 0 0 0 000010000D0000063
+ 126 0 0 8 0 0D0000064
+ 126 125 0 0 0 0 0 000010000D0000065
+ 126 0 0 9 0 0D0000066
+ 144 134 0 0 0 0 0 000020000D0000067
+ 144 0 0 1 0 0D0000068
+ 108 135 0 0 0 0 0 000010000D0000069
+ 108 0 0 1 0 0D0000070
+ 142 136 0 0 0 0 0 000010500D0000071
+ 142 0 0 1 0 0D0000072
+ 102 137 0 0 0 0 0 000010000D0000073
+ 102 0 0 1 0 0D0000074
+ 126 138 0 0 0 0 0 000010000D0000075
+ 126 0 0 9 0 0D0000076
+ 126 147 0 0 0 0 0 000010000D0000077
+ 126 0 0 9 0 0D0000078
+402,4,3,29,55,67; 0000001P0000001
+144,5,1,0,7; 0000003P0000002
+128,12,2,12,2,0,0,1,0,0,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0., 0000005P0000003
+1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,0.,0.,0.,1.,1.,1.,1.,1., 0000005P0000004
+1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1., 0000005P0000005
+1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,10.,0.,0.,10., 0000005P0000006
+1.308996939,0.,9.813075441,2.61799414,0.,9.439227424, 0000005P0000007
+3.897628325,0.,8.88357873,5.118539774,0.,8.156379476, 0000005P0000008
+6.252371344,0.,7.272778816,7.272778816,0.,6.252371344, 0000005P0000009
+8.156379476,0.,5.118539774,8.88357873,0.,3.897628325, 0000005P0000010
+9.439227424,0.,2.61799414,9.813075441,0.,1.308996939,10.,0., 0000005P0000011
+-4.440892099E-15,10.,0.,3.999867194,-0.499966801,15.00099601, 0000005P0000012
+3.999867194,0.506541629,14.590251337,3.999869677,1.51305026, 0000005P0000013
+14.179506581,3.999874642,2.496981205,13.777975524,3.999882021, 0000005P0000014
+3.435759309,13.394870828,3.999891679,4.307580319,13.039090563, 0000005P0000015
+3.999903414,5.092187748,12.718901171,3.999916967,5.771602257, 0000005P0000016
+12.441639816,3.999932025,6.330757253,12.213455005,3.99994824, 0000005P0000017
+6.758004314,12.039100325,3.999965235,7.045461961,11.92179212, 0000005P0000018
+3.99998262,7.189191209,11.863137845,4.000000004,7.189191209, 0000005P0000019
+11.863137845,6.,1.,30.,6.,1.785398163,30.,5.887845264, 0000005P0000020
+2.570796484,30.,5.663536454,3.338576995,30.,5.330147238, 0000005P0000021
+4.071123864,30.,4.893827686,4.751422806,30.,4.36366729, 0000005P0000022
+5.36366729,30.,3.751422806,5.893827686,30.,3.071123864, 0000005P0000023
+6.330147238,30.,2.338576995,6.663536454,30.,1.570796484, 0000005P0000024
+6.887845264,30.,0.785398163,7.,30.,1.776356839E-15,7.,30.,0.,1., 0000005P0000025
+0.,1.; 0000005P0000026
+142,0,5,9,19,3; 0000007P0000027
+102,4,11,13,15,17; 0000009P0000028
+110,0.,0.,0.,1.,0.,0.; 0000011P0000029
+110,1.,0.,0.,1.,1.,0.; 0000013P0000030
+110,1.,1.,0.,0.,1.,0.; 0000015P0000031
+110,0.,1.,0.,0.,0.,0.; 0000017P0000032
+102,4,21,23,25,27; 0000019P0000033
+126,12,12,1,0,1,0,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,1.,1., 0000021P0000034
+1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1., 0000021P0000035
+1.,1.,1.,10.,0.,0.,10.,1.308996939,0.,9.813075441,2.61799414,0., 0000021P0000036
+9.439227424,3.897628325,0.,8.88357873,5.118539774,0., 0000021P0000037
+8.156379476,6.252371344,0.,7.272778816,7.272778816,0., 0000021P0000038
+6.252371344,8.156379476,0.,5.118539774,8.88357873,0., 0000021P0000039
+3.897628325,9.439227424,0.,2.61799414,9.813075441,0., 0000021P0000040
+1.308996939,10.,0.,-4.440892099E-15,10.,0.,0.,1.,0.,0.,1.; 0000021P0000041
+126,2,2,1,0,1,0,0.,0.,0.,1.,1.,1.,1.,1.,1.,-4.440892099E-15,10., 0000023P0000042
+0.,4.000000004,7.189191209,11.863137845,1.776356839E-15,7.,30., 0000023P0000043
+0.,1.,0.374671959,0.922556136,9.225561365E-02; 0000023P0000044
+126,12,12,1,0,1,0,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,1.,1., 0000025P0000045
+1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1., 0000025P0000046
+1.,1.,1.,1.776356839E-15,7.,30.,0.785398163,7.,30.,1.570796484, 0000025P0000047
+6.887845264,30.,2.338576995,6.663536454,30.,3.071123864, 0000025P0000048
+6.330147238,30.,3.751422806,5.893827686,30.,4.36366729, 0000025P0000049
+5.36366729,30.,4.893827686,4.751422806,30.,5.330147238, 0000025P0000050
+4.071123864,30.,5.663536454,3.338576995,30.,5.887845264, 0000025P0000051
+2.570796484,30.,6.,1.785398163,30.,6.,1.,30.,0.,1.,-0., 0000025P0000052
+-4.730474676E-16,1.; 0000025P0000053
+126,2,2,1,0,1,0,0.,0.,0.,1.,1.,1.,1.,1.,1.,6.,1.,30., 0000027P0000054
+3.999867194,-0.499966801,15.00099601,10.,0.,0.,0.,1., 0000027P0000055
+0.242029947,-0.968119787,6.454131917E-02; 0000027P0000056
+144,31,1,0,33; 0000029P0000057
+128,12,2,12,2,0,0,1,0,0,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1., 0000031P0000058
+2.,2.,2.,2.,2.,2.,2.,2.,2.,2.,2.,2.,2.,0.,0.,0.,1.,1.,1.,1.,1., 0000031P0000059
+1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1., 0000031P0000060
+1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1., 0000031P0000061
+-4.440892099E-15,10.,0.,-3.926990817,10.,0.,-7.853979875, 0000031P0000062
+8.31767886,0.,-10.988210754,4.953059653,0.,-12.536821528, 0000031P0000063
+0.321117032,0.,-11.951833328,-4.747533624,0.,-9.173342424, 0000031P0000064
+-9.173342424,0.,-4.747533624,-11.951833328,0.,0.321117032, 0000031P0000065
+-12.536821528,0.,4.953059653,-10.988210754,0.,8.31767886, 0000031P0000066
+-7.853979875,0.,10.,-3.926990817,0.,10.,-3.552713679E-15,0., 0000031P0000067
+4.000000004,7.189191209,11.863137845,4.000052159,7.189191209, 0000031P0000068
+11.863137845,4.000104313,5.895627902,12.391026357,4.000145939, 0000031P0000069
+3.30851903,13.446796143,4.000166506,-0.253054841,14.90023404, 0000031P0000070
+4.000158737,-4.150420419,16.490704725,4.000121836,-7.553494738, 0000031P0000071
+17.879460753,4.000063056,-9.689920297,18.751311791,3.99999574, 0000031P0000072
+-10.139726967,18.934872791,3.999934223,-8.948975674, 0000031P0000073
+18.448940695,3.999889537,-6.539016027,17.465463499,3.999867194, 0000031P0000074
+-3.51949209,16.233230031,3.999867194,-0.499966801,15.00099601, 0000031P0000075
+1.776356839E-15,7.,30.,-2.35619449,7.,30.,-4.712387925, 0000031P0000076
+5.990607316,30.,-6.592926453,3.971835792,30.,-7.522092917, 0000031P0000077
+1.192670219,30.,-7.171099997,-1.848520174,30.,-5.504005454, 0000031P0000078
+-4.504005454,30.,-2.848520174,-6.171099997,30.,0.192670219, 0000031P0000079
+-6.522092917,30.,2.971835792,-5.592926453,30.,4.990607316, 0000031P0000080
+-3.712387925,30.,6.,-1.35619449,30.,6.,1.,30.,1.,2.,0.,1.; 0000031P0000081
+142,0,31,35,45,3; 0000033P0000082
+102,4,37,39,41,43; 0000035P0000083
+110,1.,0.,0.,2.,0.,0.; 0000037P0000084
+110,2.,0.,0.,2.,1.,0.; 0000039P0000085
+110,2.,1.,0.,1.,1.,0.; 0000041P0000086
+110,1.,1.,0.,1.,0.,0.; 0000043P0000087
+102,4,47,49,51,53; 0000045P0000088
+126,12,12,1,0,1,0,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,2.,2., 0000047P0000089
+2.,2.,2.,2.,2.,2.,2.,2.,2.,2.,2.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1., 0000047P0000090
+1.,1.,1.,-4.440892099E-15,10.,0.,-3.926990817,10.,0., 0000047P0000091
+-7.853979875,8.31767886,0.,-10.988210754,4.953059653,0., 0000047P0000092
+-12.536821528,0.321117032,0.,-11.951833328,-4.747533624,0., 0000047P0000093
+-9.173342424,-9.173342424,0.,-4.747533624,-11.951833328,0., 0000047P0000094
+0.321117032,-12.536821528,0.,4.953059653,-10.988210754,0., 0000047P0000095
+8.31767886,-7.853979875,0.,10.,-3.926990817,0.,10., 0000047P0000096
+-3.552713679E-15,0.,1.,2.,0.,0.,1.; 0000047P0000097
+126,2,2,1,0,1,0,0.,0.,0.,1.,1.,1.,1.,1.,1.,10.,0.,0., 0000049P0000098
+3.999867194,-0.499966801,15.00099601,6.,1.,30.,0.,1., 0000049P0000099
+0.242029947,-0.968119787,6.454131917E-02; 0000049P0000100
+126,12,12,1,0,1,0,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,2.,2., 0000051P0000101
+2.,2.,2.,2.,2.,2.,2.,2.,2.,2.,2.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1., 0000051P0000102
+1.,1.,1.,6.,1.,30.,6.,-1.35619449,30.,4.990607316,-3.712387925, 0000051P0000103
+30.,2.971835792,-5.592926453,30.,0.192670219,-6.522092917,30., 0000051P0000104
+-2.848520174,-6.171099997,30.,-5.504005454,-4.504005454,30., 0000051P0000105
+-7.171099997,-1.848520174,30.,-7.522092917,1.192670219,30., 0000051P0000106
+-6.592926453,3.971835792,30.,-4.712387925,5.990607316,30., 0000051P0000107
+-2.35619449,7.,30.,1.776356839E-15,7.,30.,1.,2., 0000051P0000108
+-9.851494733E-16,-2.627065262E-16,1.; 0000051P0000109
+126,2,2,1,0,1,0,0.,0.,0.,1.,1.,1.,1.,1.,1.,1.776356839E-15,7., 0000053P0000110
+30.,4.000000004,7.189191209,11.863137845,-4.440892099E-15,10., 0000053P0000111
+0.,0.,1.,0.374671959,0.922556136,9.225561365E-02; 0000053P0000112
+144,57,1,0,59; 0000055P0000113
+108,-0.,-0.,-1.,-0.,0,10.,0.,0.,0.; 0000057P0000114
+142,0,57,0,61,2; 0000059P0000115
+102,2,63,65; 0000061P0000116
+126,12,12,1,0,1,0,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,1.,1., 0000063P0000117
+1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1., 0000063P0000118
+1.,1.,1.,-4.440892099E-15,10.,0.,1.308996939,10.,0.,2.61799414, 0000063P0000119
+9.813075441,0.,3.897628325,9.439227424,0.,5.118539774, 0000063P0000120
+8.88357873,0.,6.252371344,8.156379476,0.,7.272778816, 0000063P0000121
+7.272778816,0.,8.156379476,6.252371344,0.,8.88357873, 0000063P0000122
+5.118539774,0.,9.439227424,3.897628325,0.,9.813075441, 0000063P0000123
+2.61799414,0.,10.,1.308996939,0.,10.,0.,0.,0.,1.,-0.,-0.,1.; 0000063P0000124
+126,12,12,1,0,1,0,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,2.,2., 0000065P0000125
+2.,2.,2.,2.,2.,2.,2.,2.,2.,2.,2.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1., 0000065P0000126
+1.,1.,1.,10.,-3.552713679E-15,0.,10.,-3.926990817,0.,8.31767886, 0000065P0000127
+-7.853979875,0.,4.953059653,-10.988210754,0.,0.321117032, 0000065P0000128
+-12.536821528,0.,-4.747533624,-11.951833328,0.,-9.173342424, 0000065P0000129
+-9.173342424,0.,-11.951833328,-4.747533624,0.,-12.536821528, 0000065P0000130
+0.321117032,0.,-10.988210754,4.953059653,0.,-7.853979875, 0000065P0000131
+8.31767886,0.,-3.926990817,10.,0.,-4.440892099E-15,10.,0.,1.,2., 0000065P0000132
+-0.,-0.,1.; 0000065P0000133
+144,69,1,0,71; 0000067P0000134
+108,-2.072416309E-15,8.881784099E-16,1.,30.,0,6.,1.,30.,0.; 0000069P0000135
+142,0,69,0,73,2; 0000071P0000136
+102,2,75,77; 0000073P0000137
+126,12,12,1,0,1,0,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,1.,1., 0000075P0000138
+1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1., 0000075P0000139
+1.,1.,1.,6.,1.,30.,6.,1.785398163,30.,5.887845264,2.570796484, 0000075P0000140
+30.,5.663536454,3.338576995,30.,5.330147238,4.071123864,30., 0000075P0000141
+4.893827686,4.751422806,30.,4.36366729,5.36366729,30., 0000075P0000142
+3.751422806,5.893827686,30.,3.071123864,6.330147238,30., 0000075P0000143
+2.338576995,6.663536454,30.,1.570796484,6.887845264,30., 0000075P0000144
+0.785398163,7.,30.,1.776356839E-15,7.,30.,0.,1., 0000075P0000145
+-1.833058937E-15,-2.207554849E-15,1.; 0000075P0000146
+126,12,12,1,0,1,0,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,2.,2., 0000077P0000147
+2.,2.,2.,2.,2.,2.,2.,2.,2.,2.,2.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1., 0000077P0000148
+1.,1.,1.,1.776356839E-15,7.,30.,-2.35619449,7.,30.,-4.712387925, 0000077P0000149
+5.990607316,30.,-6.592926453,3.971835792,30.,-7.522092917, 0000077P0000150
+1.192670219,30.,-7.171099997,-1.848520174,30.,-5.504005454, 0000077P0000151
+-4.504005454,30.,-2.848520174,-6.171099997,30.,0.192670219, 0000077P0000152
+-6.522092917,30.,2.971835792,-5.592926453,30.,4.990607316, 0000077P0000153
+-3.712387925,30.,6.,-1.35619449,30.,6.,1.,30.,1.,2., 0000077P0000154
+-8.932021891E-16,-1.70759242E-16,1.; 0000077P0000155
+S 1G 4D 78P 155 T0000001
diff --git a/src/parametric/tests/fixtures/iges/plate-brep.igs b/src/parametric/tests/fixtures/iges/plate-brep.igs
new file mode 100644
index 0000000000..a58c74c909
--- /dev/null
+++ b/src/parametric/tests/fixtures/iges/plate-brep.igs
@@ -0,0 +1,269 @@
+ S0000001
+,,31HOpen CASCADE IGES processor 7.7,13HFilename.iges, G0000001
+16HOpen CASCADE 7.7,31HOpen CASCADE IGES processor 7.7,32,308,15,308,15,G0000002
+,1.,2,2HMM,1,0.01,15H20261130.112305,1E-07,30.,2Hnj,,11,0, G0000003
+15H20261130.112305,; G0000004
+ 402 1 0 0 0 0 0 000000000D0000001
+ 402 0 0 1 1 0D0000002
+ 186 2 0 0 0 0 0 000020000D0000003
+ 186 0 0 1 0 0D0000004
+ 514 3 0 0 0 0 0 000010000D0000005
+ 514 0 0 1 1 0D0000006
+ 510 4 0 0 0 0 0 000010000D0000007
+ 510 0 0 1 1 0D0000008
+ 190 5 0 0 0 0 0 000010000D0000009
+ 190 0 0 1 1 0D0000010
+ 116 6 0 0 0 0 0 000010400D0000011
+ 116 0 0 1 0 0D0000012
+ 123 7 0 0 0 0 0 000010200D0000013
+ 123 0 0 1 0 0D0000014
+ 123 8 0 0 0 0 0 000010200D0000015
+ 123 0 0 1 0 0D0000016
+ 508 9 0 0 0 0 0 000010000D0000017
+ 508 0 0 1 1 0D0000018
+ 504 10 0 0 0 0 0 000010001D0000019
+ 504 0 0 4 1 0D0000020
+ 110 14 0 0 0 0 0 000010000D0000021
+ 110 0 0 1 0 0D0000022
+ 502 15 0 0 0 0 0 000010000D0000023
+ 502 0 0 3 1 0D0000024
+ 110 18 0 0 0 0 0 000010000D0000025
+ 110 0 0 1 0 0D0000026
+ 110 19 0 0 0 0 0 000010000D0000027
+ 110 0 0 1 0 0D0000028
+ 110 20 0 0 0 0 0 000010000D0000029
+ 110 0 0 1 0 0D0000030
+ 110 21 0 0 0 0 0 000010000D0000031
+ 110 0 0 1 0 0D0000032
+ 110 22 0 0 0 0 0 000010000D0000033
+ 110 0 0 1 0 0D0000034
+ 110 23 0 0 0 0 0 000010000D0000035
+ 110 0 0 1 0 0D0000036
+ 100 24 0 0 0 0 39 000010000D0000037
+ 100 0 0 1 0 0D0000038
+ 124 25 0 0 0 0 0 000000000D0000039
+ 124 0 0 1 0 0D0000040
+ 100 26 0 0 0 0 43 000010000D0000041
+ 100 0 0 1 0 0D0000042
+ 124 27 0 0 0 0 0 000000000D0000043
+ 124 0 0 1 0 0D0000044
+ 100 28 0 0 0 0 47 000010000D0000045
+ 100 0 0 1 0 0D0000046
+ 124 29 0 0 0 0 0 000000000D0000047
+ 124 0 0 1 0 0D0000048
+ 110 30 0 0 0 0 0 000010000D0000049
+ 110 0 0 1 0 0D0000050
+ 110 31 0 0 0 0 0 000010000D0000051
+ 110 0 0 1 0 0D0000052
+ 110 32 0 0 0 0 0 000010000D0000053
+ 110 0 0 1 0 0D0000054
+ 110 33 0 0 0 0 0 000010000D0000055
+ 110 0 0 1 0 0D0000056
+ 110 34 0 0 0 0 0 000010000D0000057
+ 110 0 0 1 0 0D0000058
+ 100 35 0 0 0 0 61 000010000D0000059
+ 100 0 0 1 0 0D0000060
+ 124 36 0 0 0 0 0 000000000D0000061
+ 124 0 0 1 0 0D0000062
+ 110 37 0 0 0 0 0 000010000D0000063
+ 110 0 0 1 0 0D0000064
+ 110 38 0 0 0 0 0 000010000D0000065
+ 110 0 0 1 0 0D0000066
+ 510 39 0 0 0 0 0 000010000D0000067
+ 510 0 0 1 1 0D0000068
+ 190 40 0 0 0 0 0 000010000D0000069
+ 190 0 0 1 1 0D0000070
+ 116 41 0 0 0 0 0 000010400D0000071
+ 116 0 0 1 0 0D0000072
+ 123 42 0 0 0 0 0 000010200D0000073
+ 123 0 0 1 0 0D0000074
+ 123 43 0 0 0 0 0 000010200D0000075
+ 123 0 0 1 0 0D0000076
+ 508 44 0 0 0 0 0 000010000D0000077
+ 508 0 0 1 1 0D0000078
+ 508 45 0 0 0 0 0 000010000D0000079
+ 508 0 0 1 1 0D0000080
+ 510 46 0 0 0 0 0 000010000D0000081
+ 510 0 0 1 1 0D0000082
+ 192 47 0 0 0 0 0 000010000D0000083
+ 192 0 0 1 1 0D0000084
+ 116 48 0 0 0 0 0 000010400D0000085
+ 116 0 0 1 0 0D0000086
+ 123 49 0 0 0 0 0 000010200D0000087
+ 123 0 0 1 0 0D0000088
+ 123 50 0 0 0 0 0 000010200D0000089
+ 123 0 0 1 0 0D0000090
+ 508 51 0 0 0 0 0 000010000D0000091
+ 508 0 0 2 1 0D0000092
+ 110 53 0 0 0 0 0 000010000D0000093
+ 110 0 0 1 0 0D0000094
+ 110 54 0 0 0 0 0 000010000D0000095
+ 110 0 0 1 0 0D0000096
+ 110 55 0 0 0 0 0 000010000D0000097
+ 110 0 0 1 0 0D0000098
+ 110 56 0 0 0 0 0 000010000D0000099
+ 110 0 0 1 0 0D0000100
+ 510 57 0 0 0 0 0 000010000D0000101
+ 510 0 0 1 1 0D0000102
+ 190 58 0 0 0 0 0 000010000D0000103
+ 190 0 0 1 1 0D0000104
+ 116 59 0 0 0 0 0 000010400D0000105
+ 116 0 0 1 0 0D0000106
+ 123 60 0 0 0 0 0 000010200D0000107
+ 123 0 0 1 0 0D0000108
+ 123 61 0 0 0 0 0 000010200D0000109
+ 123 0 0 1 0 0D0000110
+ 508 62 0 0 0 0 0 000010000D0000111
+ 508 0 0 1 1 0D0000112
+ 510 63 0 0 0 0 0 000010000D0000113
+ 510 0 0 1 1 0D0000114
+ 190 64 0 0 0 0 0 000010000D0000115
+ 190 0 0 1 1 0D0000116
+ 116 65 0 0 0 0 0 000010400D0000117
+ 116 0 0 1 0 0D0000118
+ 123 66 0 0 0 0 0 000010200D0000119
+ 123 0 0 1 0 0D0000120
+ 123 67 0 0 0 0 0 000010200D0000121
+ 123 0 0 1 0 0D0000122
+ 508 68 0 0 0 0 0 000010000D0000123
+ 508 0 0 2 1 0D0000124
+ 508 70 0 0 0 0 0 000010000D0000125
+ 508 0 0 1 1 0D0000126
+ 510 71 0 0 0 0 0 000010000D0000127
+ 510 0 0 1 1 0D0000128
+ 190 72 0 0 0 0 0 000010000D0000129
+ 190 0 0 1 1 0D0000130
+ 116 73 0 0 0 0 0 000010400D0000131
+ 116 0 0 1 0 0D0000132
+ 123 74 0 0 0 0 0 000010200D0000133
+ 123 0 0 1 0 0D0000134
+ 123 75 0 0 0 0 0 000010200D0000135
+ 123 0 0 1 0 0D0000136
+ 508 76 0 0 0 0 0 000010000D0000137
+ 508 0 0 1 1 0D0000138
+ 510 77 0 0 0 0 0 000010000D0000139
+ 510 0 0 1 1 0D0000140
+ 190 78 0 0 0 0 0 000010000D0000141
+ 190 0 0 1 1 0D0000142
+ 116 79 0 0 0 0 0 000010400D0000143
+ 116 0 0 1 0 0D0000144
+ 123 80 0 0 0 0 0 000010200D0000145
+ 123 0 0 1 0 0D0000146
+ 123 81 0 0 0 0 0 000010200D0000147
+ 123 0 0 1 0 0D0000148
+ 508 82 0 0 0 0 0 000010000D0000149
+ 508 0 0 1 1 0D0000150
+ 510 83 0 0 0 0 0 000010000D0000151
+ 510 0 0 1 1 0D0000152
+ 192 84 0 0 0 0 0 000010000D0000153
+ 192 0 0 1 1 0D0000154
+ 116 85 0 0 0 0 0 000010400D0000155
+ 116 0 0 1 0 0D0000156
+ 123 86 0 0 0 0 0 000010200D0000157
+ 123 0 0 1 0 0D0000158
+ 123 87 0 0 0 0 0 000010200D0000159
+ 123 0 0 1 0 0D0000160
+ 508 88 0 0 0 0 0 000010000D0000161
+ 508 0 0 2 1 0D0000162
+ 110 90 0 0 0 0 0 000010000D0000163
+ 110 0 0 1 0 0D0000164
+ 110 91 0 0 0 0 0 000010000D0000165
+ 110 0 0 1 0 0D0000166
+ 110 92 0 0 0 0 0 000010000D0000167
+ 110 0 0 1 0 0D0000168
+ 110 93 0 0 0 0 0 000010000D0000169
+ 110 0 0 1 0 0D0000170
+402,1,3; 0000001P0000001
+186,5,1,0; 0000003P0000002
+514,8,7,1,67,1,81,1,101,0,113,0,127,1,139,0,151,0; 0000005P0000003
+510,9,1,1,17; 0000007P0000004
+190,11,13,15; 0000009P0000005
+116,30.,0.,0.,0; 0000011P0000006
+123,1.,0.,-0.; 0000013P0000007
+123,0.,0.,1.; 0000015P0000008
+508,4,0,19,1,0,0,0,19,2,0,0,0,19,3,1,0,0,19,4,1,0; 0000017P0000009
+504,18,21,23,1,23,2,25,23,3,23,1,27,23,3,23,4,29,23,4,23,2,31, 0000019P0000010
+23,5,23,6,33,23,7,23,5,35,23,7,23,1,37,23,2,23,6,41,23,8,23,8, 0000019P0000011
+45,23,4,23,9,49,23,9,23,6,51,23,10,23,3,53,23,10,23,7,55,23,11, 0000019P0000012
+23,9,57,23,10,23,11,59,23,12,23,12,63,23,11,23,5,65,23,12,23,8; 0000019P0000013
+110,30.,0.,10.,30.,16.,10.; 0000021P0000014
+502,12,30.,0.,10.,30.,16.,10.,30.,0.,0.,30.,16.,0.,0.,20.,10., 0000023P0000015
+26.,20.,10.,0.,0.,10.,13.,10.,10.,26.,20.,0.,0.,0.,0.,0.,20.,0., 0000023P0000016
+13.,10.,0.; 0000023P0000017
+110,30.,0.,0.,30.,0.,10.; 0000025P0000018
+110,30.,0.,0.,30.,16.,0.; 0000027P0000019
+110,30.,16.,0.,30.,16.,10.; 0000029P0000020
+110,0.,20.,10.,26.,20.,10.; 0000031P0000021
+110,0.,0.,10.,0.,20.,10.; 0000033P0000022
+110,0.,0.,10.,30.,0.,10.; 0000035P0000023
+100,0.,0.,0.,0.,4.,-4.,0.; 0000037P0000024
+124,0.,1.,0.,26.,-1.,0.,0.,16.,0.,0.,1.,10.; 0000039P0000025
+100,0.,0.,0.,3.,0.,3.,0.; 0000041P0000026
+124,1.,0.,0.,10.,0.,1.,0.,10.,0.,0.,1.,10.; 0000043P0000027
+100,0.,0.,0.,0.,4.,-4.,0.; 0000045P0000028
+124,0.,1.,0.,26.,-1.,0.,0.,16.,0.,0.,1.,0.; 0000047P0000029
+110,26.,20.,0.,26.,20.,10.; 0000049P0000030
+110,0.,0.,0.,30.,0.,0.; 0000051P0000031
+110,0.,0.,0.,0.,0.,10.; 0000053P0000032
+110,0.,20.,0.,26.,20.,0.; 0000055P0000033
+110,0.,0.,0.,0.,20.,0.; 0000057P0000034
+100,0.,0.,0.,3.,0.,3.,0.; 0000059P0000035
+124,1.,0.,0.,10.,0.,1.,0.,10.,0.,0.,1.,0.; 0000061P0000036
+110,0.,20.,0.,0.,20.,10.; 0000063P0000037
+110,13.,10.,0.,13.,10.,10.; 0000065P0000038
+510,69,2,1,77,79; 0000067P0000039
+190,71,73,75; 0000069P0000040
+116,0.,0.,10.,0; 0000071P0000041
+123,0.,0.,1.; 0000073P0000042
+123,1.,0.,-0.; 0000075P0000043
+508,5,0,19,5,0,0,0,19,6,0,0,0,19,7,1,0,0,19,1,1,0,0,19,8,1,0; 0000077P0000044
+508,1,0,19,9,0,0; 0000079P0000045
+510,83,1,1,91; 0000081P0000046
+192,85,87,4.,89; 0000083P0000047
+116,26.,16.,0.,0; 0000085P0000048
+123,0.,0.,1.; 0000087P0000049
+123,1.,0.,-0.; 0000089P0000050
+508,4,0,19,10,1,1,0,93,0,19,11,1,1,0,95,0,19,8,0,1,0,97,0,19,4, 0000091P0000051
+0,1,0,99; 0000091P0000052
+110,0.,0.,0.,90.,0.,0.; 0000093P0000053
+110,90.,0.,0.,90.,10.,0.; 0000095P0000054
+110,90.,10.,0.,0.,10.,0.; 0000097P0000055
+110,0.,10.,0.,0.,0.,0.; 0000099P0000056
+510,103,1,1,111; 0000101P0000057
+190,105,107,109; 0000103P0000058
+116,0.,0.,0.,0; 0000105P0000059
+123,-0.,1.,0.; 0000107P0000060
+123,0.,0.,1.; 0000109P0000061
+508,4,0,19,12,0,0,0,19,13,1,0,0,19,7,1,0,0,19,2,0,0; 0000111P0000062
+510,115,2,1,123,125; 0000113P0000063
+190,117,119,121; 0000115P0000064
+116,0.,0.,0.,0; 0000117P0000065
+123,0.,0.,1.; 0000119P0000066
+123,1.,0.,-0.; 0000121P0000067
+508,5,0,19,14,0,0,0,19,15,0,0,0,19,12,1,0,0,19,3,1,0,0,19,10,1, 0000123P0000068
+0; 0000123P0000069
+508,1,0,19,16,0,0; 0000125P0000070
+510,129,1,1,137; 0000127P0000071
+190,131,133,135; 0000129P0000072
+116,0.,20.,0.,0; 0000131P0000073
+123,-0.,1.,0.; 0000133P0000074
+123,0.,0.,1.; 0000135P0000075
+508,4,0,19,14,0,0,0,19,17,1,0,0,19,5,1,0,0,19,11,0,0; 0000137P0000076
+510,141,1,1,149; 0000139P0000077
+190,143,145,147; 0000141P0000078
+116,0.,0.,0.,0; 0000143P0000079
+123,1.,0.,-0.; 0000145P0000080
+123,0.,0.,1.; 0000147P0000081
+508,4,0,19,13,0,0,0,19,15,1,0,0,19,17,1,0,0,19,6,0,0; 0000149P0000082
+510,153,1,1,161; 0000151P0000083
+192,155,157,3.,159; 0000153P0000084
+116,10.,10.,-1.,0; 0000155P0000085
+123,0.,0.,1.; 0000157P0000086
+123,1.,0.,-0.; 0000159P0000087
+508,4,0,19,9,0,1,0,163,0,19,18,0,1,0,165,0,19,16,1,1,0,167,0,19, 0000161P0000088
+18,1,1,0,169; 0000161P0000089
+110,360.,11.,0.,0.,11.,0.; 0000163P0000090
+110,0.,11.,0.,0.,1.,0.; 0000165P0000091
+110,0.,1.,0.,360.,1.,0.; 0000167P0000092
+110,360.,1.,0.,360.,11.,0.; 0000169P0000093
+S 1G 4D 170P 93 T0000001
diff --git a/src/parametric/tests/fixtures/iges/plate-faces-inch.igs b/src/parametric/tests/fixtures/iges/plate-faces-inch.igs
new file mode 100644
index 0000000000..2809548db7
--- /dev/null
+++ b/src/parametric/tests/fixtures/iges/plate-faces-inch.igs
@@ -0,0 +1,308 @@
+ S0000001
+,,31HOpen CASCADE IGES processor 7.7,13HFilename.iges, G0000001
+16HOpen CASCADE 7.7,31HOpen CASCADE IGES processor 7.7,32,308,15,308,15,G0000002
+,1.,1,4HINCH,1,0.000394,15H20261130.112305,3.93701E-09,1.181102,2Hnj,, G0000003
+11,0,15H20261130.112305,; G0000004
+ 402 1 0 0 0 0 0 000000000D0000001
+ 402 0 0 1 1 0D0000002
+ 144 2 0 0 0 0 0 000020000D0000003
+ 144 0 0 1 0 0D0000004
+ 108 3 0 0 0 0 0 000010000D0000005
+ 108 0 0 1 0 0D0000006
+ 142 4 0 0 0 0 0 000010500D0000007
+ 142 0 0 1 0 0D0000008
+ 102 5 0 0 0 0 0 000010000D0000009
+ 102 0 0 1 0 0D0000010
+ 110 6 0 0 0 0 0 000010000D0000011
+ 110 0 0 2 0 0D0000012
+ 110 8 0 0 0 0 0 000010000D0000013
+ 110 0 0 1 0 0D0000014
+ 110 9 0 0 0 0 0 000010000D0000015
+ 110 0 0 1 0 0D0000016
+ 110 10 0 0 0 0 0 000010000D0000017
+ 110 0 0 2 0 0D0000018
+ 144 12 0 0 0 0 0 000020000D0000019
+ 144 0 0 1 0 0D0000020
+ 108 13 0 0 0 0 0 000010000D0000021
+ 108 0 0 1 0 0D0000022
+ 142 14 0 0 0 0 0 000010500D0000023
+ 142 0 0 1 0 0D0000024
+ 102 15 0 0 0 0 0 000010000D0000025
+ 102 0 0 1 0 0D0000026
+ 110 16 0 0 0 0 0 000010000D0000027
+ 110 0 0 2 0 0D0000028
+ 110 18 0 0 0 0 0 000010000D0000029
+ 110 0 0 1 0 0D0000030
+ 110 19 0 0 0 0 0 000010000D0000031
+ 110 0 0 1 0 0D0000032
+ 110 20 0 0 0 0 0 000010000D0000033
+ 110 0 0 2 0 0D0000034
+ 100 22 0 0 0 0 37 000010000D0000035
+ 100 0 0 1 0 0D0000036
+ 124 23 0 0 0 0 0 000000000D0000037
+ 124 0 0 2 0 0D0000038
+ 142 25 0 0 0 0 0 000010500D0000039
+ 142 0 0 1 0 0D0000040
+ 100 26 0 0 0 0 43 000010000D0000041
+ 100 0 0 1 0 0D0000042
+ 124 27 0 0 0 0 0 000000000D0000043
+ 124 0 0 2 0 0D0000044
+ 144 29 0 0 0 0 0 000020000D0000045
+ 144 0 0 1 0 0D0000046
+ 120 30 0 0 0 0 49 000010000D0000047
+ 120 0 0 1 0 0D0000048
+ 124 31 0 0 0 0 0 000000000D0000049
+ 124 0 0 1 0 0D0000050
+ 110 32 0 0 0 0 0 000010000D0000051
+ 110 0 0 1 0 0D0000052
+ 110 33 0 0 0 0 0 000010000D0000053
+ 110 0 0 1 0 0D0000054
+ 142 34 0 0 0 0 0 000010500D0000055
+ 142 0 0 1 0 0D0000056
+ 102 35 0 0 0 0 0 000010000D0000057
+ 102 0 0 1 0 0D0000058
+ 110 36 0 0 0 0 0 000010000D0000059
+ 110 0 0 2 0 0D0000060
+ 110 38 0 0 0 0 0 000010000D0000061
+ 110 0 0 1 0 0D0000062
+ 110 39 0 0 0 0 0 000010000D0000063
+ 110 0 0 1 0 0D0000064
+ 110 40 0 0 0 0 0 000010000D0000065
+ 110 0 0 1 0 0D0000066
+ 102 41 0 0 0 0 0 000010000D0000067
+ 102 0 0 1 0 0D0000068
+ 100 42 0 0 0 0 71 000010000D0000069
+ 100 0 0 1 0 0D0000070
+ 124 43 0 0 0 0 0 000000000D0000071
+ 124 0 0 1 0 0D0000072
+ 110 44 0 0 0 0 0 000010000D0000073
+ 110 0 0 2 0 0D0000074
+ 100 46 0 0 0 0 77 000010000D0000075
+ 100 0 0 1 0 0D0000076
+ 124 47 0 0 0 0 0 000000000D0000077
+ 124 0 0 2 0 0D0000078
+ 110 49 0 0 0 0 0 000010000D0000079
+ 110 0 0 2 0 0D0000080
+ 144 51 0 0 0 0 0 000020000D0000081
+ 144 0 0 1 0 0D0000082
+ 108 52 0 0 0 0 0 000010000D0000083
+ 108 0 0 1 0 0D0000084
+ 142 53 0 0 0 0 0 000010500D0000085
+ 142 0 0 1 0 0D0000086
+ 102 54 0 0 0 0 0 000010000D0000087
+ 102 0 0 1 0 0D0000088
+ 110 55 0 0 0 0 0 000010000D0000089
+ 110 0 0 1 0 0D0000090
+ 110 56 0 0 0 0 0 000010000D0000091
+ 110 0 0 1 0 0D0000092
+ 110 57 0 0 0 0 0 000010000D0000093
+ 110 0 0 1 0 0D0000094
+ 110 58 0 0 0 0 0 000010000D0000095
+ 110 0 0 1 0 0D0000096
+ 144 59 0 0 0 0 0 000020000D0000097
+ 144 0 0 1 0 0D0000098
+ 108 60 0 0 0 0 0 000010000D0000099
+ 108 0 0 1 0 0D0000100
+ 142 61 0 0 0 0 0 000010500D0000101
+ 142 0 0 1 0 0D0000102
+ 102 62 0 0 0 0 0 000010000D0000103
+ 102 0 0 1 0 0D0000104
+ 110 63 0 0 0 0 0 000010000D0000105
+ 110 0 0 1 0 0D0000106
+ 110 64 0 0 0 0 0 000010000D0000107
+ 110 0 0 1 0 0D0000108
+ 110 65 0 0 0 0 0 000010000D0000109
+ 110 0 0 1 0 0D0000110
+ 100 66 0 0 0 0 113 000010000D0000111
+ 100 0 0 1 0 0D0000112
+ 124 67 0 0 0 0 0 000000000D0000113
+ 124 0 0 1 0 0D0000114
+ 110 68 0 0 0 0 0 000010000D0000115
+ 110 0 0 1 0 0D0000116
+ 142 69 0 0 0 0 0 000010500D0000117
+ 142 0 0 1 0 0D0000118
+ 100 70 0 0 0 0 121 000010000D0000119
+ 100 0 0 1 0 0D0000120
+ 124 71 0 0 0 0 0 000000000D0000121
+ 124 0 0 1 0 0D0000122
+ 144 72 0 0 0 0 0 000020000D0000123
+ 144 0 0 1 0 0D0000124
+ 108 73 0 0 0 0 0 000010000D0000125
+ 108 0 0 1 0 0D0000126
+ 142 74 0 0 0 0 0 000010500D0000127
+ 142 0 0 1 0 0D0000128
+ 102 75 0 0 0 0 0 000010000D0000129
+ 102 0 0 1 0 0D0000130
+ 110 76 0 0 0 0 0 000010000D0000131
+ 110 0 0 1 0 0D0000132
+ 110 77 0 0 0 0 0 000010000D0000133
+ 110 0 0 1 0 0D0000134
+ 110 78 0 0 0 0 0 000010000D0000135
+ 110 0 0 2 0 0D0000136
+ 110 80 0 0 0 0 0 000010000D0000137
+ 110 0 0 2 0 0D0000138
+ 144 82 0 0 0 0 0 000020000D0000139
+ 144 0 0 1 0 0D0000140
+ 108 83 0 0 0 0 0 000010000D0000141
+ 108 0 0 1 0 0D0000142
+ 142 84 0 0 0 0 0 000010500D0000143
+ 142 0 0 1 0 0D0000144
+ 102 85 0 0 0 0 0 000010000D0000145
+ 102 0 0 1 0 0D0000146
+ 110 86 0 0 0 0 0 000010000D0000147
+ 110 0 0 1 0 0D0000148
+ 110 87 0 0 0 0 0 000010000D0000149
+ 110 0 0 1 0 0D0000150
+ 110 88 0 0 0 0 0 000010000D0000151
+ 110 0 0 1 0 0D0000152
+ 110 89 0 0 0 0 0 000010000D0000153
+ 110 0 0 1 0 0D0000154
+ 144 90 0 0 0 0 0 000020000D0000155
+ 144 0 0 1 0 0D0000156
+ 120 91 0 0 0 0 159 000010000D0000157
+ 120 0 0 1 0 0D0000158
+ 124 92 0 0 0 0 0 000000000D0000159
+ 124 0 0 2 1 0D0000160
+ 110 94 0 0 0 0 0 000010000D0000161
+ 110 0 0 1 0 0D0000162
+ 110 95 0 0 0 0 0 000010000D0000163
+ 110 0 0 1 0 0D0000164
+ 142 96 0 0 0 0 0 000010500D0000165
+ 142 0 0 1 0 0D0000166
+ 102 97 0 0 0 0 0 000010000D0000167
+ 102 0 0 1 0 0D0000168
+ 110 98 0 0 0 0 0 000010000D0000169
+ 110 0 0 1 0 0D0000170
+ 110 99 0 0 0 0 0 000010000D0000171
+ 110 0 0 1 0 0D0000172
+ 110 100 0 0 0 0 0 000010000D0000173
+ 110 0 0 1 0 0D0000174
+ 110 101 0 0 0 0 0 000010000D0000175
+ 110 0 0 2 0 0D0000176
+ 102 103 0 0 0 0 0 000010000D0000177
+ 102 0 0 1 0 0D0000178
+ 110 104 0 0 0 0 0 000010000D0000179
+ 110 0 0 2 0 0D0000180
+ 100 106 0 0 0 0 183 000010000D0000181
+ 100 0 0 1 0 0D0000182
+ 124 107 0 0 0 0 0 000000000D0000183
+ 124 0 0 2 0 0D0000184
+ 110 109 0 0 0 0 0 000010000D0000185
+ 110 0 0 2 0 0D0000186
+ 100 111 0 0 0 0 189 000010000D0000187
+ 100 0 0 1 0 0D0000188
+ 124 112 0 0 0 0 0 000000000D0000189
+ 124 0 0 1 0 0D0000190
+402,8,3,19,45,81,97,123,139,155; 0000001P0000001
+144,5,1,0,7; 0000003P0000002
+108,1.,0.,-0.,1.181102362,0,1.181102362,0.,0.,0.; 0000005P0000003
+142,0,5,0,9,2; 0000007P0000004
+102,4,11,13,15,17; 0000009P0000005
+110,1.181102362,0.62992126,0.393700787,1.181102362,0., 0000011P0000006
+0.393700787; 0000011P0000007
+110,1.181102362,0.,0.393700787,1.181102362,0.,0.; 0000013P0000008
+110,1.181102362,0.,0.,1.181102362,0.62992126,0.; 0000015P0000009
+110,1.181102362,0.62992126,0.,1.181102362,0.62992126, 0000017P0000010
+0.393700787; 0000017P0000011
+144,21,1,1,23,39; 0000019P0000012
+108,0.,0.,1.,0.393700787,0,0.,0.,0.393700787,0.; 0000021P0000013
+142,0,21,0,25,2; 0000023P0000014
+102,5,27,29,31,33,35; 0000025P0000015
+110,1.023622047,0.787401575,0.393700787,0.,0.787401575, 0000027P0000016
+0.393700787; 0000027P0000017
+110,0.,0.787401575,0.393700787,0.,0.,0.393700787; 0000029P0000018
+110,0.,0.,0.393700787,1.181102362,0.,0.393700787; 0000031P0000019
+110,1.181102362,0.,0.393700787,1.181102362,0.62992126, 0000033P0000020
+0.393700787; 0000033P0000021
+100,0.,0.,0.,0.,0.157480315,-0.157480315,0.; 0000035P0000022
+124,0.,1.,0.,1.023622047,-1.,0.,0.,0.62992126,0.,0.,1., 0000037P0000023
+0.393700787; 0000037P0000024
+142,0,21,0,41,2; 0000039P0000025
+100,0.,0.,0.,0.118110236,0.,0.118110236,0.; 0000041P0000026
+124,1.,0.,0.,0.393700787,0.,-1.,0.,0.393700787,0.,0.,-1., 0000043P0000027
+0.393700787; 0000043P0000028
+144,47,1,0,55; 0000045P0000029
+120,51,53,4.71238898,6.283185307; 0000047P0000030
+124,1.,0.,0.,1.023622047,0.,1.,0.,0.62992126,0.,0.,1.,0.; 0000049P0000031
+110,0.,0.,1.,0.,0.,0.; 0000051P0000032
+110,0.157480315,0.,0.,0.157480315,0.,0.393700787; 0000053P0000033
+142,0,47,57,67,3; 0000055P0000034
+102,4,59,61,63,65; 0000057P0000035
+110,-5.776596856E-33,6.283185307,0.,-2.785058308E-17,4.71238898, 0000059P0000036
+0.; 0000059P0000037
+110,-2.785058308E-17,4.71238898,0.,1.,4.71238898,0.; 0000061P0000038
+110,1.,4.71238898,0.,1.,6.283185307,0.; 0000063P0000039
+110,1.,6.283185307,0.,0.,6.283185307,0.; 0000065P0000040
+102,4,69,73,75,79; 0000067P0000041
+100,0.,0.,0.,0.,0.157480315,-0.157480315,0.; 0000069P0000042
+124,0.,1.,0.,1.023622047,-1.,0.,0.,0.62992126,0.,0.,1.,0.; 0000071P0000043
+110,1.023622047,0.787401575,0.,1.023622047,0.787401575, 0000073P0000044
+0.393700787; 0000073P0000045
+100,0.,0.,0.,-0.157480315,0.,0.,-0.157480315; 0000075P0000046
+124,0.,-1.,0.,1.023622047,-1.,0.,0.,0.62992126,0.,0.,-1., 0000077P0000047
+0.393700787; 0000077P0000048
+110,1.181102362,0.62992126,0.393700787,1.181102362,0.62992126, 0000079P0000049
+0.; 0000079P0000050
+144,83,1,0,85; 0000081P0000051
+108,0.,-1.,-0.,-0.,0,0.,0.,0.,0.; 0000083P0000052
+142,0,83,0,87,2; 0000085P0000053
+102,4,89,91,93,95; 0000087P0000054
+110,0.,0.,0.393700787,0.,0.,0.; 0000089P0000055
+110,0.,0.,0.,1.181102362,0.,0.; 0000091P0000056
+110,1.181102362,0.,0.,1.181102362,0.,0.393700787; 0000093P0000057
+110,1.181102362,0.,0.393700787,0.,0.,0.393700787; 0000095P0000058
+144,99,1,1,101,117; 0000097P0000059
+108,-0.,-0.,-1.,-0.,0,0.,0.,0.,0.; 0000099P0000060
+142,0,99,0,103,2; 0000101P0000061
+102,5,105,107,109,111,115; 0000103P0000062
+110,1.181102362,0.,0.,0.,0.,0.; 0000105P0000063
+110,0.,0.,0.,0.,0.787401575,0.; 0000107P0000064
+110,0.,0.787401575,0.,1.023622047,0.787401575,0.; 0000109P0000065
+100,0.,0.,0.,-0.157480315,0.,0.,-0.157480315; 0000111P0000066
+124,0.,-1.,0.,1.023622047,-1.,0.,0.,0.62992126,0.,0.,-1.,0.; 0000113P0000067
+110,1.181102362,0.62992126,0.,1.181102362,0.,0.; 0000115P0000068
+142,0,99,0,119,2; 0000117P0000069
+100,0.,0.,0.,0.118110236,0.,0.118110236,0.; 0000119P0000070
+124,1.,0.,0.,0.393700787,0.,1.,0.,0.393700787,0.,0.,1.,0.; 0000121P0000071
+144,125,1,0,127; 0000123P0000072
+108,-0.,1.,0.,0.787401575,0,0.,0.787401575,0.,0.; 0000125P0000073
+142,0,125,0,129,2; 0000127P0000074
+102,4,131,133,135,137; 0000129P0000075
+110,1.023622047,0.787401575,0.,0.,0.787401575,0.; 0000131P0000076
+110,0.,0.787401575,0.,0.,0.787401575,0.393700787; 0000133P0000077
+110,0.,0.787401575,0.393700787,1.023622047,0.787401575, 0000135P0000078
+0.393700787; 0000135P0000079
+110,1.023622047,0.787401575,0.393700787,1.023622047,0.787401575, 0000137P0000080
+0.; 0000137P0000081
+144,141,1,0,143; 0000139P0000082
+108,-1.,-0.,0.,-0.,0,0.,0.,0.,0.; 0000141P0000083
+142,0,141,0,145,2; 0000143P0000084
+102,4,147,149,151,153; 0000145P0000085
+110,0.,0.787401575,0.,0.,0.,0.; 0000147P0000086
+110,0.,0.,0.,0.,0.,0.393700787; 0000149P0000087
+110,0.,0.,0.393700787,0.,0.787401575,0.393700787; 0000151P0000088
+110,0.,0.787401575,0.393700787,0.,0.787401575,0.; 0000153P0000089
+144,157,1,0,165; 0000155P0000090
+120,161,163,0.,6.283185307; 0000157P0000091
+124,1.,0.,0.,0.393700787,0.,-1.,0.,0.393700787,0.,0.,1., 0000159P0000092
+-3.937007874E-02; 0000159P0000093
+110,0.,0.,1.,0.,0.,0.; 0000161P0000094
+110,0.118110236,0.,3.937007874E-02,0.118110236,0.,0.433070866; 0000163P0000095
+142,0,157,167,177,3; 0000165P0000096
+102,4,169,171,173,175; 0000167P0000097
+110,-8.881784197E-17,1.065480738E-15,0.,1.,2.838503924E-15,0.; 0000169P0000098
+110,1.,3.552713679E-15,0.,1.,6.283185307,0.; 0000171P0000099
+110,1.,6.283185307,0.,2.220446049E-17,6.283185307,0.; 0000173P0000100
+110,2.767680502E-32,6.283185307,0.,-1.114023323E-16, 0000175P0000101
+1.776356839E-15,0.; 0000175P0000102
+102,4,179,181,185,187; 0000177P0000103
+110,0.511811024,0.393700787,0.,0.511811024,0.393700787, 0000179P0000104
+0.393700787; 0000179P0000105
+100,0.,0.,0.,0.118110236,0.,0.118110236,0.; 0000181P0000106
+124,1.,0.,0.,0.393700787,0.,1.,0.,0.393700787,0.,0.,1., 0000183P0000107
+0.393700787; 0000183P0000108
+110,0.511811024,0.393700787,0.393700787,0.511811024,0.393700787, 0000185P0000109
+0.; 0000185P0000110
+100,0.,0.,0.,0.118110236,0.,0.118110236,0.; 0000187P0000111
+124,1.,0.,0.,0.393700787,0.,-1.,0.,0.393700787,0.,0.,-1.,0.; 0000189P0000112
+S 1G 4D 190P 112 T0000001
diff --git a/src/parametric/tests/fixtures/iges/revolve-faces.igs b/src/parametric/tests/fixtures/iges/revolve-faces.igs
new file mode 100644
index 0000000000..d42266da2f
--- /dev/null
+++ b/src/parametric/tests/fixtures/iges/revolve-faces.igs
@@ -0,0 +1,169 @@
+ S0000001
+,,31HOpen CASCADE IGES processor 7.7,13HFilename.iges, G0000001
+16HOpen CASCADE 7.7,31HOpen CASCADE IGES processor 7.7,32,308,15,308,15,G0000002
+,1.,2,2HMM,1,0.01,15H20261130.111936,1E-07,37.678764,2Hnj,,11,0, G0000003
+15H20261130.111936,; G0000004
+ 402 1 0 0 0 0 0 000000000D0000001
+ 402 0 0 1 1 0D0000002
+ 144 2 0 0 0 0 0 000020000D0000003
+ 144 0 0 1 0 0D0000004
+ 120 3 0 0 0 0 0 000010000D0000005
+ 120 0 0 1 0 0D0000006
+ 110 4 0 0 0 0 0 000010000D0000007
+ 110 0 0 1 0 0D0000008
+ 126 5 0 0 0 0 0 000010000D0000009
+ 126 0 0 3 0 0D0000010
+ 142 8 0 0 0 0 0 000010500D0000011
+ 142 0 0 1 0 0D0000012
+ 102 9 0 0 0 0 0 000010000D0000013
+ 102 0 0 1 0 0D0000014
+ 110 10 0 0 0 0 0 000010000D0000015
+ 110 0 0 1 0 0D0000016
+ 110 11 0 0 0 0 0 000010000D0000017
+ 110 0 0 1 0 0D0000018
+ 110 12 0 0 0 0 0 000010000D0000019
+ 110 0 0 1 0 0D0000020
+ 110 13 0 0 0 0 0 000010000D0000021
+ 110 0 0 1 0 0D0000022
+ 102 14 0 0 0 0 0 000010000D0000023
+ 102 0 0 1 0 0D0000024
+ 100 15 0 0 0 0 27 000010000D0000025
+ 100 0 0 1 0 0D0000026
+ 124 16 0 0 0 0 0 000000000D0000027
+ 124 0 0 1 0 0D0000028
+ 126 17 0 0 0 0 0 000010000D0000029
+ 126 0 0 5 0 0D0000030
+ 100 22 0 0 0 0 33 000010000D0000031
+ 100 0 0 1 0 0D0000032
+ 124 23 0 0 0 0 0 000000000D0000033
+ 124 0 0 1 0 0D0000034
+ 126 24 0 0 0 0 0 000010000D0000035
+ 126 0 0 4 0 0D0000036
+ 144 28 0 0 0 0 0 000020000D0000037
+ 144 0 0 1 0 0D0000038
+ 120 29 0 0 0 0 41 000010000D0000039
+ 120 0 0 1 0 0D0000040
+ 124 30 0 0 0 0 0 000000000D0000041
+ 124 0 0 1 1 0D0000042
+ 110 31 0 0 0 0 0 000010000D0000043
+ 110 0 0 1 0 0D0000044
+ 110 32 0 0 0 0 0 000010000D0000045
+ 110 0 0 1 0 0D0000046
+ 142 33 0 0 0 0 0 000010500D0000047
+ 142 0 0 1 0 0D0000048
+ 102 34 0 0 0 0 0 000010000D0000049
+ 102 0 0 1 0 0D0000050
+ 110 35 0 0 0 0 0 000010000D0000051
+ 110 0 0 1 0 0D0000052
+ 110 36 0 0 0 0 0 000010000D0000053
+ 110 0 0 1 0 0D0000054
+ 110 37 0 0 0 0 0 000010000D0000055
+ 110 0 0 2 0 0D0000056
+ 110 39 0 0 0 0 0 000010000D0000057
+ 110 0 0 1 0 0D0000058
+ 102 40 0 0 0 0 0 000010000D0000059
+ 102 0 0 1 0 0D0000060
+ 100 41 0 0 0 0 63 000010000D0000061
+ 100 0 0 1 0 0D0000062
+ 124 42 0 0 0 0 0 000000000D0000063
+ 124 0 0 1 0 0D0000064
+ 110 43 0 0 0 0 0 000010000D0000065
+ 110 0 0 2 0 0D0000066
+ 100 45 0 0 0 0 69 000010000D0000067
+ 100 0 0 1 0 0D0000068
+ 124 46 0 0 0 0 0 000000000D0000069
+ 124 0 0 1 0 0D0000070
+ 110 47 0 0 0 0 0 000010000D0000071
+ 110 0 0 1 0 0D0000072
+ 144 48 0 0 0 0 0 000020000D0000073
+ 144 0 0 1 0 0D0000074
+ 108 49 0 0 0 0 0 000010000D0000075
+ 108 0 0 1 0 0D0000076
+ 142 50 0 0 0 0 0 000010500D0000077
+ 142 0 0 1 0 0D0000078
+ 102 51 0 0 0 0 0 000010000D0000079
+ 102 0 0 1 0 0D0000080
+ 126 52 0 0 0 0 0 000010000D0000081
+ 126 0 0 3 0 0D0000082
+ 110 55 0 0 0 0 0 000010000D0000083
+ 110 0 0 1 0 0D0000084
+ 144 56 0 0 0 0 0 000020000D0000085
+ 144 0 0 1 0 0D0000086
+ 108 57 0 0 0 0 0 000010000D0000087
+ 108 0 0 2 0 0D0000088
+ 142 59 0 0 0 0 0 000010500D0000089
+ 142 0 0 1 0 0D0000090
+ 102 60 0 0 0 0 0 000010000D0000091
+ 102 0 0 1 0 0D0000092
+ 110 61 0 0 0 0 0 000010000D0000093
+ 110 0 0 2 0 0D0000094
+ 126 63 0 0 0 0 0 000010000D0000095
+ 126 0 0 5 0 0D0000096
+402,4,3,37,73,85; 0000001P0000001
+144,5,1,0,11; 0000003P0000002
+120,7,9,2.792526803,6.283185307; 0000005P0000003
+110,0.,0.,0.,0.,-1.,0.; 0000007P0000004
+126,4,4,1,0,1,0,0.,0.,0.,0.,0.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1., 0000009P0000005
+20.,0.,0.,27.45285719,-5.905218312,0.,46.911317161,3.375989864, 0000009P0000006
+0.,27.703369512,26.759360272,0.,22.,12.,0.,0.,1.,0.,0.,1.; 0000009P0000007
+142,0,5,13,23,3; 0000011P0000008
+102,4,15,17,19,21; 0000013P0000009
+110,0.,6.283185307,0.,-6.189018461E-16,2.792526803,0.; 0000015P0000010
+110,-6.189018461E-16,2.792526803,0.,1.,2.792526803,0.; 0000017P0000011
+110,1.,2.792526803,0.,1.,6.283185307,0.; 0000019P0000012
+110,1.,6.283185307,0.,0.,6.283185307,0.; 0000021P0000013
+102,4,25,29,31,35; 0000023P0000014
+100,0.,0.,0.,20.,0.,-18.793852416,-6.840402867; 0000025P0000015
+124,1.,0.,0.,0.,0.,0.,1.,0.,0.,-1.,0.,0.; 0000027P0000016
+126,4,4,1,0,1,0,0.,0.,0.,0.,0.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1., 0000029P0000017
+-18.793852416,0.,6.840402867,-25.797247321,-5.905218312, 0000029P0000018
+9.389430151,-44.082218568,3.375989864,16.044615419, 0000029P0000019
+-26.032651901,26.759360272,9.475110411,-20.673237657,12., 0000029P0000020
+7.524443153,0.,1.,0.342020143,-4.738639875E-17,0.939692621; 0000029P0000021
+100,0.,0.,0.,-20.673237657,7.524443153,22.,-5.388445916E-15; 0000031P0000022
+124,1.,0.,0.,0.,0.,0.,-1.,12.,0.,1.,-0.,0.; 0000033P0000023
+126,4,4,1,0,1,0,0.,0.,0.,0.,0.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1., 0000035P0000024
+22.,12.,0.,27.703369512,26.759360272,0.,46.911317161, 0000035P0000025
+3.375989864,0.,27.45285719,-5.905218312,0.,20.,0.,0.,0.,1.,-0., 0000035P0000026
+-0.,1.; 0000035P0000027
+144,39,1,0,47; 0000037P0000028
+120,43,45,0.,3.490658504; 0000039P0000029
+124,1.,0.,0.,0.,0.,0.,1.,12.,0.,1.,0.,0.; 0000041P0000030
+110,0.,0.,1.,0.,0.,0.; 0000043P0000031
+110,20.,0.,-12.,22.,0.,0.; 0000045P0000032
+142,0,39,49,59,3; 0000047P0000033
+102,4,51,53,55,57; 0000049P0000034
+110,1.,3.552713679E-15,0.,1.,3.490658504,0.; 0000051P0000035
+110,1.,3.490658504,0.,-1.110223025E-16,3.490658504,0.; 0000053P0000036
+110,-4.06987347E-17,3.490658504,0.,-9.157215307E-17, 0000055P0000037
+1.776356839E-15,0.; 0000055P0000038
+110,-3.330669074E-16,1.395737879E-15,0.,1.,3.552713679E-15,0.; 0000057P0000039
+102,4,61,65,67,71; 0000059P0000040
+100,0.,0.,0.,22.,0.,-20.673237657,-7.524443153; 0000061P0000041
+124,1.,0.,0.,0.,0.,0.,1.,12.,0.,-1.,0.,0.; 0000063P0000042
+110,-20.673237657,12.,7.524443153,-18.793852416,5.051280013E-16, 0000065P0000043
+6.840402867; 0000065P0000044
+100,0.,0.,0.,-18.793852416,6.840402867,20.,-4.898587197E-15; 0000067P0000045
+124,1.,0.,0.,0.,0.,0.,-1.,0.,0.,1.,-0.,0.; 0000069P0000046
+110,20.,5.051280013E-16,0.,22.,12.,0.; 0000071P0000047
+144,75,1,0,77; 0000073P0000048
+108,0.,0.,1.,0.,0,26.657919411,6.736934495,0.,0.; 0000075P0000049
+142,0,75,0,79,2; 0000077P0000050
+102,2,81,83; 0000079P0000051
+126,4,4,1,0,1,0,0.,0.,0.,0.,0.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1., 0000081P0000052
+20.,0.,0.,27.45285719,-5.905218312,0.,46.911317161,3.375989864, 0000081P0000053
+0.,27.703369512,26.759360272,0.,22.,12.,0.,0.,1.,0.,0.,1.; 0000081P0000054
+110,22.,12.,0.,20.,5.051280013E-16,0.; 0000083P0000055
+144,87,1,0,89; 0000085P0000056
+108,0.342020143,-0.,0.939692621,-7.355465073E-16,0, 0000087P0000057
+-25.050250156,6.736934495,9.117545418,0.; 0000087P0000058
+142,0,87,0,91,2; 0000089P0000059
+102,2,93,95; 0000091P0000060
+110,-18.793852416,5.051280013E-16,6.840402867,-20.673237657,12., 0000093P0000061
+7.524443153; 0000093P0000062
+126,4,4,1,0,1,0,0.,0.,0.,0.,0.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1., 0000095P0000063
+-20.673237657,12.,7.524443153,-26.032651901,26.759360272, 0000095P0000064
+9.475110411,-44.082218568,3.375989864,16.044615419, 0000095P0000065
+-25.797247321,-5.905218312,9.389430151,-18.793852416,0., 0000095P0000066
+6.840402867,0.,1.,0.342020143,-5.284255876E-17,0.939692621; 0000095P0000067
+S 1G 4D 96P 67 T0000001
diff --git a/src/parametric/tests/iges.test.ts b/src/parametric/tests/iges.test.ts
new file mode 100644
index 0000000000..f95422cecc
--- /dev/null
+++ b/src/parametric/tests/iges.test.ts
@@ -0,0 +1,512 @@
+// IGES export and import. Exports are read back by this reader and checked
+// against the model; the fixtures in fixtures/iges were written by another
+// IGES writer (OpenCascade's, in trimmed-surface and B-rep modes) from a plate
+// with a hole and a filleted edge (one in inches), a loft and a revolved
+// spline profile.
+import { readFileSync } from 'node:fs';
+import { beforeAll, describe, expect, it } from 'vitest';
+import init from 'replicad-opencascadejs';
+import { ModelBuilder } from '../src/kernel/build';
+import { AssemblyBuilder, type AsmSceneItem } from '../src/kernel/assembly';
+import { type Sh, getOc, setOc, subShapes } from '../src/kernel/occ';
+import { exportIges, importIges } from '../src/kernel/iges';
+import { readStep } from '../src/kernel/stepfile';
+import { placementMatrix } from '../src/assembly/compose';
+import { EXAMPLES } from '../src/app/examples';
+import { newSurfaceFeature } from '../src/model/surfaces';
+import type { Feature, SkEntity } from '../src/model/types';
+import {
+ type NurbsCurve, angleToParam, arcCurve, clampCurve, curveDomain, curvePoint, distance, elevateDegree, fitCurve, isoCurve, paramToAngle, reverseCurve, revolveCurve,
+ surfaceDomain, surfacePoint, transposeSurface,
+} from '../src/formats/iges/nurbs';
+import { IgesWriter, asciiOnly, igesReal, writeIges } from '../src/formats/iges/write';
+import { IgesError, parseIges, tokenize } from '../src/formats/iges/parse';
+import { convertIges, curveEnd, curveStart } from '../src/formats/iges/convert';
+import { circle, extrude, polygon, rect, req, revolve, sketch } from './helpers';
+
+beforeAll(async () => {
+ setOc(await init());
+});
+
+const text = (data: Uint8Array) => new TextDecoder().decode(data);
+const fixture = (name: string) => text(readFileSync(new URL(`./fixtures/iges/${name}`, import.meta.url)));
+
+/** Volume integrated to a tight tolerance (rational surfaces need it). */
+function volume(shape: Sh): number {
+ const oc = getOc();
+ const p = new oc.GProp_GProps();
+ try {
+ oc.BRepGProp.VolumeProperties(shape.wrapped, p, 1e-9, true, false);
+ return Math.abs(p.Mass());
+ } finally {
+ p.delete();
+ }
+}
+
+async function built(features: Feature[]): Promise {
+ const b = new ModelBuilder();
+ const res = await b.build(req(features));
+ expect(res.status.filter((s) => !s.ok)).toEqual([]);
+ return b;
+}
+
+/** Imports through the regular import feature, as the app does after converting. */
+async function imported(step: string) {
+ const b = new ModelBuilder();
+ const res = await b.build(req([{ id: 'i', name: 'i', type: 'import', format: 'step', blob: 'b', fileName: 'x.igs' }], { blobs: { b: step } }));
+ expect(res.status[0]).toMatchObject({ ok: true });
+ return { faces: res.faces, shape: b.currentShapes().body! };
+}
+
+const types = (faces: ({ type: string } | { desc: { type: string } })[]) => new Set(faces.map((f) => ('desc' in f ? f.desc.type : f.type)));
+
+describe('IGES NURBS geometry', () => {
+ it('writes exact arcs whose parameter maps to the angle', () => {
+ const c = [1, 2, 3], e1 = [4, 0, 0], e2 = [0, 0, 4];
+ const arc = arcCurve(c, e1, e2, -0.3, 4.1);
+ for (const t of [-0.3, 0.2, 1.3, 2.9, 4.1]) {
+ const u = angleToParam(-0.3, 4.1, t);
+ expect(paramToAngle(-0.3, 4.1, u)).toBeCloseTo(t, 12);
+ const p = curvePoint(arc, u);
+ const want = c.map((x, i) => x + Math.cos(t) * e1[i] + Math.sin(t) * e2[i]);
+ expect(distance(p, want)).toBeLessThan(1e-12);
+ }
+ });
+
+ it('revolves a generatrix exactly (a sphere from a half circle)', () => {
+ const gen = arcCurve([0, 0, 0], [5, 0, 0], [0, 0, 5], -Math.PI / 2, Math.PI / 2);
+ const s = revolveCurve(gen, [0, 0, 0], [0, 0, 1], 0, 2 * Math.PI);
+ for (const u of [0, 1, 2.5, 5, 6.28]) for (const v of [-1.5, -0.2, 0.7, 1.5]) {
+ expect(Math.hypot(...surfacePoint(s, angleToParam(0, 2 * Math.PI, u), angleToParam(-Math.PI / 2, Math.PI / 2, v)))).toBeCloseTo(5, 12);
+ }
+ });
+
+ it('clamps an unclamped B-spline and raises its degree without moving it', () => {
+ const c: NurbsCurve = { degree: 3, knots: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], poles: [[0, 0, 0], [1, 2, 0], [3, 3, 1], [4, 0, 2], [6, -1, 1], [7, 2, 0]], weights: [1, 2, 1, 0.5, 1, 1] };
+ const k = clampCurve(c);
+ const [a, b] = curveDomain(c);
+ expect(curveDomain(k)).toEqual([a, b]);
+ expect(k.knots.slice(0, 4)).toEqual([a, a, a, a]);
+ const e = elevateDegree(k);
+ for (let i = 0; i <= 10; i++) {
+ const t = a + ((b - a) * i) / 10;
+ expect(distance(curvePoint(k, t), curvePoint(c, t))).toBeLessThan(1e-12);
+ expect(distance(curvePoint(e, t), curvePoint(c, t))).toBeLessThan(1e-12);
+ }
+ });
+
+ it('interpolates curves within the tolerance it is given', () => {
+ const ev = (t: number) => [Math.cos(t) * 10, Math.sin(3 * t), t * t];
+ const c = fitCurve(ev, 0, 2, 1e-7);
+ for (let i = 0; i <= 50; i++) expect(distance(curvePoint(c, (2 * i) / 50), ev((2 * i) / 50))).toBeLessThan(2e-7);
+ });
+});
+
+describe('IGES file format', () => {
+ it('writes reals with a decimal point, and only 7-bit text', () => {
+ expect(igesReal(0)).toBe('0.');
+ expect(igesReal(-0)).toBe('0.');
+ expect(igesReal(3)).toBe('3.');
+ expect(igesReal(-2.5)).toBe('-2.5');
+ expect(igesReal(1e-7)).toBe('1.E-7');
+ expect(igesReal(1.5e21)).toBe('1.5E21');
+ expect(asciiOnly('Straße Ünit 🙂')).toBe('Stra_e Unit __');
+ });
+
+ it('writes fixed 80-column sections with sequence numbers and a matching terminate line', () => {
+ const w = new IgesWriter();
+ const long = 'x'.repeat(150);
+ w.add(110, [0, 0, 0, { real: 1 }, { real: 2 }, { real: 3 }]);
+ w.add(406, [1, `${long.length}H${long}`], { form: 15 });
+ const out = w.toString({ name: "O'Brien, Bracket", fileName: 'b.igs', resolution: 1e-6, date: new Date(Date.UTC(2026, 0, 2, 3, 4, 5)) });
+ const lines = out.trimEnd().split('\n');
+ for (const l of lines) expect(l).toHaveLength(80);
+ const counts: Record = {};
+ for (const l of lines) {
+ const s = l[72];
+ counts[s] = (counts[s] ?? 0) + 1;
+ expect(Number(l.slice(73))).toBe(counts[s]);
+ }
+ expect(lines.at(-1)!.slice(0, 32)).toBe(`S${'1'.padStart(7, '0')}G${String(counts.G).padStart(7, '0')}D${String(counts.D).padStart(7, '0')}P${String(counts.P).padStart(7, '0')}`);
+ // Read back: the long string spans lines, the name keeps its comma.
+ const f = parseIges(out);
+ expect(f.global[2]).toBe("16HO'Brien, Bracket");
+ expect(f.global[17]).toBe('15H20260102.030405');
+ expect(f.entities.get(3)!.params[1]).toBe(`150H${long}`);
+ expect(f.entities.get(1)!.params.map(Number)).toEqual([0, 0, 0, 1, 2, 3]);
+ });
+
+ it('reads other delimiters, D exponents and strings holding delimiters', () => {
+ expect(tokenize('5Ha;b,c;2.D1;;/', ';', '/')).toEqual(['5Ha;b,c', '2.D1', '', '']);
+ const G = (s: string) => s.padEnd(72) + 'G0000001';
+ const file = [
+ ''.padEnd(72) + 'S0000001',
+ G("1H;;1H/;4Hname;6Hb;.igs;;;32;38;6;308;15;;1.;1;2HIN;1;0.01;;0.0001;100./"),
+ ' 110 1 0 0 0 0 0 000000000D0000001',
+ ' 110 0 0 1 0 0D0000002',
+ '110;1.D0;2.;3.;4.;5.;6./ 1P0000001',
+ 'S0000001G0000001D0000002P0000001'.padEnd(72) + 'T0000001',
+ ].join('\r\n');
+ const f = parseIges(file);
+ expect(f.unit).toBe(25.4);
+ expect(f.resolution).toBe(0.0001);
+ expect(f.entities.get(1)!.params.map((p) => Number(p.replace('D', 'E')))).toEqual([1, 2, 3, 4, 5, 6]);
+ });
+
+ it('says why a file cannot be read', () => {
+ expect(() => parseIges('ISO-10303-21;\nHEADER;')).toThrow(IgesError);
+ expect(() => parseIges('\u0000\u0001binary')).toThrow(/binary IGES/);
+ expect(() => parseIges(''.padEnd(72) + 'C0000001\n')).toThrow(/compressed IGES/);
+ // Only curves: nothing to import as a body.
+ const w = new IgesWriter();
+ w.add(110, [0, 0, 0, 1, 1, 1]);
+ expect(() => convertIges(parseIges(w.toString({ name: 'x', fileName: 'x.igs', resolution: 1e-6 })))).toThrow(/only curves or points/);
+ });
+});
+
+/** A unit square plane patch (128) as a trimmed face (144) bounded by `loop`. */
+function squareFace(w: IgesWriter, loop: (srf: number) => number, opts: { status?: string } = {}) {
+ const srf = w.add(128, [1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 10, 0, 0, 0, 10, 0, 10, 10, 0, 0, 1, 0, 1], { status: '00010000' });
+ return w.add(144, [srf, 1, 0, loop(srf)], { status: opts.status ?? '00000000' });
+}
+
+const lines = (w: IgesWriter, pts: number[][]) => pts.map((p, i) => w.add(110, [...p, ...pts[(i + 1) % pts.length]], { status: '00010000' }));
+const convert = (w: IgesWriter) => convertIges(parseIges(w.toString({ name: 't', fileName: 't.igs', resolution: 1e-6 })));
+
+describe('IGES entities', () => {
+ it('reads a trimmed plane, building model-space edges from a boundary given only in parameter space', () => {
+ const w = new IgesWriter();
+ squareFace(w, (srf) => {
+ // A triangle in (u, v) from 0 to 1: CPTR is 0.
+ const uv = [[0, 0, 0], [1, 0, 0], [0, 1, 0]];
+ const segs = lines(w, uv);
+ const comp = w.add(102, [3, ...segs], { status: '00010500' });
+ return w.add(142, [1, srf, comp, 0, 1], { status: '00010500' });
+ });
+ const m = convert(w);
+ expect(m.faces).toHaveLength(1);
+ expect(m.faces[0].surface.kind).toBe('plane');
+ const loop = m.faces[0].loops[0];
+ expect(loop).toHaveLength(3);
+ expect(distance(curveStart(loop[0]), [0, 0, 0])).toBeLessThan(1e-9);
+ expect(distance(curveEnd(loop[0]), [10, 0, 0])).toBeLessThan(1e-9);
+ expect(distance(curveEnd(loop[1]), [0, 10, 0])).toBeLessThan(1e-9);
+ });
+
+ it('places curves with their transformation, and reads bounded surfaces and subfigures', () => {
+ const w = new IgesWriter();
+ // 124: a quarter turn about z, then up 5.
+ const tr = w.add(124, [0, -1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 5]);
+ // A 143 bounded plane: a square through a 141 boundary whose pieces run the other way (SENSE 2).
+ const srf = w.add(128, [1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 10, 0, 0, 0, 10, 0, 10, 10, 0, 0, 1, 0, 1], { status: '00010000' });
+ const comp = w.add(102, [4, ...lines(w, [[0, 0, 0], [0, 10, 0], [10, 10, 0], [10, 0, 0]])], { status: '00010000' });
+ const bnd = w.add(141, [0, 2, srf, 1, comp, 2, 0], { status: '00010000' });
+ w.add(143, [0, srf, 1, bnd]);
+ // A face bounded by a full circle of radius 2, placed by the 124.
+ const s2 = w.add(128, [1, 1, 1, 1, 0, 0, 1, 0, 0, -5, -5, 5, 5, -5, -5, 5, 5, 1, 1, 1, 1, -5, -5, 0, 5, -5, 0, -5, 5, 0, 5, 5, 0, -5, 5, -5, 5], { status: '00010000' });
+ const arc = w.add(100, [0, 0, 0, 2, 0, 2, 0], { status: '00010000' });
+ w.add(144, [s2, 1, 0, w.add(142, [1, s2, 0, arc, 2], { status: '00010000' })]);
+ // 308/408: a unit square bounded plane, twice as large and moved 100 along x.
+ const sqc = w.add(102, [4, ...lines(w, [[0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1, 0]])], { status: '00010000' });
+ const sub = w.add(108, [0, 0, 1, 0, sqc, 0, 0, 0, 0], { form: 1, status: '00010000' });
+ const def = w.add(308, [0, '3HSUB', 1, sub], { status: '00010200' });
+ w.add(408, [def, 100, 0, 0, 2]);
+ // The arc's directory entry names the transformation (field 7).
+ const file = w.toString({ name: 't', fileName: 't.igs', resolution: 1e-6 }).split('\n')
+ .map((l) => (l[72] === 'D' && Number(l.slice(73)) === arc ? l.slice(0, 48) + String(tr).padStart(8) + l.slice(56) : l)).join('\n');
+ const m = convertIges(parseIges(file));
+ expect(m.skipped).toBe(0);
+ expect(m.faces).toHaveLength(3);
+ const [bounded, round, instance] = m.faces;
+ // The 141's reversed pieces run head to tail.
+ const loop = bounded.loops[0];
+ for (let i = 0; i < loop.length; i++) expect(distance(curveEnd(loop[i]), curveStart(loop[(i + 1) % loop.length]))).toBeLessThan(1e-9);
+ // The circle turned a quarter and lifted to z = 5.
+ const c = round.loops[0][0];
+ expect(c).toMatchObject({ kind: 'circle', r: 2 });
+ expect(distance((c as { c: number[] }).c, [0, 0, 5])).toBeLessThan(1e-12);
+ expect(distance(curveStart(c), [0, 2, 5])).toBeLessThan(1e-12);
+ expect(instance.surface.kind).toBe('plane');
+ const xs = instance.loops[0].map((k) => curveStart(k)[0]).sort((a, b) => a - b);
+ expect(xs[0]).toBeCloseTo(100, 12);
+ expect(xs[3]).toBeCloseTo(102, 12);
+ });
+
+ it('reads conics and parametric splines exactly', () => {
+ const w = new IgesWriter();
+ const s2 = w.add(128, [1, 1, 1, 1, 0, 0, 1, 0, 0, -9, -9, 9, 9, -9, -9, 9, 9, 1, 1, 1, 1, -9, -9, 0, 9, -9, 0, -9, 9, 0, 9, 9, 0, -9, 9, -9, 9], { status: '00010000' });
+ // 104: the ellipse x^2/16 + y^2/4 = 1, a full turn from (4, 0).
+ const ell = w.add(104, [{ real: 1 / 16 }, 0, { real: 1 / 4 }, 0, 0, -1, 0, 4, 0, 4, 0], { form: 1, status: '00010000' });
+ w.add(144, [s2, 1, 0, w.add(142, [1, s2, 0, ell, 2], { status: '00010000' })]);
+ // 112: x = t, y = t^2 / 2 on [0, 2] in one cubic segment, and a line back.
+ const spl = w.add(112, [3, 3, 3, 1, 0, 2, 0, 1, 0, 0, 0, 0, { real: 0.5 }, 0, 0, 0, 0, 0, ...new Array(12).fill(0)], { status: '00010000' });
+ const back = w.add(110, [2, 2, 0, 0, 0, 0], { status: '00010000' });
+ w.add(144, [s2, 1, 0, w.add(142, [1, s2, 0, w.add(102, [2, spl, back], { status: '00010000' }), 2], { status: '00010000' })]);
+ const m = convert(w);
+ expect(m.faces).toHaveLength(2);
+ expect(m.faces[0].loops[0][0]).toMatchObject({ kind: 'ellipse', r1: 4, r2: 2 });
+ const sp = m.faces[1].loops[0][0];
+ expect(sp.kind).toBe('nurbs');
+ if (sp.kind === 'nurbs') for (const t of [0, 0.3, 1.1, 2]) {
+ const p = curvePoint(sp.n, t);
+ expect(p[0]).toBeCloseTo(t, 12);
+ expect(p[1]).toBeCloseTo((t * t) / 2, 12);
+ }
+ });
+
+ it('reads a bicubic parametric spline surface (114) patch by patch', () => {
+ const w = new IgesWriter();
+ // One patch on [0, 2] x [0, 1]: x = s, y = t, z = s t^2 (coefficient of s^1 t^2 is the 10th, index 9).
+ const co = (axis: number) => Array.from({ length: 16 }, (_, i) => (axis === 0 && i === 1 ? 1 : axis === 1 && i === 4 ? 1 : axis === 2 && i === 9 ? 1 : 0));
+ const patch = [...co(0), ...co(1), ...co(2)];
+ const dummy = new Array(48).fill(0);
+ w.add(114, [3, 1, 1, 1, 0, 2, 0, 1, ...patch, ...dummy, ...dummy, ...dummy]);
+ const m = convert(w);
+ expect(m.faces).toHaveLength(1);
+ const s = m.faces[0].surface;
+ expect(s.kind).toBe('nurbs');
+ if (s.kind === 'nurbs') for (const [u, v] of [[0, 0], [0.5, 0.25], [2, 1], [1.3, 0.8]]) {
+ expect(distance(surfacePoint(s.n, u, v), [u, v, u * v * v])).toBeLessThan(1e-12);
+ }
+ });
+
+ it('leaves out blanked entities unless every face is blanked', () => {
+ const square = (w: IgesWriter, status: string) => squareFace(w, (srf) => w.add(142, [1, srf, 0, w.add(102, [4, ...lines(w, [[0, 0, 0], [10, 0, 0], [10, 10, 0], [0, 10, 0]])], { status: '00010000' }), 2], { status: '00010500' }), { status });
+ const a = new IgesWriter();
+ square(a, '00000000');
+ square(a, '01000000');
+ expect(convert(a).faces).toHaveLength(1);
+ const b = new IgesWriter();
+ square(b, '01000000');
+ expect(convert(b).faces).toHaveLength(1);
+ });
+
+ it('skips a face whose B-splines have weights that are not positive, keeping the others', () => {
+ for (const bad of [0, -1]) {
+ const w = new IgesWriter();
+ squareFace(w, (srf) => w.add(142, [1, srf, 0, w.add(102, [4, ...lines(w, [[0, 0, 0], [10, 0, 0], [10, 10, 0], [0, 10, 0]])], { status: '00010000' }), 2], { status: '00010000' }));
+ // A side that is a rational quadratic with a middle weight of `bad`.
+ squareFace(w, (srf) => {
+ const side = w.add(126, [2, 2, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, { real: bad }, 1, 0, 0, 0, 5, -1, 0, 10, 0, 0, 0, 1, 0, 0, 0], { status: '00010000' });
+ const rest = lines(w, [[10, 0, 0], [10, 10, 0], [0, 10, 0], [0, 0, 0]]).slice(0, 3);
+ return w.add(142, [1, srf, 0, w.add(102, [4, side, ...rest], { status: '00010000' }), 2], { status: '00010000' });
+ });
+ // A surface with a weight of `bad`.
+ const srf = w.add(128, [1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, { real: bad }, 1, 1, 0, 0, 0, 10, 0, 0, 0, 10, 0, 10, 10, 0, 0, 1, 0, 1]);
+ const m = convert(w);
+ expect(m.faces).toHaveLength(1);
+ expect(m.skipped).toBe(2);
+ expect(m.problems).toEqual([expect.stringMatching(/curve has invalid weights/), expect.stringMatching(new RegExp(`^128#${srf}: .*surface has invalid weights`))]);
+ }
+ });
+});
+
+describe('IGES with the geometry kernel', () => {
+ const revolved = (): SkEntity[] => [
+ { id: 'p0', t: 'point', x: 2, y: 0 }, { id: 'p1', t: 'point', x: 8, y: 2 }, { id: 'p2', t: 'point', x: 10, y: 10 }, { id: 'p3', t: 'point', x: 4, y: 18 }, { id: 'p4', t: 'point', x: 2, y: 12 },
+ { id: 'sp', t: 'spline', pts: ['p0', 'p1', 'p2', 'p3'] }, { id: 'l1', t: 'line', a: 'p3', b: 'p4' }, { id: 'l2', t: 'line', a: 'p4', b: 'p0' },
+ { id: 'a1', t: 'point', x: 0, y: -5 }, { id: 'a2', t: 'point', x: 0, y: 25 }, { id: 'ax', t: 'line', a: 'a1', b: 'a2', construction: true },
+ ];
+ const parts: [string, () => Promise][] = [
+ ...EXAMPLES.map((ex) => [ex.name, async () => { const d = ex.make(); return built(d.features); }] as [string, () => Promise]),
+ ['a revolved spline profile', () => built([sketch('S1', revolved()), revolve('R1', 'S1', 250)])],
+ ['an extruded spline profile', () => built([sketch('S1', revolved().slice(0, 8)), extrude('E1', 'S1', 7)])],
+ ];
+
+ for (const [name, make] of parts) {
+ it(`exports ${name} and reads it back with the same volume and faces`, async () => {
+ const b = await make();
+ const body = b.currentShapes().body!;
+ const data = b.exportIges(name);
+ const file = parseIges(text(data));
+ expect(file.global[2]).toBe(`${name.length}H${name}`);
+ const r = await importIges(text(data), name);
+ expect(r).toMatchObject({ solids: 1, sheets: 0, skipped: 0, faces: subShapes(body, 'face').length });
+ const back = await imported(r.step);
+ expect(volume(back.shape) / volume(body)).toBeCloseTo(1, 7);
+ // Planes, cylinders and the like come back as themselves.
+ const want = types(b.currentShapes().faces);
+ for (const t of ['plane', 'cylinder', 'cone', 'torus', 'sphere']) if (want.has(t)) expect(types(back.faces)).toContain(t);
+ });
+ }
+
+ it('writes each boundary twice, in model space and on the surface, and the two agree', async () => {
+ const b = await built(EXAMPLES[1].make().features);
+ const file = parseIges(text(b.exportIges('Flange')));
+ const all = [...file.entities.values()];
+ const cos = all.filter((e) => e.type === 142);
+ expect(all.filter((e) => e.type === 144)).toHaveLength(subShapes(b.currentShapes().body!, 'face').length);
+ // Every boundary has a parameter-space curve, preferred equally (PREF 3).
+ expect(cos.every((e) => Number(e.params[2]) > 0 && Number(e.params[4]) === 3)).toBe(true);
+ // Rebuilt from the parameter-space curves alone, the faces close into the same solid.
+ const only2d = text(b.exportIges('Flange'));
+ const m2 = convertIges(parseIges(only2d.replace(/^142,1,(\d+),(\d+),\d+,3;/gm, (all: string, srf: string, pc: string) => `142,1,${srf},${pc},0,1;`.padEnd(all.length))));
+ expect(m2.skipped).toBe(0);
+ const ref = convertIges(file);
+ // Same corner points either way.
+ m2.faces.forEach((f, i) => f.loops.forEach((l, j) => l.forEach((c, k) => {
+ const want = ref.faces[i].loops[j][k];
+ if (want) expect(distance(curveStart(c), curveStart(want))).toBeLessThan(1e-6);
+ })));
+ });
+
+ it('reads files from another IGES writer: trimmed surfaces in inches, B-rep solids, B-spline lofts and revolved splines', async () => {
+ const plate = 6000 - Math.PI * 9 * 10 - 10 * (16 - 4 * Math.PI);
+ for (const [file, vol, want] of [
+ ['plate-faces-inch.igs', plate, ['plane', 'cylinder']],
+ ['plate-brep.igs', plate, ['plane', 'cylinder']],
+ ['loft-faces.igs', 4113.199133465324, ['bspline', 'plane']],
+ ['revolve-faces.igs', 17961.866781636614, ['revolution', 'plane']],
+ ] as const) {
+ const r = await importIges(fixture(file), file);
+ expect(r, file).toMatchObject({ solids: 1, sheets: 0, skipped: 0 });
+ const back = await imported(r.step);
+ expect(volume(back.shape) / vol, file).toBeCloseTo(1, 7);
+ for (const t of want) expect(types(back.faces), file).toContain(t);
+ }
+ });
+
+ it('exports an assembly with each component as a named, coloured group', async () => {
+ const a = new AssemblyBuilder();
+ await a.build([
+ { key: 'box', features: [sketch('S1', rect(0, 0, 20, 10)), extrude('E1', 'S1', 10)], blobs: {}, quality: 0 },
+ { key: 'pin', features: [sketch('S1', circle(0, 0, 3)), extrude('E1', 'S1', 30)], blobs: {}, quality: 0 },
+ ]);
+ const item = (part: string, p: [number, number, number], name: string, color: string): AsmSceneItem => ({ part, m: placementMatrix({ p, q: [0, 0, 0, 1] }), name, color });
+ a.setScene([item('box', [0, 0, 0], 'bracket<1>', '#ff0000'), item('box', [40, 0, 0], 'bracket<2>', '#ff0000'), item('pin', [0, 0, 20], 'pin<1>', '#0080ff')]);
+ const data = a.exportIges('Assy');
+ const file = parseIges(text(data));
+ const all = [...file.entities.values()];
+ const groups = all.filter((e) => e.type === 402 && e.form === 7);
+ expect(groups).toHaveLength(3);
+ const names = all.filter((e) => e.type === 406 && e.form === 15).map((e) => e.params[1]);
+ expect(names).toEqual(['10Hbracket<1>', '10Hbracket<2>', '6Hpin<1>']);
+ // Two colours, each a 314 the faces point to.
+ const colors = all.filter((e) => e.type === 314);
+ expect(colors.map((c) => c.params.map(Number))).toEqual([[100, 0, 0], [0, 50.2, 100]]);
+ const faces = all.filter((e) => e.type === 144);
+ expect(new Set(faces.map((f) => -f.color))).toEqual(new Set(colors.map((c) => c.de)));
+ // Grouped faces are logically dependent, so readers take them once (through their group).
+ expect(faces.every((f) => f.subordinate === 2)).toBe(true);
+ const r = await importIges(text(data), 'Assy');
+ expect(r.solids).toBe(3);
+ const read = await readStep(r.step);
+ expect(subShapes(read, 'solid').reduce((s, x) => s + volume(x), 0)).toBeCloseTo(4000 + Math.PI * 9 * 30, 4);
+ });
+
+ it('exports surface bodies, which read back as surfaces', async () => {
+ const sheet: Feature[] = [
+ sketch('S2', [{ id: 'q0', t: 'point', x: -5, y: 20 }, { id: 'q1', t: 'point', x: 25, y: 20 }, { id: 'ql', t: 'line', a: 'q0', b: 'q1' }]),
+ { ...newSurfaceFeature('surfaceExtrude', 'F1', 'F1', 10), sketch: 'S2', depth: 30 } as Feature,
+ ];
+ const b = await built([sketch('S1', rect(0, 0, 20, 10)), extrude('E1', 'S1', 10), ...sheet]);
+ const r = await importIges(text(b.exportIges('Sheet')), 'Sheet');
+ expect(r).toMatchObject({ solids: 1, sheets: 1, faces: 7 });
+ });
+
+ it('reads a closed shell inside another as a hollow, not a second solid', async () => {
+ const b = await built([sketch('S1', rect(0, 0, 20, 20)), extrude('E1', 'S1', 20)]);
+ const outer = b.currentShapes().body!;
+ const oc = getOc();
+ // A hollow cube: the outer box with a smaller box cut from its middle.
+ const inner = new oc.BRepPrimAPI_MakeBox(new oc.gp_Pnt(5, 5, 5), 10, 10, 10);
+ const cutter = new oc.BRepAlgoAPI_Cut(outer.wrapped, inner.Shape(), new oc.Message_ProgressRange());
+ const hollow = { wrapped: cutter.Shape() } as Sh;
+ expect(subShapes(hollow, 'shell')).toHaveLength(2);
+ const r = await importIges(text(exportIges([{ shape: hollow }], 'Hollow')), 'Hollow');
+ expect(r.solids).toBe(1);
+ expect(volume(await readStep(r.step))).toBeCloseTo(8000 - 1000, 6);
+ // A cube floating in the hollow is a solid of its own again.
+ const core = new oc.BRepPrimAPI_MakeBox(new oc.gp_Pnt(8, 8, 8), 4, 4, 4);
+ const both = await importIges(text(exportIges([{ shape: hollow }, { shape: { wrapped: core.Shape() } as Sh }], 'Nested')), 'Nested');
+ expect(both.solids).toBe(2);
+ const solids = subShapes(await readStep(both.step), 'solid').map(volume).sort((a, b) => a - b);
+ expect(solids[0]).toBeCloseTo(64, 6);
+ expect(solids[1]).toBeCloseTo(7000, 6);
+ inner.delete();
+ cutter.delete();
+ core.delete();
+ });
+
+ it('reads a solid in the notch of another (inside its box, outside its material) as a solid of its own', async () => {
+ const u = await built([sketch('S1', polygon([[0, 0], [30, 0], [30, 30], [20, 30], [20, 10], [10, 10], [10, 30], [0, 30]])), extrude('E1', 'S1', 10)]);
+ const block = await built([sketch('S1', rect(12, 12, 18, 28)), extrude('E1', 'S1', 10)]);
+ const items = [u, block].map((b) => ({ shape: b.currentShapes().body! }));
+ const r = await importIges(text(exportIges(items, 'Notch')), 'Notch');
+ expect(r.solids).toBe(2);
+ const solids = subShapes(await readStep(r.step), 'solid').map(volume).sort((a, b) => a - b);
+ expect(solids[0]).toBeCloseTo(6 * 16 * 10, 6);
+ expect(solids[1]).toBeCloseTo((900 - 200) * 10, 6);
+ });
+
+ it('keeps the trimmed part of a B-spline surface read as a torus, whichever way its normal points', async () => {
+ // A band round the inside of a torus (R 40, r 30), half a turn: the trimmed
+ // part of a closed surface, whose other side is a valid face too.
+ const [R, r, t0, t1] = [40, 30, Math.PI - 0.4, Math.PI + 0.4];
+ const band = revolveCurve(arcCurve([R, 0, 0], [r, 0, 0], [0, 0, r], t0, t1), [0, 0, 0], [0, 0, 1], 0, Math.PI);
+ const want = Math.PI * r * (R * (t1 - t0) + r * (Math.sin(t1) - Math.sin(t0)));
+ // Transposed, the same band has its normal the other way.
+ for (const s of [band, transposeSurface(band)]) {
+ const [u0, u1, v0, v1] = surfaceDomain(s);
+ // The boundary runs counterclockwise in (u, v), as IGES has it.
+ const model = [isoCurve(s, 'u', v0), isoCurve(s, 'v', u1), reverseCurve(isoCurve(s, 'u', v1)), reverseCurve(isoCurve(s, 'v', u0))].map((curve) => ({ curve }));
+ const file = writeIges([{ faces: [{ surface: s, loops: [{ model, param: null }] }] }], { name: 'Band', fileName: 'band.igs', resolution: 1e-6 });
+ expect(convertIges(parseIges(file)).faces[0].surface.kind).toBe('torus');
+ const read = await readStep((await importIges(file, 'Band')).step);
+ const oc = getOc();
+ const p = new oc.GProp_GProps();
+ oc.BRepGProp.SurfaceProperties(read.wrapped, p, 1e-9, false);
+ expect(p.Mass() / want).toBeCloseTo(1, 6);
+ p.delete();
+ }
+ });
+
+ it('reads a part a fraction of a millimetre across with all its faces, whatever resolution its file gives', async () => {
+ // The example bracket at a thousandth of its size (60 micrometres long).
+ const b = await built(EXAMPLES[0].make().features);
+ const oc = getOc();
+ const trsf = new oc.gp_Trsf();
+ trsf.SetScale(new oc.gp_Pnt(0, 0, 0), 0.001);
+ const small = { wrapped: new oc.BRepBuilderAPI_Transform(b.currentShapes().body!.wrapped, trsf, true, false).Shape() } as Sh;
+ // A resolution of half a micrometre: about the size of its smaller edges.
+ const file = text(exportIges([{ shape: small }], 'Small')).replace(',0.000001,', ',0.000500,');
+ expect(parseIges(file).resolution).toBe(5e-4);
+ const r = await importIges(file, 'Small');
+ expect(r).toMatchObject({ solids: 1, sheets: 0, faces: subShapes(small, 'face').length });
+ expect(volume(await readStep(r.step)) / volume(small)).toBeCloseTo(1, 6);
+ trsf.delete();
+ });
+
+ it('leaves out faces with no area rather than reading them as surfaces or solids of their own', async () => {
+ // Shelling a smooth loft outwards leaves four sliver faces of no area where the rounds meet the top.
+ const b = await built([
+ sketch('A', rect(-10, -10, 10, 10)),
+ { id: 'P1', name: 'P1', type: 'plane', ref: { kind: 'base', plane: 'front' }, offset: 20, flip: false },
+ sketch('B', circle(0, 0, 5), { kind: 'feature', id: 'P1' }),
+ { id: 'L', name: 'L', type: 'loft', profiles: ['A', 'B'], cut: false, ruled: false },
+ { id: 'SH', name: 'SH', type: 'shell', faces: [], thickness: 1, outward: true },
+ ]);
+ const body = b.currentShapes().body!;
+ const r = await importIges(text(b.exportIges('Shelled')), 'Shelled');
+ expect(r).toMatchObject({ solids: 1, sheets: 0, faces: subShapes(body, 'face').length - 4 });
+ expect(volume(await readStep(r.step)) / volume(body)).toBeCloseTo(1, 4);
+ }, 60_000);
+
+ it('says what is wrong with a file it cannot import', async () => {
+ await expect(importIges('not an IGES file', 'x')).rejects.toThrow(/not an IGES file/);
+ const w = new IgesWriter();
+ w.add(110, [0, 0, 0, 1, 1, 1]);
+ await expect(importIges(w.toString({ name: 'x', fileName: 'x.igs', resolution: 1e-6 }), 'x')).rejects.toThrow(/only curves or points/);
+ const empty = new ModelBuilder();
+ expect(() => empty.exportIges('x')).toThrow(/no geometry/);
+ });
+
+ it('writes the same file twice for the same part and date', async () => {
+ const b = await built([sketch('S1', rect(0, 0, 10, 10)), extrude('E1', 'S1', 5)]);
+ const date = new Date(Date.UTC(2026, 10, 30));
+ const body = b.currentShapes().body!;
+ expect(text(exportIges([{ shape: body }], 'A', { date }))).toBe(text(exportIges([{ shape: body }], 'A', { date })));
+ // writeIges directly: a face without loops is left out rather than written unbounded.
+ expect(writeIges([{ faces: [] }], { name: 'e', fileName: 'e.igs', resolution: 1e-6, date })).toContain('T0000001');
+ });
+});