brepjs 18.36.0 → 18.37.0

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/dist/brepjs.cjs CHANGED
@@ -159,7 +159,13 @@ function initVoxel(engine, id = "voxel") {
159
159
  }
160
160
  //#endregion
161
161
  //#region src/voxel/signFns.ts
162
- function validateInputs(mesh, queries) {
162
+ /**
163
+ * Validate a triangle-soup mesh before it crosses into wasm: flat-xyz vertices,
164
+ * triangle-multiple indices, and every index in range. An out-of-range index
165
+ * would otherwise panic in Rust and surface as a wasm trap, escaping the Result
166
+ * contract — so it must be rejected here.
167
+ */
168
+ function validateMesh(mesh) {
163
169
  if (mesh.vertices.length % 3 !== 0) return require_errors.validationError("VOXEL_INVALID_MESH", "mesh.vertices length must be a multiple of 3 (flat xyz).");
164
170
  if (mesh.triangles.length % 3 !== 0) return require_errors.validationError("VOXEL_INVALID_MESH", "mesh.triangles length must be a multiple of 3.");
165
171
  const vertexCount = mesh.vertices.length / 3;
@@ -167,9 +173,15 @@ function validateInputs(mesh, queries) {
167
173
  const idx = mesh.triangles[i];
168
174
  if (idx === void 0 || idx >= vertexCount) return require_errors.validationError("VOXEL_INVALID_TRIANGLE_INDEX", `triangle index ${idx} at position ${i} is out of range for ${vertexCount} vertices.`);
169
175
  }
176
+ return null;
177
+ }
178
+ function validateInputs(mesh, queries) {
179
+ const meshInvalid = validateMesh(mesh);
180
+ if (meshInvalid) return meshInvalid;
170
181
  if (queries.length % 3 !== 0) return require_errors.validationError("VOXEL_INVALID_QUERIES", "queries length must be a multiple of 3 (flat xyz).");
171
182
  return null;
172
183
  }
184
+ /** Resolve a registered voxel engine, mapping an unregistered id to an error. */
173
185
  function resolveEngine(id) {
174
186
  try {
175
187
  return require_errors.ok(getVoxel(id));
@@ -205,6 +217,53 @@ function pointsInside(mesh, queries, id) {
205
217
  return require_errors.ok(Array.from(flags, (flag) => flag === 1));
206
218
  }
207
219
  //#endregion
220
+ //#region src/voxel/repairFns.ts
221
+ var DEFAULT_RESOLUTION = 48;
222
+ var DEFAULT_PADDING = 2;
223
+ /**
224
+ * Repair a (possibly non-watertight) triangle-soup mesh into a closed surface:
225
+ * voxelize an FWN-signed SDF, then Surface-Nets contour it back to triangles.
226
+ *
227
+ * The FWN sign classifies inside/outside even on holey input, so a mesh with
228
+ * missing faces still yields a watertight result (ADR-0013 §11). Returns a
229
+ * {@link KernelMeshResult} in world coordinates (a single face group, no UVs).
230
+ */
231
+ function repairMesh(mesh, opts, id) {
232
+ const invalid = validateMesh(mesh);
233
+ if (invalid) return require_errors.err(invalid);
234
+ if (mesh.vertices.length === 0 || mesh.triangles.length === 0) return require_errors.err(require_errors.validationError("VOXEL_EMPTY_MESH", "repairMesh requires a non-empty triangle mesh."));
235
+ const resolution = opts?.resolution ?? DEFAULT_RESOLUTION;
236
+ const padding = opts?.padding ?? DEFAULT_PADDING;
237
+ if (!Number.isInteger(resolution) || resolution < 1) return require_errors.err(require_errors.validationError("VOXEL_INVALID_RESOLUTION", "resolution must be an integer >= 1."));
238
+ if (!Number.isInteger(padding) || padding < 1) return require_errors.err(require_errors.validationError("VOXEL_INVALID_PADDING", "padding must be an integer >= 1."));
239
+ const engine = resolveEngine(id);
240
+ if (require_errors.isErr(engine)) return engine;
241
+ try {
242
+ try {
243
+ var _usingCtx$4 = require_shapeTypes._usingCtx();
244
+ const repaired = _usingCtx$4.u(engine.value.repair_mesh(mesh.vertices, mesh.triangles, resolution, padding));
245
+ const vertexCount = repaired.positions.length / 3;
246
+ return require_errors.ok({
247
+ vertices: repaired.positions,
248
+ normals: repaired.normals,
249
+ triangles: repaired.indices,
250
+ uvs: new Float32Array(vertexCount * 2),
251
+ faceGroups: [{
252
+ start: 0,
253
+ count: repaired.indices.length / 3,
254
+ faceHash: 0
255
+ }]
256
+ });
257
+ } catch (_) {
258
+ _usingCtx$4.e = _;
259
+ } finally {
260
+ _usingCtx$4.d();
261
+ }
262
+ } catch (cause) {
263
+ return require_errors.err(require_errors.computationError("VOXEL_REPAIR_FAILED", cause instanceof Error ? cause.message : "voxel repair failed (grid too large?).", cause));
264
+ }
265
+ }
266
+ //#endregion
208
267
  //#region src/core/kernelBoundary.ts
209
268
  /** Convert Vec3 to a kernel 3D vector. Caller must call .delete() when done. */
210
269
  function toKernelVec(v) {
@@ -5666,6 +5725,7 @@ exports.registerVoxel = registerVoxel;
5666
5725
  exports.rejectAll = require_workerHandler.rejectAll;
5667
5726
  exports.removeChild = require_historyFns.removeChild;
5668
5727
  exports.removeHolesFromFace = require_faceFns.removeHolesFromFace;
5728
+ exports.repairMesh = repairMesh;
5669
5729
  exports.replayFrom = require_historyFns.replayFrom;
5670
5730
  exports.replayHistory = require_historyFns.replayHistory;
5671
5731
  exports.resetDisposalStats = require_shapeTypes.resetDisposalStats;
package/dist/brepjs.js CHANGED
@@ -170,7 +170,13 @@ function initVoxel(engine, id = "voxel") {
170
170
  }
171
171
  //#endregion
172
172
  //#region src/voxel/signFns.ts
173
- function validateInputs(mesh, queries) {
173
+ /**
174
+ * Validate a triangle-soup mesh before it crosses into wasm: flat-xyz vertices,
175
+ * triangle-multiple indices, and every index in range. An out-of-range index
176
+ * would otherwise panic in Rust and surface as a wasm trap, escaping the Result
177
+ * contract — so it must be rejected here.
178
+ */
179
+ function validateMesh(mesh) {
174
180
  if (mesh.vertices.length % 3 !== 0) return validationError("VOXEL_INVALID_MESH", "mesh.vertices length must be a multiple of 3 (flat xyz).");
175
181
  if (mesh.triangles.length % 3 !== 0) return validationError("VOXEL_INVALID_MESH", "mesh.triangles length must be a multiple of 3.");
176
182
  const vertexCount = mesh.vertices.length / 3;
@@ -178,9 +184,15 @@ function validateInputs(mesh, queries) {
178
184
  const idx = mesh.triangles[i];
179
185
  if (idx === void 0 || idx >= vertexCount) return validationError("VOXEL_INVALID_TRIANGLE_INDEX", `triangle index ${idx} at position ${i} is out of range for ${vertexCount} vertices.`);
180
186
  }
187
+ return null;
188
+ }
189
+ function validateInputs(mesh, queries) {
190
+ const meshInvalid = validateMesh(mesh);
191
+ if (meshInvalid) return meshInvalid;
181
192
  if (queries.length % 3 !== 0) return validationError("VOXEL_INVALID_QUERIES", "queries length must be a multiple of 3 (flat xyz).");
182
193
  return null;
183
194
  }
195
+ /** Resolve a registered voxel engine, mapping an unregistered id to an error. */
184
196
  function resolveEngine(id) {
185
197
  try {
186
198
  return ok(getVoxel(id));
@@ -216,6 +228,53 @@ function pointsInside(mesh, queries, id) {
216
228
  return ok(Array.from(flags, (flag) => flag === 1));
217
229
  }
218
230
  //#endregion
231
+ //#region src/voxel/repairFns.ts
232
+ var DEFAULT_RESOLUTION = 48;
233
+ var DEFAULT_PADDING = 2;
234
+ /**
235
+ * Repair a (possibly non-watertight) triangle-soup mesh into a closed surface:
236
+ * voxelize an FWN-signed SDF, then Surface-Nets contour it back to triangles.
237
+ *
238
+ * The FWN sign classifies inside/outside even on holey input, so a mesh with
239
+ * missing faces still yields a watertight result (ADR-0013 §11). Returns a
240
+ * {@link KernelMeshResult} in world coordinates (a single face group, no UVs).
241
+ */
242
+ function repairMesh(mesh, opts, id) {
243
+ const invalid = validateMesh(mesh);
244
+ if (invalid) return err(invalid);
245
+ if (mesh.vertices.length === 0 || mesh.triangles.length === 0) return err(validationError("VOXEL_EMPTY_MESH", "repairMesh requires a non-empty triangle mesh."));
246
+ const resolution = opts?.resolution ?? DEFAULT_RESOLUTION;
247
+ const padding = opts?.padding ?? DEFAULT_PADDING;
248
+ if (!Number.isInteger(resolution) || resolution < 1) return err(validationError("VOXEL_INVALID_RESOLUTION", "resolution must be an integer >= 1."));
249
+ if (!Number.isInteger(padding) || padding < 1) return err(validationError("VOXEL_INVALID_PADDING", "padding must be an integer >= 1."));
250
+ const engine = resolveEngine(id);
251
+ if (isErr(engine)) return engine;
252
+ try {
253
+ try {
254
+ var _usingCtx$4 = _usingCtx();
255
+ const repaired = _usingCtx$4.u(engine.value.repair_mesh(mesh.vertices, mesh.triangles, resolution, padding));
256
+ const vertexCount = repaired.positions.length / 3;
257
+ return ok({
258
+ vertices: repaired.positions,
259
+ normals: repaired.normals,
260
+ triangles: repaired.indices,
261
+ uvs: new Float32Array(vertexCount * 2),
262
+ faceGroups: [{
263
+ start: 0,
264
+ count: repaired.indices.length / 3,
265
+ faceHash: 0
266
+ }]
267
+ });
268
+ } catch (_) {
269
+ _usingCtx$4.e = _;
270
+ } finally {
271
+ _usingCtx$4.d();
272
+ }
273
+ } catch (cause) {
274
+ return err(computationError("VOXEL_REPAIR_FAILED", cause instanceof Error ? cause.message : "voxel repair failed (grid too large?).", cause));
275
+ }
276
+ }
277
+ //#endregion
219
278
  //#region src/core/kernelBoundary.ts
220
279
  /** Convert Vec3 to a kernel 3D vector. Caller must call .delete() when done. */
221
280
  function toKernelVec(v) {
@@ -5234,4 +5293,4 @@ var csg_exports = /* @__PURE__ */ __exportAll({
5234
5293
  withEvaluator: () => withEvaluator
5235
5294
  });
5236
5295
  //#endregion
5237
- export { BaseSketcher2d, BlueprintSketcher, BrepBugError, BrepErrorCode, BrepWrapperError, BrepkitAdapter, CompoundSketch, DEG2RAD, DisposalScope, FaceSketcher, HASH_CODE_MAX, OK, OcctWasmAdapter, RAD2DEG, Sketch, Sketcher, Sketches, addChild, addHoles, addMate, addStep, adjacentFaces, all, andThen, applyGlue, applyMatrix, approximateCurve, as2D, as3D, asTopo, assignRoles, autoHeal, bezier, blueprintToDXF, booleanPipeline, booleans_exports as booleans, boss, box, bsplineApprox, bug, cameraFromPlane, cameraLookAt, captureHint, cast, castShape, castShape3D, chamfer, chamferDistAngle as chamferDistAngleShape, chamferWithEvolution, checkAllInterferences, checkBoolean, checkInterference, circle, circularPattern, classifyPointOnFace, clearMeshCache, clone, closedWire, collect, collectShapes, colorFaces, colorShape, complexExtrude, composeTransforms, compound, compoundSketchExtrude, compoundSketchFace, compoundSketchLoft, compoundSketchRevolve, computationError, computeStraightSkeleton, cone, construction_exports as construction, convexHull, cornerFinder, countNodes, createAssembly, createAssemblyNode, createBlueprint, createCamera, createCompound, createCompoundBlueprint, createDistanceQuery, createEdge, createFace, createHandle, createHistory, createKernelHandle, createMeshCache, createNamedPlane, createOperationRegistry, createPlane, createRef, createRegistry, createShell, createSolid, createTaskQueue, createVertex, createWire, createWorkerClient, createWorkerHandler, csg_exports as csg, curve2dBoundingBox, curve2dDistanceFrom, curve2dFirstPoint, curve2dIsOnCurve, curve2dLastPoint, curve2dParameter, curve2dSplitAt, curve2dTangentAt, curveEndPoint, curveIsClosed, curveIsPeriodic, curveLength, curvePeriod, curvePointAt, curveStartPoint, curveTangentAt, cut, cut2D, cutAll, cutAllBisect, cutBlueprints, cutWithEvolution, cylinder, defaultScorer, dequeueTask, describe, deserializeDrawing, deserializeHistory, fromBREP as deserializeShape, downcast, draft, draw, drawCircle, drawEllipse, drawFaceOutline, drawParametricFunction, drawPointsInterpolation, drawPolysides, drawProjection, drawRectangle, drawRoundedRectangle, drawSingleCircle, drawSingleEllipse, drawText, drawingChamfer, drawingCut, drawingFillet, drawingFuse, drawingIntersect, drawingToSketchOnPlane, drill, edgeFinder, edgesOfFace, ellipse, ellipseArc, ellipsoid, enqueueTask, err, exportAssemblySTEP, exportDXF, exportGlb, exportGltf, exportIGES, exportOBJ, exportSTEP, exportSTEPConfigured, exportSTL, exportThreeMF, extrude, extrudeAll, face, faceCenter, faceFinder, faceGeomType, faceOrientation, facesOfEdge, fill, filledFace, fillet, filletWithEvolution, findFacesByTag, findNode, findStep, fixSelfIntersection, fixShape, flatMap, flatten, flipFaceOrientation, flipOrientation, fontMetrics, fromBREP$1 as fromBREP, fromKernelDir, fromKernelPnt, fromKernelVec, fromNullable, fuse, fuse2D, fuseAll, fuseAllBisect, fuseBlueprints, fuseWithEvolution, gearGeometry, getActiveVoxelId, getBounds, getBounds2D, getCompSolids, getCurveType, getDisposalStats, getEdges, getFaceColor, getFaceOrigins, getFaceTags, getFaces, getFont, getHashCode, getShape as getHistoryShape, getKernel, getNurbsCurveData, getNurbsSurfaceData, getOrientation, getOrientation2D, getPerformanceStats, getShapeColor, getShapeKind, getShells, getSingleFace, getSolids, getSurfaceType, getTagMetadata, getVertices, getVoxel, getWires, guidedSweep, heal, healFace, healSolid, healWire, helix, hull, importDXF, importGLB, importIGES, importOBJ, importSTEP, importSTL, importSVG, importSVGPathD, importThreeMF, init, initFromManifold, initFromOC, initVoxel, innerWires, interpolateCurve, intersect, intersect2D, intersectBlueprints, intersectWithEvolution, invalidateShapeCache, ioNs_exports as io, ioError, is2D, is3D, isChamferRadius, isClosedWire, isCompSolid, isCompound, isDisposeRequest, isEdge, isEmpty, isEqualShape, isErr, isErrorResponse, isFace, isFilletRadius, isInitRequest, isInside2D, isLive, isManifoldShell, isNumber, isOk, isOperationRequest, isOrientedFace, isPlanarFace, isPlanarWire, isProjectionPlane, isEmpty$1 as isQueueEmpty, isSameShape, isShape1D, isShape3D, isShell, isSolid, isSuccessResponse, isValid, isValidSolid, isVertex, isWire, iterCompSolids, iterEdges, iterFaces, iterShells, iterSolids, iterTopo, iterVertices, iterWires, kernelCall, kernelCallRaw, kernelCallScoped, kernelError, line, linearPattern, loadFont, loft, loftAll, makeBaseBox, makeExternalGear, makeInternalGear, makePlane, makePlanetaryGear, makeProjectedEdges, manifoldShell, map, mapBoth, mapErr, match, measureArea, measureCurvatureAt, measureCurvatureAtMid, measureDistance, measureDistanceProps, measureLength, measureLinearProps, measureSurfaceProps, measureVolume, measureVolumeProps, measurement_exports as measurement, mesh, meshEdges, meshMultiLOD, minkowski, mirror, mirror2D, mirrorDrawing, mirrorJoin, modifiers_exports as modifiers, modifyStep, moduleInitError, multiSectionSweep, normalAt, offset, offsetFace, offsetWire2D, ok, or, orElse, organiseBlueprints, orientedFace, outerWire, patterns_exports as patterns, pendingCount, pipeline, pivotPlane, planarFace, planarWire, planetPlacements, pocket, pointOnSurface, pointsInside, polygon, polyhedron, polysideInnerRadius, polysidesBlueprint, positionOnCurve, prewarm, primitives_exports as primitives, projectEdges, projectPointOnFace, query_exports as query, queryError, rectangularPattern, registerHandler, registerKernel, registerOperation, registerShape, registerVoxel, rejectAll, removeChild, removeHolesFromFace, replayFrom, replayHistory, resetDisposalStats, resetPerformanceStats, resize, resolve, resolve3D, resolveDirection, resolvePlane, resolveRef, reverseCurve, revolve, roof, rotate, rotate2D, rotateDrawing, roundedRectangleBlueprint, scale, scale2D, scaleDrawing, section, sectionToFace, serializeHistory, setShapeOrigin, setTagMetadata, sewShells, shape, shapeType, sharedEdges, shell, shellWithEvolution, simplify, sketchCircle, sketchEllipse, sketchExtrude, sketchFace, sketchFaceOffset, sketchHelix, sketchLoft, sketchOnFace2D, sketchOnPlane2D, sketchParametricFunction, sketchPolysides, sketchRectangle, sketchRevolve, sketchRoundedRectangle, sketchSweep, sketchText, sketchWires, sketcherStateError, slice, solid, solidFromShell, solveAssembly, sphere, split, stepCount, stepsFrom, stretch2D, subFace, supportExtrude, supportsConstraintSketch, supportsProjection, surfaceFromGrid, surfaceFromImage, sweep, tagFaces, tangentArc, tap, tapErr, textBlueprints, textMetrics, thicken, threePointArc, toBREP, toBufferGeometryData, toGroupedBufferGeometryData, toKernelVec, toLODGeometryData, toLineGeometryData, toSVGPathD, toVec2, toVec3, torus, transformCopy, transforms_exports as transforms, translate, translate2D, translateDrawing, translatePlane, tryCatch, tryCatchAsync, twistExtrude, typeCastError, undoLast, unsupportedError, unwrap, unwrapErr, unwrapOr, unwrapOrElse, updateNode, updateRoles, uvBounds, uvCoordinates, validSolid, validatePlanetary, validationError, variableFillet, vecAdd, vecAngle, vecCross, vecDistance, vecDot, vecEquals, vecIsZero, vecLength, vecLengthSq, vecNegate, vecNormalize, vecProjectToPlane, vecRepr, vecRotate, vecScale, vecSub, vertex, vertexFinder, vertexPosition, verticesOfEdge, walkAssembly, windingNumbers, wire, wireFinder, wireLoop, wiresOfFace, withKernel, withKernelDir, withKernelPnt, withKernelVec, withScope, withScopeResult, withScopeResultAsync, zip as zipResults };
5296
+ export { BaseSketcher2d, BlueprintSketcher, BrepBugError, BrepErrorCode, BrepWrapperError, BrepkitAdapter, CompoundSketch, DEG2RAD, DisposalScope, FaceSketcher, HASH_CODE_MAX, OK, OcctWasmAdapter, RAD2DEG, Sketch, Sketcher, Sketches, addChild, addHoles, addMate, addStep, adjacentFaces, all, andThen, applyGlue, applyMatrix, approximateCurve, as2D, as3D, asTopo, assignRoles, autoHeal, bezier, blueprintToDXF, booleanPipeline, booleans_exports as booleans, boss, box, bsplineApprox, bug, cameraFromPlane, cameraLookAt, captureHint, cast, castShape, castShape3D, chamfer, chamferDistAngle as chamferDistAngleShape, chamferWithEvolution, checkAllInterferences, checkBoolean, checkInterference, circle, circularPattern, classifyPointOnFace, clearMeshCache, clone, closedWire, collect, collectShapes, colorFaces, colorShape, complexExtrude, composeTransforms, compound, compoundSketchExtrude, compoundSketchFace, compoundSketchLoft, compoundSketchRevolve, computationError, computeStraightSkeleton, cone, construction_exports as construction, convexHull, cornerFinder, countNodes, createAssembly, createAssemblyNode, createBlueprint, createCamera, createCompound, createCompoundBlueprint, createDistanceQuery, createEdge, createFace, createHandle, createHistory, createKernelHandle, createMeshCache, createNamedPlane, createOperationRegistry, createPlane, createRef, createRegistry, createShell, createSolid, createTaskQueue, createVertex, createWire, createWorkerClient, createWorkerHandler, csg_exports as csg, curve2dBoundingBox, curve2dDistanceFrom, curve2dFirstPoint, curve2dIsOnCurve, curve2dLastPoint, curve2dParameter, curve2dSplitAt, curve2dTangentAt, curveEndPoint, curveIsClosed, curveIsPeriodic, curveLength, curvePeriod, curvePointAt, curveStartPoint, curveTangentAt, cut, cut2D, cutAll, cutAllBisect, cutBlueprints, cutWithEvolution, cylinder, defaultScorer, dequeueTask, describe, deserializeDrawing, deserializeHistory, fromBREP as deserializeShape, downcast, draft, draw, drawCircle, drawEllipse, drawFaceOutline, drawParametricFunction, drawPointsInterpolation, drawPolysides, drawProjection, drawRectangle, drawRoundedRectangle, drawSingleCircle, drawSingleEllipse, drawText, drawingChamfer, drawingCut, drawingFillet, drawingFuse, drawingIntersect, drawingToSketchOnPlane, drill, edgeFinder, edgesOfFace, ellipse, ellipseArc, ellipsoid, enqueueTask, err, exportAssemblySTEP, exportDXF, exportGlb, exportGltf, exportIGES, exportOBJ, exportSTEP, exportSTEPConfigured, exportSTL, exportThreeMF, extrude, extrudeAll, face, faceCenter, faceFinder, faceGeomType, faceOrientation, facesOfEdge, fill, filledFace, fillet, filletWithEvolution, findFacesByTag, findNode, findStep, fixSelfIntersection, fixShape, flatMap, flatten, flipFaceOrientation, flipOrientation, fontMetrics, fromBREP$1 as fromBREP, fromKernelDir, fromKernelPnt, fromKernelVec, fromNullable, fuse, fuse2D, fuseAll, fuseAllBisect, fuseBlueprints, fuseWithEvolution, gearGeometry, getActiveVoxelId, getBounds, getBounds2D, getCompSolids, getCurveType, getDisposalStats, getEdges, getFaceColor, getFaceOrigins, getFaceTags, getFaces, getFont, getHashCode, getShape as getHistoryShape, getKernel, getNurbsCurveData, getNurbsSurfaceData, getOrientation, getOrientation2D, getPerformanceStats, getShapeColor, getShapeKind, getShells, getSingleFace, getSolids, getSurfaceType, getTagMetadata, getVertices, getVoxel, getWires, guidedSweep, heal, healFace, healSolid, healWire, helix, hull, importDXF, importGLB, importIGES, importOBJ, importSTEP, importSTL, importSVG, importSVGPathD, importThreeMF, init, initFromManifold, initFromOC, initVoxel, innerWires, interpolateCurve, intersect, intersect2D, intersectBlueprints, intersectWithEvolution, invalidateShapeCache, ioNs_exports as io, ioError, is2D, is3D, isChamferRadius, isClosedWire, isCompSolid, isCompound, isDisposeRequest, isEdge, isEmpty, isEqualShape, isErr, isErrorResponse, isFace, isFilletRadius, isInitRequest, isInside2D, isLive, isManifoldShell, isNumber, isOk, isOperationRequest, isOrientedFace, isPlanarFace, isPlanarWire, isProjectionPlane, isEmpty$1 as isQueueEmpty, isSameShape, isShape1D, isShape3D, isShell, isSolid, isSuccessResponse, isValid, isValidSolid, isVertex, isWire, iterCompSolids, iterEdges, iterFaces, iterShells, iterSolids, iterTopo, iterVertices, iterWires, kernelCall, kernelCallRaw, kernelCallScoped, kernelError, line, linearPattern, loadFont, loft, loftAll, makeBaseBox, makeExternalGear, makeInternalGear, makePlane, makePlanetaryGear, makeProjectedEdges, manifoldShell, map, mapBoth, mapErr, match, measureArea, measureCurvatureAt, measureCurvatureAtMid, measureDistance, measureDistanceProps, measureLength, measureLinearProps, measureSurfaceProps, measureVolume, measureVolumeProps, measurement_exports as measurement, mesh, meshEdges, meshMultiLOD, minkowski, mirror, mirror2D, mirrorDrawing, mirrorJoin, modifiers_exports as modifiers, modifyStep, moduleInitError, multiSectionSweep, normalAt, offset, offsetFace, offsetWire2D, ok, or, orElse, organiseBlueprints, orientedFace, outerWire, patterns_exports as patterns, pendingCount, pipeline, pivotPlane, planarFace, planarWire, planetPlacements, pocket, pointOnSurface, pointsInside, polygon, polyhedron, polysideInnerRadius, polysidesBlueprint, positionOnCurve, prewarm, primitives_exports as primitives, projectEdges, projectPointOnFace, query_exports as query, queryError, rectangularPattern, registerHandler, registerKernel, registerOperation, registerShape, registerVoxel, rejectAll, removeChild, removeHolesFromFace, repairMesh, replayFrom, replayHistory, resetDisposalStats, resetPerformanceStats, resize, resolve, resolve3D, resolveDirection, resolvePlane, resolveRef, reverseCurve, revolve, roof, rotate, rotate2D, rotateDrawing, roundedRectangleBlueprint, scale, scale2D, scaleDrawing, section, sectionToFace, serializeHistory, setShapeOrigin, setTagMetadata, sewShells, shape, shapeType, sharedEdges, shell, shellWithEvolution, simplify, sketchCircle, sketchEllipse, sketchExtrude, sketchFace, sketchFaceOffset, sketchHelix, sketchLoft, sketchOnFace2D, sketchOnPlane2D, sketchParametricFunction, sketchPolysides, sketchRectangle, sketchRevolve, sketchRoundedRectangle, sketchSweep, sketchText, sketchWires, sketcherStateError, slice, solid, solidFromShell, solveAssembly, sphere, split, stepCount, stepsFrom, stretch2D, subFace, supportExtrude, supportsConstraintSketch, supportsProjection, surfaceFromGrid, surfaceFromImage, sweep, tagFaces, tangentArc, tap, tapErr, textBlueprints, textMetrics, thicken, threePointArc, toBREP, toBufferGeometryData, toGroupedBufferGeometryData, toKernelVec, toLODGeometryData, toLineGeometryData, toSVGPathD, toVec2, toVec3, torus, transformCopy, transforms_exports as transforms, translate, translate2D, translateDrawing, translatePlane, tryCatch, tryCatchAsync, twistExtrude, typeCastError, undoLast, unsupportedError, unwrap, unwrapErr, unwrapOr, unwrapOrElse, updateNode, updateRoles, uvBounds, uvCoordinates, validSolid, validatePlanetary, validationError, variableFillet, vecAdd, vecAngle, vecCross, vecDistance, vecDot, vecEquals, vecIsZero, vecLength, vecLengthSq, vecNegate, vecNormalize, vecProjectToPlane, vecRepr, vecRotate, vecScale, vecSub, vertex, vertexFinder, vertexPosition, verticesOfEdge, walkAssembly, windingNumbers, wire, wireFinder, wireLoop, wiresOfFace, withKernel, withKernelDir, withKernelPnt, withKernelVec, withScope, withScopeResult, withScopeResultAsync, zip as zipResults };
package/dist/index.d.ts CHANGED
@@ -34,8 +34,8 @@ export { exportDXF, blueprintToDXF, type DXFEntity, type DXFExportOptions, } fro
34
34
  export { exportThreeMF, type ThreeMFExportOptions, type ThreeMFMaterial, } from './io/threemfExportFns.js';
35
35
  export { importSVGPathD, importSVG, type SVGImportOptions } from './io/svgImportFns.js';
36
36
  export { exportSTEPConfigured, type StepExportOptions, type StepExportPart, } from './io/stepConfigFns.js';
37
- export { initVoxel, registerVoxel, getVoxel, getActiveVoxelId, windingNumbers, pointsInside, } from './voxel/index.js';
38
- export type { VoxelEngine, VoxelMeshInput } from './voxel/index.js';
37
+ export { initVoxel, registerVoxel, getVoxel, getActiveVoxelId, windingNumbers, pointsInside, repairMesh, } from './voxel/index.js';
38
+ export type { VoxelEngine, VoxelMeshInput, VoxelRepairResult, RepairOptions, } from './voxel/index.js';
39
39
  export { default as Sketcher } from './sketching/sketcher.js';
40
40
  export { default as FaceSketcher } from './sketching/faceSketcher.js';
41
41
  export { BaseSketcher2d } from './2d/blueprints/baseSketcher2d.js';
@@ -11,6 +11,21 @@ export interface VoxelEngine {
11
11
  winding_numbers(verts: Float32Array, tris: Uint32Array, queries: Float32Array): Float32Array;
12
12
  /** Inside/outside classification per query point (1 = inside, 0 = outside). */
13
13
  points_inside(verts: Float32Array, tris: Uint32Array, queries: Float32Array): Uint8Array;
14
+ /** Voxelize-and-contour a mesh into a closed surface (FWN sign keystone). */
15
+ repair_mesh(verts: Float32Array, tris: Uint32Array, resolution: number, padding: number): VoxelRepairResult;
14
16
  /** Engine artifact version, for loader/artifact compatibility checks. */
15
17
  version(): string;
16
18
  }
19
+ /**
20
+ * The repaired-mesh handle the wasm `repair_mesh` returns. Flat xyz
21
+ * `positions`/`normals` (length 3·V) and a triangle-list `indices` (3 per tri),
22
+ * in world space. Structurally satisfied by the generated `RepairResult` class.
23
+ */
24
+ export interface VoxelRepairResult {
25
+ readonly positions: Float32Array;
26
+ readonly normals: Float32Array;
27
+ readonly indices: Uint32Array;
28
+ /** Release the backing WASM allocation (wasm-bindgen lifecycle). */
29
+ free(): void;
30
+ [Symbol.dispose](): void;
31
+ }
@@ -5,7 +5,9 @@
5
5
  * API. v1 surfaces the repair-slice keystone (Generalized Winding Number sign);
6
6
  * grid / contour / bridge seams land behind the same registry.
7
7
  */
8
- export type { VoxelEngine } from './engine.js';
8
+ export type { VoxelEngine, VoxelRepairResult } from './engine.js';
9
9
  export type { VoxelMeshInput } from './signFns.js';
10
+ export type { RepairOptions } from './repairFns.js';
10
11
  export { registerVoxel, getVoxel, getActiveVoxelId, initVoxel } from './registry.js';
11
12
  export { windingNumbers, pointsInside } from './signFns.js';
13
+ export { repairMesh } from './repairFns.js';
@@ -0,0 +1,18 @@
1
+ import { Result } from '../core/result.js';
2
+ import { KernelMeshResult } from '../kernel/types.js';
3
+ import { VoxelMeshInput } from './signFns.js';
4
+ /** Voxel-repair tuning. `resolution` sizes the longest bbox axis in voxels;
5
+ * `padding` is the positive air-margin ring (>= 1) Surface Nets needs. */
6
+ export interface RepairOptions {
7
+ resolution?: number;
8
+ padding?: number;
9
+ }
10
+ /**
11
+ * Repair a (possibly non-watertight) triangle-soup mesh into a closed surface:
12
+ * voxelize an FWN-signed SDF, then Surface-Nets contour it back to triangles.
13
+ *
14
+ * The FWN sign classifies inside/outside even on holey input, so a mesh with
15
+ * missing faces still yields a watertight result (ADR-0013 §11). Returns a
16
+ * {@link KernelMeshResult} in world coordinates (a single face group, no UVs).
17
+ */
18
+ export declare function repairMesh(mesh: VoxelMeshInput, opts?: RepairOptions, id?: string): Result<KernelMeshResult>;
@@ -1,4 +1,6 @@
1
1
  import { Result } from '../core/result.js';
2
+ import { BrepError } from '../core/errors.js';
3
+ import { VoxelEngine } from './engine.js';
2
4
  /**
3
5
  * Minimal triangle-soup input for sign queries. Structurally satisfied by a
4
6
  * {@link KernelMeshResult} (which also carries normals/uvs/faceGroups).
@@ -7,6 +9,15 @@ export interface VoxelMeshInput {
7
9
  vertices: Float32Array;
8
10
  triangles: Uint32Array;
9
11
  }
12
+ /**
13
+ * Validate a triangle-soup mesh before it crosses into wasm: flat-xyz vertices,
14
+ * triangle-multiple indices, and every index in range. An out-of-range index
15
+ * would otherwise panic in Rust and surface as a wasm trap, escaping the Result
16
+ * contract — so it must be rejected here.
17
+ */
18
+ export declare function validateMesh(mesh: VoxelMeshInput): BrepError | null;
19
+ /** Resolve a registered voxel engine, mapping an unregistered id to an error. */
20
+ export declare function resolveEngine(id: string | undefined): Result<VoxelEngine>;
10
21
  /**
11
22
  * Generalized winding number at each query point against a triangle-soup mesh.
12
23
  *
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "brepjs",
3
- "version": "18.36.0",
3
+ "version": "18.37.0",
4
4
  "description": "Web CAD library with pluggable geometry kernel",
5
5
  "keywords": [
6
6
  "cad",