Speed: a rebuild sends and draws only the bodies it changed. Every rebuild (each move of a cut or extrude drag too) sent every body's triangles from the geometry worker to the page, and the view rebuilt them all for the graphics card - 3.8 MB a move on the jet engine for one body changed (0.9 MB now). Meshes have a key: an unchanged one goes across as its key only, and the view keeps what it drew for it. Join / cut checks work out a body's volume, gaps and hair-thin faces once per shape (the target's volume was measured twice and the result's three times, and the body before the step was checked again on each drag move - slow on a freeform's curved faces)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
superGeometry
2026-11-08 20:47:24 +02:00
parent 6fc54e4871
commit 07dad071d3
6 changed files with 126 additions and 30 deletions
+18 -2
View File
@@ -1,5 +1,5 @@
import type { Feature } from "../doc/types";
import type { Envelope, ExportFormat, RegenResult, Request, Response } from "./protocol";
import type { BodyMesh, Envelope, ExportFormat, RegenResult, Request, Response } from "./protocol";
/** Promise-based wrapper around the kernel worker. */
export class KernelClient {
@@ -13,12 +13,16 @@ export class KernelClient {
// Coalesce regenerations: while one runs, only the most recent request waits.
private regenRunning = false;
private regenQueued: { features: Feature[]; resolve: (r: RegenResult | null) => void } | null = null;
/** The last answer's meshes by key: the worker sends a mesh once, then just its key. */
private meshes = new Map<number, BodyMesh>();
constructor() {
this.start();
}
private start(): void {
// A fresh worker sends every mesh again.
this.meshes = new Map();
this.worker = new Worker(new URL("./worker.ts", import.meta.url), { type: "module" });
this.worker.onmessage = (e: MessageEvent<Envelope<Response>>) => {
const cb = this.pending.get(e.data.id);
@@ -86,7 +90,7 @@ export class KernelClient {
// Stopped meanwhile: the fresh worker has its own queue.
if (worker !== this.worker) return resolve(null);
this.running = null;
resolve(r.type === "regenerated" ? r.result : null);
resolve(r.type === "regenerated" ? this.withMeshes(r.result) : null);
if (r.type === "error") console.error(r.message);
this.regenRunning = false;
const q = this.regenQueued;
@@ -94,6 +98,18 @@ export class KernelClient {
if (q) this.runRegen(q.features, q.resolve);
}
/** Meshes sent as their key only (unchanged bodies): the ones the page has. */
private withMeshes(result: RegenResult): RegenResult {
const bodies = result.bodies.map((b) => {
if (!(b as { same?: boolean }).same) return b;
const had = this.meshes.get(b.key)!;
// (The same object when nothing about it changed: the view keeps what it drew.)
return had.id === b.id && had.name === b.name ? had : { ...had, id: b.id, name: b.name };
});
this.meshes = new Map(bodies.map((b) => [b.key, b]));
return { ...result, bodies };
}
async export(features: Feature[], format: ExportFormat, bodies?: string[]): Promise<Blob> {
await this.ready;
const r = await this.call({ type: "export", features, format, bodies });
+29 -8
View File
@@ -28,6 +28,7 @@ import {
measureDistanceBetween,
measureVolume,
revolution,
Solid,
Vector,
assembleWire,
type AnyShape,
@@ -90,6 +91,8 @@ interface CacheEntry {
}
const meshCache = new WeakMap<Shape3D, BodyMesh>();
/** The next mesh's key (see BodyMesh.key). */
let meshKey = 1;
const importCache = new Map<string, Shape3D>();
let cache: CacheEntry[] = [];
@@ -1489,15 +1492,31 @@ function combine(id: string, mode: string, target: string | undefined, solid: Sh
else ctx.bodies.set(target, result);
}
/**
* A shape's (signed) volume, worked out once per shape: a cut asks for its
* body's, its tool's and its result's in several checks, and again for the
* same body on every move of a drag - slow on a freeform's curved faces.
* (A shape turned right way out in place is measured again, not looked up.)
*/
const volumes = new WeakMap<Shape3D, number>();
function volumeOf(s: Shape3D): number {
let v = volumes.get(s);
if (v === undefined) {
v = measureVolume(s);
volumes.set(s, v);
}
return v;
}
/**
* Can this be the volume of a ∪ b (or a − b)? A union is at least the bigger
* of the two and at most both together; a cut is at most a and at least a − b.
*/
function booleanVolumeOk(op: "fuse" | "cut", a: Shape3D, b: Shape3D, r: Shape3D): boolean {
try {
const va = Math.abs(measureVolume(a));
const vb = Math.abs(measureVolume(b));
const v = isEmpty(r) ? 0 : measureVolume(r);
const va = Math.abs(volumeOf(a));
const vb = Math.abs(volumeOf(b));
const v = isEmpty(r) ? 0 : volumeOf(r);
// A big many-faced body measures a little differently once a join splits
// its faces (a jet engine's casing: 2 to 75 mm³ in 1.9 litres) - more than
// the name raised on its pylon (158 mm³) could stand under a closer check.
@@ -1565,7 +1584,7 @@ function fuzzyBoolean(op: "cut" | "fuse" | "common", a: Shape3D, b: Shape3D): Sh
/** Bodies (other than `skip`) that `solid` really overlaps (not just touches). */
function overlapping(solid: Shape3D, ctx: Ctx, skip?: string): string[] {
const sb = solid.boundingBox;
const vs = Math.abs(measureVolume(solid));
const vs = Math.abs(volumeOf(solid));
const out: string[] = [];
for (const [id, body] of ctx.bodies) {
if (id === skip) continue;
@@ -1576,7 +1595,7 @@ function overlapping(solid: Shape3D, ctx: Ctx, skip?: string): string[] {
// Tolerant: a wall drawn from the body's own edge (projected, offset…) sits a hair
// off the body's surface, and an exact boolean then finds no overlap at all.
const common = fuzzyBoolean("common", body, solid);
if (!isEmpty(common) && Math.abs(measureVolume(common)) > Math.max(1e-9, Math.min(vs, Math.abs(measureVolume(body))) * 1e-6)) out.push(id);
if (!isEmpty(common) && Math.abs(measureVolume(common)) > Math.max(1e-9, Math.min(vs, Math.abs(volumeOf(body))) * 1e-6)) out.push(id);
} catch {
// can't tell: leave it alone
}
@@ -1790,6 +1809,7 @@ function meshBody(id: string, name: string, shape: Shape3D): BodyMesh {
const mesh: BodyMesh = {
id,
name,
key: meshKey++,
positions: new Float32Array(m.vertices),
normals: new Float32Array(m.normals),
indices: new Uint32Array(m.triangles),
@@ -1860,7 +1880,7 @@ function guardEdit(before: Shape3D | undefined, after: Shape3D, mayPart: boolean
const was = before ? subShapes(before, "SOLID").length : Math.max(1, subShapes(after, "SOLID").length);
// Not a solid before (an imported mesh, a sheet): nothing to hold it to.
if (!was) return after;
const v0 = before ? Math.abs(measureVolume(before)) : 0;
const v0 = before ? Math.abs(volumeOf(before)) : 0;
let solids = subShapes(after, "SOLID");
if (!solids.length) {
// A hollow (outer skin + inner skin) left as loose skins: one solid with a void.
@@ -1875,7 +1895,8 @@ function guardEdit(before: Shape3D | undefined, after: Shape3D, mayPart: boolean
after = cast(solid) as Shape3D;
}
// A lump inside out among the others: the cut went wrong.
const signed = solids.map((x) => measureVolume(cast(x) as Shape3D));
// (One solid: the body itself - its volume, worked out once.)
const signed = solids.length === 1 && after instanceof Solid ? [volumeOf(after)] : solids.map((x) => measureVolume(cast(x) as Shape3D));
if (solids.length > 1 && signed.some((v) => v < 0) && signed.some((v) => v > 0)) throw new Error("That edit would damage the body - try a different value");
// Crumbs: lumps far smaller than the rest (left between coincident faces).
const vols = signed.map((v) => Math.abs(v));
@@ -1892,7 +1913,7 @@ function guardEdit(before: Shape3D | undefined, after: Shape3D, mayPart: boolean
if (!mayPart && solids.length > was) throw new Error("That would break the body into pieces - try a smaller value");
// Inside out (negative volume): turn it right - on a copy (its faces may be
// shared with earlier steps' results, which must never change).
if (measureVolume(after) < 0) {
if (volumeOf(after) < 0) {
after = deepCopy(after);
solids = subShapes(after, "SOLID");
for (const x of solids) oc.BRepLib.OrientClosedSolid(x);
+20
View File
@@ -25,7 +25,19 @@ function checkValid(shape: Shape3D): boolean {
}
/**
* Edges with a face on one side only (gaps), by index. Worked out once per
* shape, like the checks below: every edit asks it of the body as it was
* before, which is the same body on each move of a drag.
*/
const openCache = new WeakMap<Shape3D, number[]>();
export function openEdges(shape: Shape3D): number[] {
let known = openCache.get(shape);
if (!known) openCache.set(shape, (known = findOpenEdges(shape)));
return known;
}
function findOpenEdges(shape: Shape3D): number[] {
const edges = shape.edges;
const buckets = new Map<number, { e: Edge; i: number; n: number }[]>();
edges.forEach((e, i) => {
@@ -70,7 +82,15 @@ export function subShapes(s: Shape3D, kind: "SOLID" | "SHELL"): any[] {
return out;
}
/** How many faces are next to nothing in area (once per shape: every face's area is slow on curved faces). */
const thinCache = new WeakMap<Shape3D, number>();
export function hairThin(s: Shape3D): number {
let known = thinCache.get(s);
if (known === undefined) thinCache.set(s, (known = countHairThin(s)));
return known;
}
function countHairThin(s: Shape3D): number {
const areas = s.faces.map((f) => measureArea(f));
const total = areas.reduce((a, b) => a + b, 0);
return areas.filter((a) => a < total * 1e-7).length;
+6
View File
@@ -28,6 +28,12 @@ export interface EdgeInfo {
export interface BodyMesh {
id: string;
name: string;
/**
* Which mesh this is: the same key, the same geometry (a body the step
* didn't change). The worker sends only the key for a mesh the page already
* has, and the view keeps what it drew for it.
*/
key: number;
positions: Float32Array;
normals: Float32Array;
indices: Uint32Array;
+14 -3
View File
@@ -5,7 +5,14 @@ import opencascade from "replicad-opencascadejs";
import wasmUrl from "replicad-opencascadejs/wasm?url";
import { setOC } from "replicad";
import { errorText, exportBodies, regenerate } from "./engine";
import type { Envelope, Request, Response } from "./protocol";
import type { BodyMesh, Envelope, Request, Response } from "./protocol";
/**
* The meshes the page has (it keeps the last answer's): those go back as their
* key only - a step changes one body, and every body's triangles were copied
* across on each move of a drag.
*/
let sent = new Set<number>();
self.onmessage = async (e: MessageEvent<Envelope<Request>>) => {
const { id, msg } = e.data;
@@ -16,9 +23,13 @@ self.onmessage = async (e: MessageEvent<Envelope<Request>>) => {
setOC(await opencascade({ locateFile: () => wasmUrl }));
reply({ type: "ready" });
break;
case "regenerate":
reply({ type: "regenerated", result: await regenerate(msg.features) });
case "regenerate": {
const result = await regenerate(msg.features);
const bodies = result.bodies.map((b) => (sent.has(b.key) ? ({ id: b.id, name: b.name, key: b.key, same: true } as unknown as BodyMesh) : b));
sent = new Set(result.bodies.map((b) => b.key));
reply({ type: "regenerated", result: { ...result, bodies } });
break;
}
case "export":
reply({ type: "exported", blob: await exportBodies(msg.features, msg.format, msg.bodies) });
break;
+39 -17
View File
@@ -357,17 +357,37 @@ export class Viewport {
}
setBodies(meshes: BodyMesh[]): void {
for (const b of this.bodies.values()) {
// A body the step didn't change (same mesh key): what was drawn for it stays
// (its triangles went to the graphics card once, not again on every rebuild).
const was = new Map(this.bodies);
const keep = new Set(meshes.filter((m) => was.get(m.id)?.data.key === m.key).map((m) => m.id));
for (const [id, b] of was) {
b.outline?.geometry.dispose();
b.outline = null;
if (keep.has(id)) continue;
b.mesh.geometry.dispose();
b.edges.geometry.dispose();
}
this.openMats.forEach((m) => this.releaseLineMaterial(m));
this.openMats = [];
for (const b of this.bodies.values()) b.outline?.geometry.dispose();
this.bodies.clear();
this.bodiesGroup.clear();
this.capGroup.clear();
for (const data of meshes) {
const old = keep.has(data.id) ? was.get(data.id) : undefined;
if (old) {
const i = this.bodies.size;
old.data = data;
old.mesh.material = this.matsFor(data.id).body;
old.cap.material = this.matsFor(data.id).cap;
old.capStencil.forEach((sm) => (sm.renderOrder = 10 + 3 * i));
old.cap.renderOrder = 11 + 3 * i;
this.bodiesGroup.add(old.mesh, old.edges, old.hidden);
this.capGroup.add(old.cap, ...old.capStencil);
this.bodies.set(data.id, old);
this.addOpenEdges(data);
continue;
}
const g = new BufferGeometry();
g.setAttribute("position", new BufferAttribute(data.positions, 3));
g.setAttribute("normal", new BufferAttribute(data.normals, 3));
@@ -396,27 +416,29 @@ export class Viewport {
this.capGroup.add(cap, ...capStencil);
const vertices = uniqueEnds(data.edges);
this.bodies.set(data.id, { data, mesh, cap, capStencil, outline: null, edges, hidden, vertices });
// Open (non-watertight) edges stand out in orange.
if (data.openEdges?.length) {
const seg: number[] = [];
for (const i of data.openEdges) {
const g = data.edgeGroups.find((x) => x.edge === i);
if (g) seg.push(...Array.from(data.edgePositions.slice(g.start * 3, (g.start + g.count) * 3)));
}
if (seg.length) {
const mat = this.lineMaterial(0xff9a3d, 3, true);
this.openMats.push(mat);
const l = new LineSegments2(new LineSegmentsGeometry().setPositions(seg), mat);
l.renderOrder = 3;
this.bodiesGroup.add(l);
}
}
this.addOpenEdges(data);
}
this.applyClip();
this.applySettings();
this.applyHidden();
}
/** Open (non-watertight) edges stand out in orange. */
private addOpenEdges(data: BodyMesh): void {
if (!data.openEdges?.length) return;
const seg: number[] = [];
for (const i of data.openEdges) {
const g = data.edgeGroups.find((x) => x.edge === i);
if (g) seg.push(...Array.from(data.edgePositions.slice(g.start * 3, (g.start + g.count) * 3)));
}
if (!seg.length) return;
const mat = this.lineMaterial(0xff9a3d, 3, true);
this.openMats.push(mat);
const l = new LineSegments2(new LineSegmentsGeometry().setPositions(seg), mat);
l.renderOrder = 3;
this.bodiesGroup.add(l);
}
// ------------------------------------------------------- hidden/isolate
private hiddenIds = new Set<string>();