@nekocad/occt-wasm 5.1.1-nekocad.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,484 @@
1
+ <div align="center">
2
+
3
+ # occt-wasm
4
+
5
+ [![npm](https://img.shields.io/npm/v/occt-wasm)](https://www.npmjs.com/package/occt-wasm)
6
+ [![Crates.io](https://img.shields.io/crates/v/occt-wasm.svg)](https://crates.io/crates/occt-wasm)
7
+ [![CI](https://github.com/andymai/occt-wasm/actions/workflows/ci.yml/badge.svg)](https://github.com/andymai/occt-wasm/actions/workflows/ci.yml)
8
+ [![Last release](https://img.shields.io/github/release-date/andymai/occt-wasm?label=last%20release)](https://github.com/andymai/occt-wasm/releases)
9
+ [![Commit activity](https://img.shields.io/github/commit-activity/m/andymai/occt-wasm?label=commits%2Fmonth)](https://github.com/andymai/occt-wasm/commits/main)
10
+ [![License](https://img.shields.io/badge/tooling-MIT%20OR%20Apache--2.0-blue.svg)](#license) [![WASM License](https://img.shields.io/badge/wasm%20output-LGPL--2.1--only-blue.svg)](#license)
11
+
12
+ [OpenCascade](https://github.com/Open-Cascade-SAS/OCCT) V8 compiled to WebAssembly with a clean TypeScript API.
13
+
14
+ Smaller bundles, branded types, arena-based memory, and modern tooling.
15
+
16
+ </div>
17
+
18
+ > **Looking for a higher-level CAD library?** [brepjs](https://github.com/andymai/brepjs) builds on occt-wasm with a friendlier API for parametric modeling, sketching, and production CAD applications. Use occt-wasm directly when you need full control over OCCT operations.
19
+
20
+ ## Highlights
21
+
22
+ - **~4.5 MB brotli** -- roughly 2x smaller than opencascade.js
23
+ - **Comprehensive API** -- primitives, booleans, sweeps, XCAF assemblies, curves, surfaces, STEP/STL/glTF/BREP I/O, topology, shape evolution tracking
24
+ - **Arena-based API** -- u32 shape handles, no manual `.delete()`, `Symbol.dispose` support
25
+ - **TypeScript-first** -- branded `ShapeHandle`, union types for shapes/surfaces/curves, structured returns
26
+ - **Structured error handling** -- `OcctErrorCode` enum for programmatic `switch/case` instead of string parsing
27
+ - **Web Worker support** -- `OcctWorker` class for off-main-thread CAD operations via [Comlink](https://github.com/GoogleChromeLabs/comlink)
28
+ - **Modern browser targets** -- WASM SIMD, tail calls, wasm-exceptions
29
+
30
+ ## Scope
31
+
32
+ To set expectations, this library deliberately does not:
33
+
34
+ - **Provide a higher-level CAD modeling API** — parametric sketching, constraints, feature trees, and ergonomic modeling belong in [brepjs](https://github.com/andymai/brepjs), which wraps occt-wasm for that purpose
35
+ - **Manage memory automatically beyond arena handles** — shapes are freed when the kernel is disposed or you call `release()`; there is no per-shape garbage collection
36
+ - **Support non-WASM-SIMD browsers** — the build requires WASM SIMD (baseline `-msimd128`), tail calls, and wasm exceptions, so it needs a recent engine (see [Browser Compatibility](#browser-compatibility)). Relaxed-SIMD is intentionally not used: some Safari/iOS WebKit builds fail to compile relaxed-SIMD modules, and it made geometry non-reproducible across CPUs
37
+ - **Include OCCT visualization or display modules** — TKV3d, TKHLR (except the HLR facade), and the AIS interactive context are excluded; bring your own renderer (Three.js, Babylon.js, etc.)
38
+ - **Support IGES import/export** -- TKDEIGES is excluded from the link; use STEP for interchange
39
+
40
+ ## Install
41
+
42
+ ```bash
43
+ npm install occt-wasm
44
+ ```
45
+
46
+ ## Quick Start
47
+
48
+ ```typescript check
49
+ import { OcctKernel } from "occt-wasm";
50
+
51
+ // Recommended: deterministic cleanup via Symbol.dispose
52
+ {
53
+ using kernel = await OcctKernel.init();
54
+
55
+ // Primitives
56
+ const box = kernel.makeBox(20, 20, 20);
57
+ const cyl = kernel.makeCylinder(8, 30);
58
+
59
+ // Modeling -- fillet takes a solid, so round the box before combining
60
+ const edges = kernel.getSubShapes(box, "edge");
61
+ const filleted = kernel.fillet(box, edges.slice(0, 4), 2.0);
62
+
63
+ // Booleans
64
+ const fused = kernel.fuse(filleted, cyl);
65
+
66
+ // Tessellation -> Three.js / Babylon.js
67
+ const mesh = kernel.tessellate(fused);
68
+ // mesh.positions (Float32Array), mesh.normals, mesh.indices
69
+
70
+ // STEP I/O
71
+ const step = kernel.exportStep(fused);
72
+ const reimported = kernel.importStep(step);
73
+
74
+ // Query
75
+ const vol = kernel.getVolume(fused);
76
+ const bbox = kernel.getBoundingBox(fused);
77
+ const com = kernel.getCenterOfMass(fused);
78
+
79
+ // kernel is disposed at end of block
80
+ }
81
+ ```
82
+
83
+ > **Boolean results are compounds.** OCCT's `BRepAlgoAPI` operations wrap their
84
+ > output in a `TopoDS_Compound` — a boolean can produce several disjoint solids.
85
+ > The operations that downcast to a solid (`fillet`, `chamfer`, `filletVariable`,
86
+ > `filletBatch`, `healSolid`) reject one, so unwrap first:
87
+ >
88
+ > ```typescript check kernel,fused
89
+ > const [solid] = kernel.getSubShapes(fused, "solid");
90
+ > if (!solid) throw new Error("boolean produced no solid");
91
+ > ```
92
+ >
93
+ > **Not every edge is filletable.** Seam and degenerate edges are not, so on a
94
+ > shape you didn't build yourself, select edges by geometry rather than by index.
95
+ > The `slice(0, 4)` above is safe only because all 12 edges of a plain box round
96
+ > cleanly — on the box-plus-cylinder fusion, only 13 of 20 edges do.
97
+
98
+ ## Rust Crate
99
+
100
+ The same OCCT WASM is available as a [Rust crate](https://crates.io/crates/occt-wasm) for native targets (servers, CLIs, build scripts) — no C++ toolchain required:
101
+
102
+ ```toml
103
+ [dependencies]
104
+ occt-wasm = "3"
105
+ ```
106
+
107
+ ```rust
108
+ use occt_wasm::OcctKernel;
109
+
110
+ let mut kernel = OcctKernel::new()?;
111
+ let box_shape = kernel.make_box(10.0, 20.0, 30.0)?;
112
+ let sphere = kernel.make_sphere(8.0)?;
113
+ let fused = kernel.fuse(box_shape, sphere)?;
114
+ let mesh = kernel.tessellate(fused, 0.1, 0.5)?;
115
+ let step = kernel.export_step(fused)?;
116
+ ```
117
+
118
+ The crate embeds a brotli-compressed WASM binary (~4.7 MB) and runs it via [wasmtime](https://wasmtime.dev/). Same 170+ facade methods as the TS API. See [`crate/README.md`](./crate/README.md) and [docs.rs/occt-wasm](https://docs.rs/occt-wasm) for full details.
119
+
120
+ ## Initialization
121
+
122
+ By default, `OcctKernel.init()` auto-locates the `.wasm` file next to the JS module. You can also provide explicit paths or pre-loaded binaries:
123
+
124
+ ```typescript check
125
+ import { OcctKernel } from "occt-wasm";
126
+
127
+ // Auto-detect (browser, Node.js, or Worker):
128
+ const kernel = await OcctKernel.init();
129
+
130
+ // ...or point at an explicit URL / path:
131
+ await OcctKernel.init({ wasm: "/assets/occt-wasm.wasm" });
132
+
133
+ // ...or hand over a pre-fetched binary, skipping the fetch:
134
+ const binary = await fetch("/occt-wasm.wasm").then((r) => r.arrayBuffer());
135
+ await OcctKernel.init({ wasm: binary });
136
+ await OcctKernel.init({ wasm: new Uint8Array(binary) });
137
+ ```
138
+
139
+ ## Error Handling
140
+
141
+ All errors are instances of `OcctError` with a structured `code` field for programmatic handling:
142
+
143
+ ```typescript check kernel,a,b
144
+ import { OcctError, OcctErrorCode } from "occt-wasm";
145
+
146
+ try {
147
+ kernel.fuse(a, b);
148
+ } catch (e) {
149
+ if (e instanceof OcctError) {
150
+ switch (e.code) {
151
+ case OcctErrorCode.BooleanFailed:
152
+ // retry with simpler geometry
153
+ break;
154
+ case OcctErrorCode.InvalidShapeId:
155
+ // shape was already released
156
+ break;
157
+ case OcctErrorCode.KernelError:
158
+ // OCCT internal error (Standard_Failure)
159
+ console.error(e.message);
160
+ break;
161
+ }
162
+ }
163
+ }
164
+ ```
165
+
166
+ Available error codes:
167
+
168
+ | Code | When |
169
+ | -------------------- | ----------------------------------------------- |
170
+ | `ConstructionFailed` | `Build()`/`IsDone()` returned false |
171
+ | `BooleanFailed` | Boolean operation (fuse/cut/common/etc.) failed |
172
+ | `InvalidShapeId` | Shape ID not found in the arena |
173
+ | `InvalidLabelId` | XCAF label ID not found |
174
+ | `TessellationFailed` | Meshing operation failed |
175
+ | `ImportExportFailed` | STEP/STL/BREP I/O error |
176
+ | `HealingFailed` | Shape repair failed |
177
+ | `DocumentClosed` | Operation on a closed XCAF document |
178
+ | `KernelError` | OCCT `Standard_Failure` (unclassified) |
179
+ | `Unknown` | Error from outside the kernel |
180
+
181
+ > **`OcctWorker` is the exception.** Comlink serializes a thrown error down to
182
+ > `{ message, name, stack }`, so an error crossing the worker boundary arrives
183
+ > as a plain `Error`: the message survives intact, but `code`, `operation`, and
184
+ > `instanceof OcctError` do not. Match on `e.message` there, or do the
185
+ > `switch (e.code)` inside the worker.
186
+
187
+ ## Named Enums
188
+
189
+ Sweep, offset, and boolean operations use self-documenting enums instead of opaque numbers:
190
+
191
+ ```typescript check kernel,profile,spine,wire,base,tool1,tool2
192
+ import { TransitionMode, JoinType, BooleanOp } from "occt-wasm";
193
+
194
+ // Sweep with round-corner transitions
195
+ kernel.sweep(profile, spine, TransitionMode.RoundCorner);
196
+
197
+ // Offset wire with arc joins
198
+ kernel.offsetWire2D(wire, 2.0, JoinType.Arc);
199
+
200
+ // Boolean pipeline
201
+ kernel.booleanPipeline(base, [BooleanOp.Cut, BooleanOp.Fuse], [tool1, tool2]);
202
+ ```
203
+
204
+ Numeric values (0, 1, 2) are still accepted for backwards compatibility.
205
+
206
+ ## Type Predicates
207
+
208
+ Convenience methods for checking shape topology:
209
+
210
+ ```typescript check kernel,shape
211
+ if (kernel.isSolid(shape)) {
212
+ /* ... */
213
+ }
214
+ if (kernel.isFace(shape)) {
215
+ /* ... */
216
+ }
217
+ if (kernel.isEdge(shape)) {
218
+ /* ... */
219
+ }
220
+ if (kernel.isWire(shape)) {
221
+ /* ... */
222
+ }
223
+ if (kernel.isVertex(shape)) {
224
+ /* ... */
225
+ }
226
+ if (kernel.isShell(shape)) {
227
+ /* ... */
228
+ }
229
+ if (kernel.isCompound(shape)) {
230
+ /* ... */
231
+ }
232
+ ```
233
+
234
+ ## Web Workers
235
+
236
+ For browser apps, heavy CAD operations can block the main thread. `OcctWorker` runs a full kernel in a Web Worker with the same API:
237
+
238
+ ```typescript check edge
239
+ import { OcctWorker } from "occt-wasm/worker";
240
+
241
+ // Spawn a worker with its own kernel
242
+ const worker = await OcctWorker.spawn({ wasm: "/occt-wasm.wasm" });
243
+
244
+ // Same API, every call returns a Promise
245
+ const box = await worker.makeBox(10, 20, 30);
246
+ const cyl = await worker.makeCylinder(5, 40);
247
+ const fused = await worker.fuse(box, cyl);
248
+ const mesh = await worker.tessellate(fused);
249
+ console.log(`${mesh.triangleCount} triangles`);
250
+
251
+ // Access the full kernel via .kernel for less common methods
252
+ const nurbs = await worker.kernel.getNurbsCurveData(edge);
253
+
254
+ // Clean up
255
+ worker.terminate();
256
+ ```
257
+
258
+ The worker helper uses [Comlink](https://github.com/GoogleChromeLabs/comlink) (~1.2 KB gzipped) for transparent RPC. Each worker has its own WASM instance and arena -- shape handles are local to the worker.
259
+
260
+ ## XCAF Assemblies
261
+
262
+ Create assembly documents with colors, names, and component hierarchies:
263
+
264
+ ```typescript check kernel,box,gear,stepData
265
+ // Factory method auto-injects Emscripten FS for glTF export
266
+ const doc = kernel.createXCAFDocument();
267
+
268
+ const housing = doc.addShape(box, { name: "housing", color: [0.8, 0.2, 0.1] });
269
+ doc.addChild(housing, gear, {
270
+ name: "gear-1",
271
+ location: { tx: 10, tz: 5 },
272
+ color: [0.5, 0.5, 0.5],
273
+ });
274
+
275
+ // Export
276
+ const step = doc.exportSTEP(); // preserves colors/names
277
+ const glb = doc.exportGLTF(); // no need to pass FS manually
278
+ doc.close();
279
+
280
+ // Import with preserved metadata
281
+ const imported = kernel.importXCAFFromSTEP(stepData);
282
+ ```
283
+
284
+ Walking an imported assembly: each component is a placed reference to a prototype label (a part or sub-assembly). Resolve it with `getReferredLabel` to reach the prototype's name, named sub-shapes and children. To author the same structure, add a compound with `doc.addShape(compound, { assembly: true })`.
285
+
286
+ ```typescript check doc
287
+ import type { LabelTag } from "occt-wasm";
288
+
289
+ function walk(label: LabelTag, depth = 0): void {
290
+ const info = doc.getLabelInfo(label);
291
+ console.log(`${" ".repeat(depth)}${info.name}`);
292
+ const proto = doc.getReferredLabel(label) ?? label;
293
+ for (const sub of doc.getSubShapes(proto)) {
294
+ console.log(`${" ".repeat(depth + 1)}(${doc.getLabelInfo(sub).name})`);
295
+ }
296
+ for (const child of doc.getChildren(proto)) walk(child, depth + 1);
297
+ }
298
+ for (const root of doc.getRoots()) walk(root);
299
+ ```
300
+
301
+ `getLocation(label)` returns a component's placement as a 3x4 matrix in the layout `kernel.transform` accepts, so a prototype's geometry can be tessellated once and instanced per component.
302
+
303
+ ## Bundler Configuration
304
+
305
+ ### Vite
306
+
307
+ ```typescript
308
+ // vite.config.ts
309
+ export default defineConfig({
310
+ optimizeDeps: {
311
+ exclude: ["occt-wasm"], // Don't pre-bundle WASM
312
+ },
313
+ build: {
314
+ target: "esnext", // Required for WASM features
315
+ },
316
+ });
317
+ ```
318
+
319
+ ### Webpack 5
320
+
321
+ ```javascript
322
+ // webpack.config.js
323
+ module.exports = {
324
+ experiments: { asyncWebAssembly: true },
325
+ module: {
326
+ rules: [{ test: /\.wasm$/, type: "asset/resource" }],
327
+ },
328
+ };
329
+ ```
330
+
331
+ Webpack bundles the Emscripten glue and emits `occt-wasm.wasm` as a hashed
332
+ asset, rewriting the URL it is loaded from. No manual copy step is needed, and
333
+ `OcctKernel.init()` finds the binary without a `wasm` option.
334
+
335
+ ### Next.js
336
+
337
+ No configuration needed, under either Turbopack or webpack. Both emit the
338
+ `.wasm` into `_next/static` and rewrite the URL. Initialize from a client
339
+ component (`"use client"`) so the kernel loads in the browser rather than
340
+ during SSR:
341
+
342
+ ```javascript
343
+ "use client";
344
+ import { useEffect } from "react";
345
+
346
+ export default function Viewer() {
347
+ useEffect(() => {
348
+ (async () => {
349
+ const { OcctKernel } = await import("occt-wasm");
350
+ const kernel = await OcctKernel.init();
351
+ // ...
352
+ })();
353
+ }, []);
354
+ }
355
+ ```
356
+
357
+ ### Node.js
358
+
359
+ ```typescript check
360
+ // Works out of the box with Node.js 18+
361
+ import { OcctKernel } from "occt-wasm";
362
+ const kernel = await OcctKernel.init();
363
+ ```
364
+
365
+ ## API Reference
366
+
367
+ Generate full docs locally: `cd ts && npm run docs` (TypeDoc output).
368
+
369
+ | Category | What's covered |
370
+ | ---------------- | -------------------------------------------------------------------------------------------------------------- |
371
+ | **Primitives** | Box, cylinder, sphere, cone, torus, ellipsoid, rectangle, half-space |
372
+ | **Booleans** | Fuse, cut, common, intersect, section + multi-shape variants, intersection cells |
373
+ | **Modeling** | Extrude, revolve, fillet, chamfer, shell, offset, draft |
374
+ | **Sweeps** | Pipe, loft, sweep, oriented sweep (fixed/Frenet/up-axis/auxiliary), draft prism, extrusion laws |
375
+ | **Construction** | Vertices, edges (line/arc/circle/ellipse/bezier/helix), wires, faces, solids, compounds, sewing |
376
+ | **Transforms** | Translate, rotate, scale, mirror, align to bounding box, 3x4 matrix, linear/circular patterns |
377
+ | **Topology** | Shape type queries, type predicates, sub-shape extraction, adjacency, hash codes |
378
+ | **Tessellation** | Triangle meshes (absolute or relative deflection), wireframe polylines, per-face groups, batched meshing |
379
+ | **I/O** | STEP, STL (ASCII + binary), BREP (text + binary) import/export |
380
+ | **Query** | Bounding box, volume, surface area, length, center of mass, inertia tensor, point-in-solid, curvature |
381
+ | **Surfaces** | Type, normal, UV bounds, point classification, B-spline construction |
382
+ | **Curves** | Type, point/tangent eval, parameters, NURBS data, interpolation (incl. clamped tangents), project point |
383
+ | **Projection** | Hidden line removal (HLR), multiview SVG render (Front/Top/Right/Iso) |
384
+ | **Modifiers** | Thicken, defeature, reverse, simplify, variable fillet, 2D wire offset |
385
+ | **Evolution** | Face-tracking history for translate, fuse, cut, fillet, rotate, mirror, scale, chamfer, shell, offset, thicken |
386
+ | **XCAF** | Assembly documents with colors, names, component hierarchies, STEP/glTF export |
387
+ | **Healing** | Fix shape, unify domain, heal solid/face/wire, fix orientations, remove degenerate edges |
388
+ | **Batch** | Multi-shape translate, chained boolean pipeline |
389
+
390
+ ## Architecture
391
+
392
+ ```
393
+ OCCT V8.0.1 C++ (git submodule)
394
+ -> emcmake cmake (static libs)
395
+ -> C++ facade (OcctKernel class, arena-based u32 IDs)
396
+ -> Embind bindings
397
+ -> emcc link (-O3, -flto, -fwasm-exceptions, SIMD) -> .wasm
398
+ -> wasm-opt -O4 --converge --gufa -> dist/
399
+ ```
400
+
401
+ Built with Rust xtask (`cargo xtask build`), tested with Vitest.
402
+
403
+ ## Size & Performance
404
+
405
+ Compared against other OCCT-to-WASM builds (all include STEP, XCAF, glTF):
406
+
407
+ | Build | brotli |
408
+ | ------------------ | ------- |
409
+ | **occt-wasm** | ~4.5 MB |
410
+ | opencascade.js | ~9 MB |
411
+ | brepjs-opencascade | ~5 MB |
412
+
413
+ Run benchmarks locally: `npx tsx test/benchmark.ts`
414
+
415
+ ## Development
416
+
417
+ ### Building from Source
418
+
419
+ ```bash
420
+ # Prerequisites: Rust 1.95+, emsdk 5.0.3
421
+ git clone --recurse-submodules https://github.com/andymai/occt-wasm
422
+ cd occt-wasm
423
+ npm install && cd ts && npm install && cd ..
424
+
425
+ cargo xtask build # Build OCCT + facade -> WASM
426
+ cargo xtask test # Run tests
427
+
428
+ # View the Three.js example
429
+ node scripts/static-server.mjs
430
+ # Open http://localhost:3000/examples/three-js/
431
+ ```
432
+
433
+ ### Docker Build
434
+
435
+ No local emsdk or Rust needed -- everything runs in the container.
436
+
437
+ ```bash
438
+ npm run docker:build # Build image (OCCT layer cached after first run)
439
+ npm run docker:dist # Build + copy dist/ artifacts to host
440
+ ```
441
+
442
+ ## Browser Compatibility
443
+
444
+ occt-wasm requires modern browsers with WASM SIMD, tail calls, and exception
445
+ handling. WASM **tail calls** are the newest and therefore binding requirement —
446
+ they gate the minimum versions below. The versions listed are the lowest
447
+ combinations verified to load the kernel:
448
+
449
+ | Browser | Minimum (verified) | Notes |
450
+ | ------- | ------------------ | ------------------------------------------- |
451
+ | Chrome | 114+ | Tail calls landed in 112; 114 is verified |
452
+ | Edge | 114+ | Same engine as Chrome |
453
+ | Safari | 17.2+ | Earliest WebKit verified to load the kernel |
454
+ | Firefox | 121+ | Tail calls shipped in 121; 146 is verified |
455
+
456
+ Node.js 22+ is recommended (tail calls via V8). Node.js 18+ works if your V8 version supports the required WASM features.
457
+
458
+ ## Known Limitations
459
+
460
+ These are upstream OCCT V8.0.1 issues, not occt-wasm bugs:
461
+
462
+ - **IGES** -- TKDEIGES excluded from link; no IGES import/export
463
+ - **Zero-length extrusion** -- WASM exception escapes JS catch boundary (1 test skip)
464
+ - **Single WASM thread** -- each kernel instance is single-threaded; use `OcctWorker` (see above) to move work off the main thread
465
+
466
+ These will be addressed as upstream OCCT and browser support improve.
467
+
468
+ OCCT V8.0.1 (2026-07) resolved several upstream hangs and crashes that
469
+ affected modeling here: an infinite-loop guard in the boolean section
470
+ algorithm, crash guards in chamfer construction (`ChFi3d_Builder`) and
471
+ `BRep_Tool::CurveOnPlane`, null-pcurve guards in `UnifySameDomain`, and
472
+ an infinite-loop guard in the STEP writer.
473
+
474
+ ## Contributing
475
+
476
+ This project is open source. Bug reports and feature requests are welcome via GitHub Issues. For pull requests, please open an issue first to discuss the change.
477
+
478
+ ## License
479
+
480
+ **Build tooling** (xtask, scripts, TypeScript wrapper): MIT OR Apache-2.0
481
+
482
+ **Compiled WASM output**: LGPL-2.1-only (inherits from [OCCT](https://dev.opencascade.org/resources/download))
483
+
484
+ The LGPL requires that end users can replace the LGPL component. For web applications, this is satisfied by loading the `.wasm` file from a URL (which users can override via `OcctKernel.init({ wasm: '...' })`). If you ship a desktop app with the WASM embedded, consult the [LGPL-2.1 FAQ](https://www.gnu.org/licenses/old-licenses/lgpl-2.1.html).