Tools for checking the app: sg in the console, a project checker, pictures without a browser, a shared test kit, version.json

- sg (the browser's console): the project, tool, hint, open window,
  selection, errors and bodies in one look; pick things by name; list and
  run what's offered; read and set the open window's rows (slots, numbers,
  choices, toggles); give a waiting slot a face or edge; Done / Cancel;
  wait for the engine; each body's health; open a project. sg.help() lists it.
- npm run check <project>: rebuilds it step by step and says what each step
  made, changed or took away, its error, and how sound each body is.
- npm run render <project> <out.png>: a shaded picture with edges from any
  side, drawn without a browser.
- tests/kit.ts: the engine started once, check / done, and quick sketches,
  shapes and steps (wrap.test.ts uses it).
- version.json on the site: the commit it was built from; npm run live says
  whether main is live (--wait until it is).
- The engine measures each body's health on request (valid, closed, solids,
  faces, volume, box).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
superGeometry
2026-11-11 21:23:25 +02:00
parent c9562582d9
commit 60c66fd731
15 changed files with 1018 additions and 27 deletions
+4 -1
View File
@@ -9,7 +9,10 @@
"dev": "vite --host",
"build": "tsc --noEmit && vite build",
"preview": "vite preview --host",
"typecheck": "tsc --noEmit"
"typecheck": "tsc --noEmit",
"check": "tsx scripts/check.ts",
"render": "tsx scripts/render.ts",
"live": "tsx scripts/live.ts"
},
"dependencies": {
"@fontsource/bebas-neue": "^5.3.0",
+3
View File
@@ -22,3 +22,6 @@
/offline-files.json
Cache-Control: no-cache
/version.json
Cache-Control: no-cache
+146
View File
@@ -0,0 +1,146 @@
// Check a project from the command line: rebuild it step by step and say what
// each step did (its error, the bodies it made, changed or took away) and how
// sound each body is at the end.
//
// npx tsx scripts/check.ts project.super step by step, then the bodies
// npx tsx scripts/check.ts project.super --end only the bodies at the end
// npx tsx scripts/check.ts project.super --json the same, as JSON
// npx tsx scripts/check.ts project.super --png a.png and a picture of it (see render.ts)
//
// Exit code 1 when a step fails or a body isn't sound.
import { readFileSync } from "node:fs";
import opencascade from "replicad-opencascadejs";
import { setOC } from "replicad";
import { parseProject } from "../src/doc/store";
import { debugBodies, healthReport, regenerate } from "../src/kernel/engine";
import type { BodyHealth } from "../src/kernel/protocol";
import type { Feature } from "../src/doc/types";
import { renderPNG, type RenderOptions } from "./render";
export interface StepReport {
index: number;
id: string;
name: string;
type: string;
off?: boolean;
error?: string;
note?: string;
/** Bodies it made, took away, or changed (volume before → after, mm³). */
made: string[];
gone: string[];
changed: { body: string; from: number; to: number }[];
/** Bodies that were sound before it and aren't after. */
broke: string[];
ms: number;
}
export interface CheckReport {
name: string;
steps?: StepReport[];
bodies: BodyHealth[];
errors: { step: string; message: string }[];
ok: boolean;
}
/** Every body's health after the steps (name from the rebuild). */
function bodiesNow(names: Map<string, string>): BodyHealth[] {
return [...debugBodies()].map(([id, s]) => healthReport(id, names.get(id) ?? id, s));
}
export async function checkProject(features: Feature[], name: string, stepwise = true): Promise<CheckReport> {
const steps: StepReport[] = [];
if (stepwise) {
let before = new Map<string, BodyHealth>();
for (let i = 0; i < features.length; i++) {
const f = features[i];
const t0 = performance.now();
const r = await regenerate(features.slice(0, i + 1));
const names = new Map(r.bodies.map((b) => [b.id, b.name]));
const now = new Map(bodiesNow(names).map((h) => [h.id, h]));
const step: StepReport = { index: i + 1, id: f.id, name: f.name, type: f.type, made: [], gone: [], changed: [], broke: [], ms: Math.round(performance.now() - t0) };
if (f.suppressed) step.off = true;
const err = r.errors.find((e) => e.featureId === f.id);
if (err) step.error = err.message;
const note = r.notes?.find((e) => e.featureId === f.id);
if (note) step.note = note.message;
for (const [id, h] of now) {
const was = before.get(id);
if (!was) step.made.push(h.name);
else if (Math.abs(was.volume - h.volume) > 1e-6 * Math.max(1, was.volume) || was.faces !== h.faces) step.changed.push({ body: h.name, from: was.volume, to: h.volume });
if (was?.healthy && !h.healthy) step.broke.push(h.name);
if (!was && !h.healthy) step.broke.push(h.name);
}
for (const [id, h] of before) if (!now.has(id)) step.gone.push(h.name);
steps.push(step);
before = now;
}
}
const r = await regenerate(features);
const names = new Map(r.bodies.map((b) => [b.id, b.name]));
const bodies = bodiesNow(names);
const byId = new Map(features.map((f) => [f.id, f]));
const errors = r.errors.map((e) => ({ step: byId.get(e.featureId)?.name ?? e.featureId, message: e.message }));
return { name, ...(stepwise ? { steps } : {}), bodies, errors, ok: !errors.length && bodies.every((b) => b.healthy) };
}
const n = (v: number) => (Math.abs(v) >= 100 ? v.toFixed(0) : Math.abs(v) >= 1 ? v.toFixed(2) : v.toPrecision(3));
/** The report as lines to read. */
export function reportText(rep: CheckReport): string {
const out: string[] = [`Project: ${rep.name}`];
if (rep.steps) {
out.push("", "Steps:");
for (const s of rep.steps) {
const what: string[] = [];
if (s.off) what.push("switched off");
if (s.made.length) what.push(`made ${s.made.join(", ")}`);
for (const c of s.changed) what.push(`${c.body} ${c.to >= c.from ? "+" : ""}${n(c.to - c.from)} mm³`);
if (s.gone.length) what.push(`took away ${s.gone.join(", ")}`);
if (s.broke.length) what.push(`!! not sound after it: ${s.broke.join(", ")}`);
if (s.note) what.push(`note: ${s.note}`);
if (s.error) what.push(`ERROR: ${s.error}`);
out.push(`${String(s.index).padStart(3)}. ${s.name} [${s.type}]${what.length ? " - " + what.join("; ") : ""} (${s.ms} ms)`);
}
}
out.push("", "Bodies:");
if (!rep.bodies.length) out.push(" (none)");
for (const b of rep.bodies) {
const size = b.box[1].map((v, k) => n(v - b.box[0][k])).join(" x ");
const bad: string[] = [];
if (!b.valid) bad.push("invalid");
if (b.solids !== 1) bad.push(`${b.solids} solids`);
if (b.openEdges) bad.push(`${b.openEdges} open edges`);
if (b.thin) bad.push(`${b.thin} hair-thin faces`);
if (!(b.volume > 0)) bad.push("no volume");
out.push(` ${b.healthy ? "ok " : "BAD "} ${b.name}: ${n(b.volume)} mm³, ${b.faces} faces, ${b.edges} edges, ${size} mm${bad.length ? " - " + bad.join(", ") : ""}`);
}
if (rep.errors.length) {
out.push("", "Errors:");
for (const e of rep.errors) out.push(` ${e.step}: ${e.message}`);
}
out.push("", rep.ok ? "All sound." : "Not all sound.");
return out.join("\n");
}
// ------------------------------------------------------------------ command line
if (process.argv[1]?.replace(/\\/g, "/").endsWith("scripts/check.ts")) {
const args = process.argv.slice(2);
const file = args.find((a) => !a.startsWith("--") && !/\.png$/i.test(a));
if (!file) {
console.log("Usage: npx tsx scripts/check.ts <project.super> [--end] [--json] [--png out.png] [--view iso|front|top|right|...]");
process.exit(2);
}
const doc = parseProject(readFileSync(file, "utf8"));
setOC(await (opencascade as unknown as () => Promise<any>)());
const rep = await checkProject(doc.features, doc.name, !args.includes("--end"));
console.log(args.includes("--json") ? JSON.stringify(rep, null, 2) : reportText(rep));
const png = args[args.indexOf("--png") + 1];
if (args.includes("--png") && png) {
const view = args.includes("--view") ? (args[args.indexOf("--view") + 1] as RenderOptions["view"]) : "iso";
const hidden = new Set(doc.hidden ?? []);
renderPNG([...debugBodies()].filter(([id]) => !hidden.has(id)).map(([id, shape]) => ({ shape, color: doc.colors?.[id] })), png, { view });
console.log(`Picture: ${png}`);
}
process.exit(rep.ok ? 0 : 1);
}
+52
View File
@@ -0,0 +1,52 @@
// Is the push live? Compares the commit supergeometry.app was built from
// (its /version.json) with main here.
//
// npx tsx scripts/live.ts once
// npx tsx scripts/live.ts --wait until it is (up to 20 minutes)
// npx tsx scripts/live.ts --site http://localhost:4173
import { execSync } from "node:child_process";
const args = process.argv.slice(2);
const site = (args.includes("--site") ? args[args.indexOf("--site") + 1] : "https://supergeometry.app").replace(/\/$/, "");
const git = (cmd: string) => {
try {
return execSync(`git ${cmd}`, { stdio: ["ignore", "pipe", "ignore"] }).toString().trim();
} catch {
return "";
}
};
const want = git("rev-parse origin/main");
const short = (c: string) => c.slice(0, 7);
interface Version {
version: string;
commit: string;
subject: string;
script: string;
built: string;
}
async function live(): Promise<Version | null> {
try {
const r = await fetch(`${site}/version.json?t=${Date.now()}`, { cache: "no-store" });
if (!r.ok) return null;
return (await r.json()) as Version;
} catch {
return null;
}
}
const until = Date.now() + 20 * 60_000;
for (;;) {
const v = await live();
if (v?.commit && v.commit === want) {
console.log(`Live: ${short(v.commit)} ${v.subject} (built ${v.built}, ${v.script})`);
process.exit(0);
}
if (!args.includes("--wait") || Date.now() > until) {
if (!v) console.log(`${site} has no version.json yet (built before it was added), main is ${short(want)}`);
else console.log(`Not live yet: the site is ${short(v.commit)} ${v.subject} (built ${v.built}), main is ${short(want)} ${git(`log -1 --format=%s ${want}`)}`);
process.exit(1);
}
await new Promise((r) => setTimeout(r, 20_000));
}
+269
View File
@@ -0,0 +1,269 @@
// A picture of solids without a browser: the bodies meshed, drawn shaded with
// their edges by a small software renderer, and written as a PNG.
//
// npx tsx scripts/render.ts project.super out.png [--view iso|front|back|top|bottom|left|right] [--size 800]
// import { renderPNG } from "./render"; renderPNG([{ shape }], "out.png", { view: "front" });
import { writeFileSync } from "node:fs";
import { deflateSync } from "node:zlib";
import type { Shape3D } from "replicad";
type V3 = [number, number, number];
export interface RenderOptions {
view?: "iso" | "front" | "back" | "top" | "bottom" | "left" | "right";
/** Width and height in pixels (default 800). */
size?: number;
/** Background, "#rrggbb" (default light grey). */
background?: string;
/** Edges drawn over the faces (default on). */
edges?: boolean;
}
export interface RenderBody {
shape: Shape3D;
/** "#rrggbb" (default a blue-grey). */
color?: string;
}
// The views: the direction looked from (towards the viewer) and which way is up on the picture.
const VIEWS: Record<NonNullable<RenderOptions["view"]>, { dir: V3; up: V3 }> = {
iso: { dir: [1, -1, 1], up: [0, 0, 1] },
front: { dir: [0, -1, 0], up: [0, 0, 1] },
back: { dir: [0, 1, 0], up: [0, 0, 1] },
top: { dir: [0, 0, 1], up: [0, 1, 0] },
bottom: { dir: [0, 0, -1], up: [0, -1, 0] },
left: { dir: [-1, 0, 0], up: [0, 0, 1] },
right: { dir: [1, 0, 0], up: [0, 0, 1] },
};
const sub = (a: V3, b: V3): V3 => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
const dot = (a: V3, b: V3) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
const cross = (a: V3, b: V3): V3 => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
const norm = (a: V3): V3 => {
const l = Math.hypot(...a) || 1;
return [a[0] / l, a[1] / l, a[2] / l];
};
const rgb = (hex: string): V3 => {
const m = /^#?([0-9a-f]{6})$/i.exec(hex.trim());
const v = m ? parseInt(m[1], 16) : 0x8fa3b8;
return [(v >> 16) & 255, (v >> 8) & 255, v & 255];
};
/** The picture as RGBA pixels (size x size). */
export function renderRGBA(bodies: RenderBody[], o: RenderOptions = {}): { width: number; height: number; data: Uint8Array } {
const size = o.size ?? 800;
const SS = 2; // drawn twice as big, then averaged down (smooth edges)
const W = size * SS;
const view = VIEWS[o.view ?? "iso"];
const fwd = norm(view.dir);
const right = norm(cross(view.up, fwd));
const up = cross(fwd, right);
const bg = rgb(o.background ?? "#eef0f3");
// Meshes in view space: x right, y up, z towards the viewer.
const meshes = bodies.flatMap((b) => {
try {
const m = b.shape.mesh({ tolerance: 0.05, angularTolerance: 0.15 });
let lines: number[] = [];
if (o.edges !== false) {
try {
lines = (b.shape as any).meshEdges({ tolerance: 0.05, angularTolerance: 0.15 }).lines as number[];
} catch {
lines = [];
}
}
return [{ v: m.vertices as number[], t: m.triangles as number[], lines, color: rgb(b.color ?? "#8fa3b8") }];
} catch {
return [];
}
});
const toView = (a: number[], i: number): V3 => {
const p: V3 = [a[i], a[i + 1], a[i + 2]];
return [dot(p, right), dot(p, up), dot(p, fwd)];
};
let lo: V3 = [Infinity, Infinity, Infinity];
let hi: V3 = [-Infinity, -Infinity, -Infinity];
for (const m of meshes)
for (let i = 0; i < m.v.length; i += 3) {
const p = toView(m.v, i);
lo = [Math.min(lo[0], p[0]), Math.min(lo[1], p[1]), Math.min(lo[2], p[2])];
hi = [Math.max(hi[0], p[0]), Math.max(hi[1], p[1]), Math.max(hi[2], p[2])];
}
const color = new Float32Array(W * W * 3);
for (let i = 0; i < W * W; i++) color.set(bg, i * 3);
const depth = new Float32Array(W * W).fill(-Infinity);
if (Number.isFinite(lo[0])) {
// Fit with a margin, centred.
const span = Math.max(hi[0] - lo[0], hi[1] - lo[1]) || 1;
const k = (W * 0.86) / span;
const cx = (lo[0] + hi[0]) / 2;
const cy = (lo[1] + hi[1]) / 2;
const px = (p: V3): V3 => [W / 2 + (p[0] - cx) * k, W / 2 - (p[1] - cy) * k, p[2]];
const light = norm([0.35, 0.55, 1]);
for (const m of meshes) {
const P: V3[] = [];
for (let i = 0; i < m.v.length; i += 3) P.push(px(toView(m.v, i)));
for (let t = 0; t < m.t.length; t += 3) {
const a = P[m.t[t]];
const b = P[m.t[t + 1]];
const c = P[m.t[t + 2]];
// The face's normal in view space (screen y is down: flip it back).
const n = norm(cross(sub([b[0], -b[1], b[2]], [a[0], -a[1], a[2]]), sub([c[0], -c[1], c[2]], [a[0], -a[1], a[2]])));
const facing = n[2] < 0 ? ([-n[0], -n[1], -n[2]] as V3) : n;
const shade = 0.38 + 0.62 * Math.max(0, dot(facing, light));
const col: V3 = [m.color[0] * shade, m.color[1] * shade, m.color[2] * shade];
fillTri(a, b, c, col, color, depth, W);
}
// Edges: dark, drawn where they are not behind a face.
const bias = (hi[2] - lo[2] || 1) * 2e-3;
for (let i = 0; i + 5 < m.lines.length; i += 6) {
const a = px(toView(m.lines, i));
const b = px(toView(m.lines, i + 3));
drawLine(a, b, [40, 44, 52], color, depth, W, bias, SS);
}
}
}
// Average each SS x SS block.
const data = new Uint8Array(size * size * 4);
for (let y = 0; y < size; y++)
for (let x = 0; x < size; x++) {
let r = 0,
g = 0,
b = 0;
for (let j = 0; j < SS; j++)
for (let i = 0; i < SS; i++) {
const q = ((y * SS + j) * W + x * SS + i) * 3;
r += color[q];
g += color[q + 1];
b += color[q + 2];
}
const o4 = (y * size + x) * 4;
data[o4] = r / (SS * SS);
data[o4 + 1] = g / (SS * SS);
data[o4 + 2] = b / (SS * SS);
data[o4 + 3] = 255;
}
return { width: size, height: size, data };
}
function fillTri(a: V3, b: V3, c: V3, col: V3, color: Float32Array, depth: Float32Array, W: number): void {
const x0 = Math.max(0, Math.floor(Math.min(a[0], b[0], c[0])));
const x1 = Math.min(W - 1, Math.ceil(Math.max(a[0], b[0], c[0])));
const y0 = Math.max(0, Math.floor(Math.min(a[1], b[1], c[1])));
const y1 = Math.min(W - 1, Math.ceil(Math.max(a[1], b[1], c[1])));
const area = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
if (Math.abs(area) < 1e-12) return;
for (let y = y0; y <= y1; y++)
for (let x = x0; x <= x1; x++) {
const px = x + 0.5;
const py = y + 0.5;
const w0 = ((b[0] - px) * (c[1] - py) - (b[1] - py) * (c[0] - px)) / area;
const w1 = ((c[0] - px) * (a[1] - py) - (c[1] - py) * (a[0] - px)) / area;
const w2 = 1 - w0 - w1;
if (w0 < 0 || w1 < 0 || w2 < 0) continue;
const z = w0 * a[2] + w1 * b[2] + w2 * c[2];
const i = y * W + x;
if (z <= depth[i]) continue;
depth[i] = z;
color[i * 3] = col[0];
color[i * 3 + 1] = col[1];
color[i * 3 + 2] = col[2];
}
}
function drawLine(a: V3, b: V3, col: V3, color: Float32Array, depth: Float32Array, W: number, bias: number, thick: number): void {
const steps = Math.ceil(Math.max(Math.abs(b[0] - a[0]), Math.abs(b[1] - a[1]))) + 1;
for (let s = 0; s <= steps; s++) {
const t = s / steps;
const x = a[0] + (b[0] - a[0]) * t;
const y = a[1] + (b[1] - a[1]) * t;
const z = a[2] + (b[2] - a[2]) * t;
for (let j = 0; j < thick; j++)
for (let i = 0; i < thick; i++) {
const X = Math.floor(x - thick / 2 + i + 0.5);
const Y = Math.floor(y - thick / 2 + j + 0.5);
if (X < 0 || Y < 0 || X >= W || Y >= W) continue;
const k = Y * W + X;
if (z + bias < depth[k]) continue;
color[k * 3] = col[0];
color[k * 3 + 1] = col[1];
color[k * 3 + 2] = col[2];
}
}
}
// ------------------------------------------------------------------ PNG
const CRC = (() => {
const t = new Uint32Array(256);
for (let n = 0; n < 256; n++) {
let c = n;
for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
t[n] = c >>> 0;
}
return t;
})();
function crc32(buf: Uint8Array): number {
let c = 0xffffffff;
for (const b of buf) c = CRC[(c ^ b) & 255] ^ (c >>> 8);
return (c ^ 0xffffffff) >>> 0;
}
function chunk(type: string, data: Uint8Array): Uint8Array {
const out = new Uint8Array(12 + data.length);
const dv = new DataView(out.buffer);
dv.setUint32(0, data.length);
out.set(Buffer.from(type, "ascii"), 4);
out.set(data, 8);
dv.setUint32(8 + data.length, crc32(out.subarray(4, 8 + data.length)));
return out;
}
/** RGBA pixels as a PNG file. */
export function encodePNG(width: number, height: number, rgba: Uint8Array): Uint8Array {
const raw = new Uint8Array(height * (width * 4 + 1));
for (let y = 0; y < height; y++) raw.set(rgba.subarray(y * width * 4, (y + 1) * width * 4), y * (width * 4 + 1) + 1);
const ihdr = new Uint8Array(13);
const dv = new DataView(ihdr.buffer);
dv.setUint32(0, width);
dv.setUint32(4, height);
ihdr.set([8, 6, 0, 0, 0], 8);
const parts = [new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10]), chunk("IHDR", ihdr), chunk("IDAT", deflateSync(raw)), chunk("IEND", new Uint8Array())];
const out = new Uint8Array(parts.reduce((s, p) => s + p.length, 0));
let at = 0;
for (const p of parts) out.set(p, at), (at += p.length);
return out;
}
/** Draw the bodies and write the picture to `file`. */
export function renderPNG(bodies: RenderBody[], file: string, o: RenderOptions = {}): void {
const { width, height, data } = renderRGBA(bodies, o);
writeFileSync(file, encodePNG(width, height, data));
}
// ------------------------------------------------------------------ command line
if (process.argv[1]?.replace(/\\/g, "/").endsWith("scripts/render.ts")) {
const args = process.argv.slice(2);
const [file, out] = args.filter((a, i) => !a.startsWith("--") && !args[i - 1]?.startsWith("--"));
if (!file || !out) {
console.log("Usage: npx tsx scripts/render.ts <project.super> <out.png> [--view iso|front|back|top|bottom|left|right] [--size 800]");
process.exit(2);
}
const { readFileSync } = await import("node:fs");
const opencascade = (await import("replicad-opencascadejs")).default;
const { setOC } = await import("replicad");
const { parseProject } = await import("../src/doc/store");
const { debugBodies, regenerate } = await import("../src/kernel/engine");
const doc = parseProject(readFileSync(file, "utf8"));
setOC(await (opencascade as unknown as () => Promise<any>)());
const r = await regenerate(doc.features);
for (const e of r.errors) console.log(`error in ${e.featureId}: ${e.message}`);
const hidden = new Set(doc.hidden ?? []);
const opt = (k: string) => (args.includes(k) ? args[args.indexOf(k) + 1] : undefined);
renderPNG(
[...debugBodies()].filter(([id]) => !hidden.has(id)).map(([id, shape]) => ({ shape, color: doc.colors?.[id] })),
out,
{ view: (opt("--view") as RenderOptions["view"]) ?? "iso", size: Number(opt("--size") ?? 800) },
);
console.log(`Picture: ${out}`);
}
+325
View File
@@ -0,0 +1,325 @@
// The console's handle on the app: `sg` - read what's there and work the tools
// without tapping at pixels. For checking the app by hand or by script (the
// browser's console, or a test driving the page). Type sg.help() to list it.
//
// sg.state() the project, tool, hint, panel, selection, errors, bodies
// sg.select(sg.sel.body("Box")) pick something (as a tap would)
// sg.actions() what the picked thing offers (left column, bottom bar)
// sg.run("Project as Sketch") run one (by id or label, also in sub-menus)
// sg.panel() the open tool's window: slots, values, choices
// sg.set("XY") sg.set("Height", 2) sg.set("Sink in", true)
// sg.pick(sg.sel.face("Box", 3)) give the waiting slot a face / edge / plane…
// sg.done() sg.cancel() await sg.idle() await sg.health()
import type { App } from "./app";
import type { ToolItem, PanelItem } from "./ui/ui";
import type { Feature } from "./doc/types";
import type { Sel } from "./tools/tool";
import type { PickHit } from "./view/viewport";
import type { ProjectDoc } from "./doc/types";
import { parseProject } from "./doc/store";
import { newProjectId } from "./doc/library";
// (The app's insides it reads: kept out of the classes' public faces on purpose.)
interface Insides {
tool: { id: string; editingId?: string; activeSketch?: string; slots?: { label: string; accept(h: PickHit): boolean; multi?: boolean }[]; active?: number; advance?(): void; render?(): void; update?(): void };
regenerate(): Promise<void>;
undo(): void;
redo(): void;
switchProject(doc: ProjectDoc, id: string): Promise<void>;
}
interface UIInsides {
toolItems: ToolItem[];
bottomItems: ToolItem[];
panelSpec: { title: string; items?: PanelItem[]; fields?: { label: string; value: number; onInput(v: number): void }[]; actions?: ToolItem[]; onDone?(): void; onCancel?(): void } | null;
hintText: string | null;
recentToasts?: string[];
}
interface Listed {
id: string;
label: string;
/** Where it sits: "Sketch › Rectangle". */
path: string;
disabled?: boolean;
why?: string;
item: ToolItem;
}
function flatten(items: ToolItem[], path: string[] = []): Listed[] {
// (Separators have no label.)
return items.filter((it) => it.label).flatMap((it) => [
{ id: it.id, label: it.label, path: [...path, it.label].join(" › "), ...(it.disabled ? { disabled: true, why: it.why } : {}), item: it },
...flatten(it.children ?? [], [...path, it.label]),
]);
}
const plain = (l: Listed[]) => l.map(({ item: _, ...rest }) => rest);
const same = (a: string, b: string) => a.trim().toLowerCase() === b.trim().toLowerCase();
export function installDebug(app: App): void {
const inside = app as unknown as Insides;
const ui = app.ui as unknown as UIInsides;
const features = () => app.store.doc.features;
/** A step or body by id or name. */
const featureOf = (key: string): Feature | undefined => features().find((f) => f.id === key) ?? features().find((f) => same(f.name, key));
const bodyId = (key: string): string => {
const list = app.view.bodyList;
const names = app.store.doc.names ?? {};
return list.find((b) => b.id === key)?.id ?? list.find((b) => same(names[b.id] ?? b.name, key))?.id ?? key;
};
const panelItems = (): PanelItem[] => {
const spec = ui.panelSpec;
if (!spec) return [];
const fields: PanelItem[] = (spec.fields ?? []).map((f) => ({ type: "number", label: f.label, value: f.value, onInput: f.onInput }));
return [...fields, ...(spec.items ?? [])];
};
const shown = (): ToolItem[] => [...ui.toolItems, ...ui.bottomItems, ...(ui.panelSpec?.actions ?? [])];
const sg = {
app,
/** What's there now, in one look. */
state() {
const r = app.result;
const byId = new Map(features().map((f) => [f.id, f.name]));
return {
project: app.store.doc.name,
tool: inside.tool.id,
editing: inside.tool.editingId ?? inside.tool.activeSketch ?? null,
hint: ui.hintText,
panel: ui.panelSpec?.title ?? null,
selection: app.selection,
steps: features().length,
errors: (r?.errors ?? []).map((e) => `${byId.get(e.featureId) ?? e.featureId}: ${e.message}`),
notes: (r?.notes ?? []).map((e) => `${byId.get(e.featureId) ?? e.featureId}: ${e.message}`),
toasts: ui.recentToasts?.slice(-5) ?? [],
bodies: sg.bodies(),
};
},
/** The steps in History: id, name, type, switched off, its error. */
steps() {
const errs = new Map((app.result?.errors ?? []).map((e) => [e.featureId, e.message]));
return features().map((f, i) => ({ i: i + 1, id: f.id, name: f.name, type: f.type, ...(f.suppressed ? { off: true } : {}), ...(errs.has(f.id) ? { error: errs.get(f.id) } : {}) }));
},
/** A step as stored (by id or name). */
step: (key: string) => featureOf(key),
/** The bodies shown: id, name, how many faces and edges, hidden. */
bodies() {
const names = app.store.doc.names ?? {};
const hidden = new Set(app.store.doc.hidden);
return app.view.bodyList.map((b) => ({ id: b.id, name: names[b.id] ?? b.name, faces: b.faces.length, edges: b.edges.length, ...(hidden.has(b.id) ? { hidden: true } : {}) }));
},
/** Each body measured on the solid: valid, closed, solids, faces, volume, box. */
health: () => app.kernel.health(features()),
/** The main tools (the left column with nothing picked, with their sub-menus). */
tools: () => plain(flatten(app.mainTools())),
/** What's offered now: the left column (what the picked thing offers), the bottom bar, the open window's buttons. */
actions: () => plain(flatten(shown())),
/** Run a tool or action by id or label (what's offered now first, then the main tools). */
run(key: string): string {
const all = [...flatten(shown()), ...flatten(app.mainTools())];
const hit = all.find((x) => x.id === key) ?? all.find((x) => same(x.label, key)) ?? all.find((x) => same(x.path, key));
if (!hit) return `No "${key}" here. sg.actions() / sg.tools() list what there is.`;
if (hit.disabled) return `"${hit.label}" is off: ${hit.why ?? "(no reason given)"}`;
if (!hit.item.run) return `"${hit.label}" opens a menu: ${(hit.item.children ?? []).map((c) => c.label).join(", ")}`;
hit.item.run();
return `ran ${hit.path}`;
},
/** Pick things, as taps would (sg.sel builds them). */
select(...sel: Sel[]) {
app.setSelection(sel);
return app.selection;
},
/** Things to pick, by name or id. */
sel: {
body: (body: string): Sel => ({ kind: "body", body: bodyId(body) }),
face: (body: string, face: number): Sel => ({ kind: "face", body: bodyId(body), face }),
edge: (body: string, edge: number): Sel => ({ kind: "edge", body: bodyId(body), edge }),
vertex: (body: string, vertex: number): Sel => ({ kind: "vertex", body: bodyId(body), vertex }),
/** A sketch's closed shape (regions counted as the sketch finds them). */
profile: (sketch: string, region = 0): Sel => ({ kind: "profile", sketch: featureOf(sketch)?.id ?? sketch, region }),
curve: (sketch: string, entity: string): Sel => ({ kind: "curve", sketch: featureOf(sketch)?.id ?? sketch, entity }),
plane: (id: string): Sel => ({ kind: "plane", id: featureOf(id)?.id ?? id }),
axis: (id: string): Sel => ({ kind: "axis", id: featureOf(id)?.id ?? id }),
origin: (): Sel => ({ kind: "origin" }),
},
/** A body's faces: index, type, centre, normal, area (to find the one to pick). */
faces(body: string) {
return (app.view.body(bodyId(body))?.faces ?? []).map((f, i) => ({ i, type: f.type, center: f.center, normal: f.normal, area: +f.area.toFixed(3), ...(f.round ? { round: f.round } : {}) }));
},
/** A body's edges: index, type, ends. */
edges(body: string) {
return (app.view.body(bodyId(body))?.edges ?? []).map((e, i) => ({ i, type: e.type, start: e.start, mid: e.mid, end: e.end, length: +e.length.toFixed(3) }));
},
/** The open tool's window: title, rows (slots, numbers, choices, toggles), buttons. */
panel() {
const spec = ui.panelSpec;
if (!spec) return null;
return {
title: spec.title,
rows: panelItems().map((it) => {
switch (it.type) {
case "number":
case "slider":
case "toggle":
return { type: it.type, label: it.label, value: it.value };
case "slot":
return { type: it.type, label: it.label, value: it.value, ...(it.active ? { waiting: true } : {}), filled: it.filled };
case "choice":
return { type: it.type, label: it.label ?? "", value: it.value, options: it.options.map((o) => o.label) };
case "button":
return { type: it.type, label: it.label };
case "chips":
return { type: it.type, label: it.label ?? "", chips: it.chips.map((c) => c.label + (c.on ? " (on)" : "")) };
default:
return { type: (it as { type: string }).type };
}
}),
buttons: (spec.actions ?? []).map((a) => a.label),
};
},
/**
* Set a row of the open window by its label: a number, a toggle, a choice
* (or just a choice's option: sg.set("XY")), a slot to fill next, a button.
*/
set(label: string, value?: number | boolean | string): string {
const items = panelItems();
const row = items.find((it) => "label" in it && it.label && same(it.label, label));
if (row) {
switch (row.type) {
case "number":
case "slider":
row.onInput(Number(value));
return `${row.label} = ${value}`;
case "toggle":
row.onChange(value === undefined ? !row.value : !!value);
return `${row.label} ${value === undefined ? !row.value : !!value ? "on" : "off"}`;
case "choice": {
const o = row.options.find((x) => x.id === value || same(x.label, String(value)));
if (!o) return `${row.label}: no "${value}" (${row.options.map((x) => x.label).join(", ")})`;
row.onChange(o.id);
return `${row.label} = ${o.label}`;
}
case "slot":
row.onClick();
return `${row.label}: waiting for a pick`;
case "button":
row.onClick();
return `pressed ${row.label}`;
}
}
// An option of a choice with no label (the X / Y / Z, XY / XZ / YZ by a slot), or a chip.
for (const it of items) {
if (it.type === "choice") {
const o = it.options.find((x) => same(x.label, label));
if (o) {
it.onChange(o.id);
return `chose ${o.label}`;
}
}
if (it.type === "chips") {
const c = it.chips.find((x) => same(x.label, label));
if (c) {
c.onClick();
return `tapped ${c.label}`;
}
}
}
const btn = ui.panelSpec?.actions?.find((a) => same(a.label, label) || a.id === label);
if (btn?.run) {
btn.run();
return `pressed ${btn.label}`;
}
return `No "${label}" in the window. sg.panel() lists its rows.`;
},
/** Give the open tool's waiting slot a pick (a face, edge, profile, plane…), as a tap on it would. */
pick(sel: Sel, point?: [number, number, number]): string {
const t = inside.tool;
const slot = t.slots?.[t.active ?? -1];
if (!slot) return "No slot waiting (sg.set(<slot label>) makes one wait).";
let at = point;
if (!at && (sel.kind === "face" || sel.kind === "edge")) {
const b = app.view.body(sel.body);
at = sel.kind === "face" ? b?.faces[sel.face]?.center : b?.edges[sel.edge]?.mid;
}
const hit = { ...sel, point: at ?? [0, 0, 0] } as PickHit;
if (!slot.accept(hit)) return `${slot.label} doesn't take that.`;
t.advance?.();
t.render?.();
t.update?.();
return `${slot.label}: picked`;
},
/** Done / Cancel in the open tool's window. */
done(): string {
const spec = ui.panelSpec;
if (!spec?.onDone) return "No window with Done open.";
spec.onDone();
return `done: ${spec.title}`;
},
cancel(): string {
const spec = ui.panelSpec;
if (spec?.onCancel) spec.onCancel();
else app.setTool(null);
return "cancelled";
},
undo: () => inside.undo(),
redo: () => inside.redo(),
/** Wait until the geometry engine has nothing left to do (and the page has drawn it). */
async idle(timeoutMs = 30000): Promise<boolean> {
const k = app.kernel as unknown as { pending: Map<number, unknown>; regenRunning: boolean };
const t0 = performance.now();
let quiet = 0;
while (performance.now() - t0 < timeoutMs) {
await new Promise((r) => setTimeout(r, 50));
quiet = k.pending.size || k.regenRunning ? 0 : quiet + 1;
if (quiet >= 3) return true;
}
return false;
},
/** The project as saved (JSON). */
save: () => JSON.stringify(app.store.doc),
/**
* Open a project (its JSON, as text or object) as a new one in the
* library, as File → Open does; the one open now is kept. Resolves once
* it is built.
*/
async load(project: string | object, name?: string): Promise<string> {
const doc = parseProject(typeof project === "string" ? project : JSON.stringify(project));
if (name) doc.name = name;
await inside.switchProject(doc, newProjectId());
await sg.idle();
return doc.name;
},
/** What there is, with one line each. */
help(): number {
const lines: string[] = Object.entries(sg as Record<string, unknown>)
.filter(([k]) => k !== "app")
.map(([k, v]) => (typeof v === "function" ? `sg.${k}(${((v as () => void).toString().match(/^[^(]*\(([^)]*)\)/)?.[1] ?? "").replace(/\s+/g, " ")})` : `sg.${k}`));
console.log(lines.join("\n"));
return lines.length;
},
};
(window as unknown as { sg: typeof sg }).sg = sg;
}
+9 -1
View File
@@ -1,5 +1,5 @@
import type { Feature } from "../doc/types";
import type { BodyMesh, BodyProps, ProjectedView, ViewSpec, Envelope, ExportFormat, RegenResult, Request, Response } from "./protocol";
import type { BodyHealth, BodyMesh, BodyProps, ProjectedView, ViewSpec, Envelope, ExportFormat, RegenResult, Request, Response } from "./protocol";
/**
* The steps as the engine needs them: a reference image without its picture
@@ -234,6 +234,14 @@ export class KernelClient {
throw new Error(r.type === "error" ? r.message : "Could not measure the bodies");
}
/** Each body's health: valid, closed, solids, faces, volume (the console's sg.health()). */
async health(features: Feature[]): Promise<BodyHealth[]> {
await this.ready;
const r = await this.call({ type: "health", features: lean(features) });
if (r.type === "health") return r.bodies;
throw new Error(r.type === "error" ? r.message : "Could not check the bodies");
}
async export(features: Feature[], format: ExportFormat, bodies?: string[]): Promise<Blob> {
await this.ready;
const r = await this.call({ type: "export", features: lean(features), format, bodies });
+23 -2
View File
@@ -61,7 +61,7 @@ import { carried } from "../sketch/follow";
import { cageToShape } from "./freeform";
import { evenly, gentle, guideCurve, oriented, plainSpine, smoothed } from "../freeform/connect";
import { deepCopy, hairThin, meshVolume, openEdges, shapeValid, subShapes } from "./health";
import { healthOf, repairShape } from "./repair";
import { healthOf, isHealthy, repairShape } from "./repair";
export { shapeValid } from "./health";
import { applyPlan, boundaryEdges, cachedPlan, deleteFaces, isClosed, selfCrossings, subdivide } from "../freeform/cage";
import { useSafeBooleans } from "./safeBooleans";
@@ -77,7 +77,7 @@ import { anchorOf, freeformFaces, meshViews, viewEdge } from "./viewLines";
import { entitiesWire, regionFaces, regionHoleWires, regionWire, withFittedSplines } from "./sketchGeom";
import { stretchShape } from "./stretch";
import { imprint, onFace as linesOnFace, seenFrom, wrapOnto } from "./wrap";
import type { BodyMesh, BodyProps, ProjectedView, ViewBody, ViewEdge, ViewSpec, ConstructionInfo, EdgeInfo, ExportFormat, FaceInfo, FeatureError, RegenResult } from "./protocol";
import type { BodyHealth, BodyMesh, BodyProps, ProjectedView, ViewBody, ViewEdge, ViewSpec, ConstructionInfo, EdgeInfo, ExportFormat, FaceInfo, FeatureError, RegenResult } from "./protocol";
type Bodies = Map<string, Shape3D>;
type SketchState = SketchFeature & { boundary: SketchEntity[] };
@@ -359,6 +359,27 @@ export async function bodyProperties(features: Feature[]): Promise<BodyProps[]>
});
}
/** Each body's health: valid, closed, solids, faces, volume (for checking a model from the console or the command line). */
export async function bodyHealth(features: Feature[]): Promise<BodyHealth[]> {
const { ctx, numbers } = await run(features);
const names = bodyNames(features, [...ctx.bodies.keys()], numbers);
return [...ctx.bodies.entries()].map(([id, s]) => healthReport(id, names.get(id) ?? id, s));
}
/** One body's health (also for tests and scripts that hold the solid). */
export function healthReport(id: string, name: string, s: Shape3D): BodyHealth {
const h = healthOf(s);
let edges = 0;
let box: [Vec3, Vec3] = [[0, 0, 0], [0, 0, 0]];
try {
edges = s.edges.length;
box = s.boundingBox.bounds as [Vec3, Vec3];
} catch {
// a broken shape: what healthOf found is the news
}
return { id, name, ...h, edges, box, healthy: isHealthy(h) };
}
/**
* Drawings: the bodies seen along each view's direction, with hidden line
* removal (OpenCascade's exact HLR), each body's edges kept apart so a balloon
+24
View File
@@ -103,6 +103,28 @@ export interface BodyProps {
box: [Vec3, Vec3];
}
/**
* A body's health, measured on the solid (for checking a model from the
* console or the command line): valid, closed, how many solids and faces.
*/
export interface BodyHealth {
id: string;
name: string;
valid: boolean;
solids: number;
shells: number;
openEdges: number;
/** Hair-thin faces. */
thin: number;
volume: number;
faces: number;
edges: number;
/** Its box: lowest corner, highest corner. */
box: [Vec3, Vec3];
/** Valid, closed, no hair-thin faces, a real volume. */
healthy: boolean;
}
/** A view to draw: the model seen from `dir` (towards the viewer), `xAxis` to the right on the paper. */
export interface ViewSpec {
id: string;
@@ -149,6 +171,7 @@ export type Request =
| { type: "regenerate"; features: Feature[]; saved?: boolean }
| { type: "export"; features: Feature[]; format: ExportFormat; bodies?: string[] }
| { type: "properties"; features: Feature[] }
| { type: "health"; features: Feature[] }
| { type: "drawing"; features: Feature[]; views: ViewSpec[]; bodies?: string[] };
export type Response =
@@ -156,6 +179,7 @@ export type Response =
| { type: "regenerated"; result: RegenResult }
| { type: "exported"; blob: Blob }
| { type: "properties"; bodies: BodyProps[] }
| { type: "health"; bodies: BodyHealth[] }
| { type: "drawing"; views: ProjectedView[] }
| { type: "error"; message: string };
+4 -1
View File
@@ -4,7 +4,7 @@
import opencascade from "replicad-opencascadejs";
import wasmUrl from "replicad-opencascadejs/wasm?url";
import { setOC } from "replicad";
import { bodyProperties, projectViews, errorText, exportBodies, regenerate, resetKernel, withFreshKernel } from "./engine";
import { bodyHealth, bodyProperties, projectViews, errorText, exportBodies, regenerate, resetKernel, withFreshKernel } from "./engine";
import type { BodyMesh, Envelope, Request, Response } from "./protocol";
/**
@@ -68,6 +68,9 @@ async function handle(e: MessageEvent<Envelope<Request>>): Promise<void> {
case "properties":
reply({ type: "properties", bodies: await withFreshKernel(load, () => bodyProperties(msg.features)) });
break;
case "health":
reply({ type: "health", bodies: await withFreshKernel(load, () => bodyHealth(msg.features)) });
break;
}
} catch (err) {
console.error(err);
+3
View File
@@ -1,6 +1,7 @@
import "./style.css";
import { App } from "./app";
import { outerScrollbars } from "./ui/scrollbars";
import { installDebug } from "./debug";
// Update reloads with ?v=<time> so no stored copy is used; once loaded, the
// address is plain again (it's what people copy to share the app).
@@ -18,3 +19,5 @@ outerScrollbars();
const app = new App(document.getElementById("view") as HTMLCanvasElement);
// Handy for debugging from the console.
(window as unknown as { supergeometry: App }).supergeometry = app;
// And sg: read and work the app from the console (sg.help()).
installDebug(app);
+5
View File
@@ -572,7 +572,12 @@ export class UI {
document.getElementById("ctx-menu")?.remove();
}
/** The last few toasts (the console's sg.state() shows them: they fade before you can read them). */
readonly recentToasts: string[] = [];
toast(text: string, kind: "info" | "error" = "info"): void {
this.recentToasts.push(text);
if (this.recentToasts.length > 20) this.recentToasts.shift();
this.toastEl.textContent = text;
this.toastEl.className = `show ${kind}`;
// Never over what's being typed into (a value box, the numpad, the tool panel): then it shows up top.
+107
View File
@@ -0,0 +1,107 @@
// Shared pieces of the tests: the geometry engine started once, pass/fail
// counting, and quick ways to write sketches, shapes and steps.
//
// import { check, done, sketch, rect, circle, extrude, XY, after } from "./kit";
// const fs = [sketch("s", XY(), [rect("r", 0, 0, 10, 10)]), extrude("E", "s", 5)];
// const { body, err } = await after(fs, "E");
// check("a 10 x 10 x 5 block", !err && Math.abs(volume(body) - 500) < 1e-6);
// done();
import opencascade from "replicad-opencascadejs";
import { measureVolume, setOC, type Shape3D } from "replicad";
import { debugBodies, healthReport, regenerate } from "../src/kernel/engine";
import { arrangement, regionRef } from "../src/sketch/regions";
import type { Feature, PlaneDef, SketchEntity, Vec3 } from "../src/doc/types";
import type { BodyHealth, RegenResult } from "../src/kernel/protocol";
setOC(await (opencascade as unknown as () => Promise<any>)());
// ------------------------------------------------------------------ results
let failed = 0;
let passed = 0;
/** One check: printed as ok or FAIL, with what was found when it fails (or always, if given). */
export function check(name: string, ok: boolean, info: unknown = ""): boolean {
if (ok) passed++;
else failed++;
console.log(ok ? "ok " : "FAIL", name, typeof info === "string" ? info : JSON.stringify(info));
return ok;
}
/** Near enough: |a - b| <= tol. */
export const near = (a: number, b: number, tol = 1e-6) => Math.abs(a - b) <= tol;
/** The end of a test file: the count, and the exit code. */
export function done(): never {
console.log(failed ? `${failed} failed, ${passed} passed` : `all ${passed} passed`);
process.exit(failed ? 1 : 0);
}
// ------------------------------------------------------------------ planes
export const XY = (z = 0): PlaneDef => ({ origin: [0, 0, z], xDir: [1, 0, 0], normal: [0, 0, 1] });
/** Seen from the front: x to the right, z up. */
export const XZ = (y = 0): PlaneDef => ({ origin: [0, y, 0], xDir: [1, 0, 0], normal: [0, -1, 0] });
export const YZ = (x = 0): PlaneDef => ({ origin: [x, 0, 0], xDir: [0, 1, 0], normal: [1, 0, 0] });
export const plane = (origin: Vec3, normal: Vec3, xDir: Vec3): PlaneDef => ({ origin, normal, xDir });
// ------------------------------------------------------------------ sketches
export const rect = (id: string, x0: number, y0: number, x1: number, y1: number): SketchEntity =>
({ id, kind: "polyline", points: [[x0, y0], [x1, y0], [x1, y1], [x0, y1]], closed: true }) as SketchEntity;
export const circle = (id: string, x: number, y: number, r: number): SketchEntity => ({ id, kind: "circle", center: [x, y], radius: r }) as SketchEntity;
export const line = (id: string, a: [number, number], b: [number, number]): SketchEntity => ({ id, kind: "line", a, b }) as SketchEntity;
export const poly = (id: string, points: [number, number][], closed = true): SketchEntity => ({ id, kind: "polyline", points, closed }) as SketchEntity;
export const sketch = (id: string, plane: PlaneDef, entities: SketchEntity[], name = id): Feature => ({ id, name, type: "sketch", plane, entities }) as Feature;
/** Every closed shape of the sketch's curves (or those `pick` keeps). */
export function profile(sketchId: string, entities: SketchEntity[], pick?: (regions: ReturnType<typeof regionRef>[]) => ReturnType<typeof regionRef>[]) {
const regions = arrangement(entities).regions.map(regionRef);
return { kind: "profile" as const, sketch: sketchId, regions: pick ? pick(regions) : regions };
}
/** The entities of a sketch step made above. */
const entitiesOf = (fs: Feature[], id: string) => (fs.find((f) => f.id === id) as { entities: SketchEntity[] } | undefined)?.entities ?? [];
// ------------------------------------------------------------------ steps
/** An extrude of the sketch's shapes (all of them, given its entities or the steps holding it). */
export function extrude(id: string, sk: Feature | string, distance: number, mode: "new" | "add" | "cut" = "new", extra: Record<string, unknown> = {}): Feature {
const sid = typeof sk === "string" ? sk : sk.id;
const es = typeof sk === "string" ? [] : (sk as { entities: SketchEntity[] }).entities;
return { id, name: id, type: "extrude", source: profile(sid, es), distance, mode, ...extra } as Feature;
}
/** A block w x d x h from the origin (a sketch and its extrude). */
export function block(id: string, w: number, d: number, h: number, at: Vec3 = [0, 0, 0]): Feature[] {
const s = sketch(`${id}-s`, XY(at[2]), [rect(`${id}-r`, at[0], at[1], at[0] + w, at[1] + d)]);
return [s, extrude(id, s, h)];
}
/** A cylinder of radius r and height h standing on the XY plane at (x, y). */
export function cylinder(id: string, r: number, h: number, x = 0, y = 0, z = 0): Feature[] {
const s = sketch(`${id}-s`, XY(z), [circle(`${id}-c`, x, y, r)]);
return [s, extrude(id, s, h)];
}
// ------------------------------------------------------------------ results
/** Rebuild the steps: the result, the solid of one body (by its id), and the first error. */
export async function after(fs: Feature[], bodyId?: string): Promise<{ r: RegenResult; body: Shape3D | undefined; err?: string; errors: string[] }> {
const r = await regenerate(fs);
const bodies = debugBodies();
const body = bodyId ? bodies.get(bodyId) : [...bodies.values()][0];
const errors = r.errors.map((e) => `${e.featureId}: ${e.message}`);
return { r, body, err: r.errors[0]?.message, errors };
}
/** The solids of the last rebuild, by body id. */
export const bodies = () => debugBodies();
export const volume = (s: Shape3D | undefined) => (s ? measureVolume(s) : 0);
/** A body's health: valid, closed, solids, faces, volume, box. */
export const health = (s: Shape3D, id = "body"): BodyHealth => healthReport(id, id, s);
export { entitiesOf };
+5 -20
View File
@@ -1,36 +1,22 @@
// Run: npx tsx tests/wrap.test.ts - Project as Edge (a sketch drawn onto the
// faces seen from it, or edges onto a face: the faces split along them) and
// Wrap & Emboss (a sketch wrapped round a round face, raised or sunk).
import opencascade from "replicad-opencascadejs";
import { measureVolume, setOC } from "replicad";
import { after, check, done, profile, rect, sketch, XY } from "./kit";
import { measureVolume } from "replicad";
import { debugBodies, regenerate } from "../src/kernel/engine";
import { healthOf, isHealthy } from "../src/kernel/repair";
import { arrangement, regionRef } from "../src/sketch/regions";
import { projectRegions } from "../src/sketch/edit";
import type { Feature, PlaneDef } from "../src/doc/types";
setOC(await (opencascade as unknown as () => Promise<any>)());
let failed = 0;
const check = (name: string, ok: boolean, info = "") => {
if (!ok) failed++;
console.log(ok ? "ok " : "FAIL", name, info);
};
const sketch = (id: string, plane: PlaneDef, es: any[]): Feature => ({ id, name: id, type: "sketch", plane, entities: es }) as Feature;
const profile = (sk: string, es: any[]) => ({ kind: "profile" as const, sketch: sk, regions: arrangement(es).regions.map(regionRef) });
const rect = (id: string, x0: number, y0: number, x1: number, y1: number) => ({ id, kind: "polyline", points: [[x0, y0], [x1, y0], [x1, y1], [x0, y1]], closed: true });
const XY = (z: number): PlaneDef => ({ origin: [0, 0, z], xDir: [1, 0, 0], normal: [0, 0, 1] });
// A 100 x 60 x 20 box.
const boxEs = [rect("b", 0, 0, 100, 60)];
const box: Feature[] = [sketch("bs", XY(0), boxEs), { id: "B", name: "Box", type: "extrude", source: profile("bs", boxEs), distance: 20, mode: "new" } as Feature];
const circle = [{ id: "c", kind: "circle", center: [50, 30], radius: 10 }];
async function bodyAfter(fs: Feature[], id: string): Promise<{ s: any; err?: string }> {
const r: any = await regenerate(fs);
const s = [...debugBodies()].find(([k]) => k === id)?.[1];
return { s, err: r.errors[0]?.message };
const { body, err } = await after(fs, id);
return { s: body, err };
}
const v0 = 100 * 60 * 20;
@@ -119,5 +105,4 @@ check("a plane across the axis: asked for one along it", /along the round face's
check("two shapes side by side: the side they share drawn once (7 lines)", both.length === 7 && both.every((e) => e.kind === "line"), String(both.length));
}
console.log(failed ? `${failed} failed` : "all passed");
process.exit(failed ? 1 : 0);
done();
+39 -2
View File
@@ -1,3 +1,4 @@
import { execSync } from "node:child_process";
import { readFileSync, readdirSync, statSync, writeFileSync } from "node:fs";
import { join, relative } from "node:path";
import { defineConfig, type Plugin } from "vite";
@@ -17,7 +18,7 @@ function offlineFiles(): Plugin {
outDir = c.build.outDir;
},
closeBundle() {
const skip = new Set(["_headers", "robots.txt", "sitemap.xml", "og-image.png", "sw.js", "offline-files.json"]);
const skip = new Set(["_headers", "robots.txt", "sitemap.xml", "og-image.png", "sw.js", "offline-files.json", "version.json"]);
const files: string[] = [];
const walk = (dir: string) => {
for (const n of readdirSync(dir)) {
@@ -38,6 +39,42 @@ function offlineFiles(): Plugin {
};
}
/**
* What is live: dist/version.json names the commit it was built from and the
* main script, so `npm run live` (or a glance at /version.json) tells whether
* a push has reached the site.
*/
function versionFile(): Plugin {
let outDir = "dist";
return {
name: "version-file",
apply: "build",
configResolved(c) {
outDir = c.build.outDir;
},
closeBundle() {
const git = (cmd: string) => {
try {
return execSync(`git ${cmd}`, { stdio: ["ignore", "pipe", "ignore"] }).toString().trim();
} catch {
return "";
}
};
// The build server's own name for the commit when it has no git folder.
const commit = git("rev-parse HEAD") || process.env.WORKERS_CI_COMMIT_SHA || process.env.CF_PAGES_COMMIT_SHA || "";
const html = readFileSync(join(outDir, "index.html"), "utf8");
const info = {
version: pkg.version,
commit,
subject: commit ? git(`log -1 --format=%s ${commit}`) : "",
script: html.match(/index-[\w-]+\.js/)?.[0] ?? "",
built: new Date().toISOString(),
};
writeFileSync(join(outDir, "version.json"), JSON.stringify(info, null, 2));
},
};
}
export default defineConfig({
// Relative base so the build works from any static host sub-path (GitHub Pages etc.).
base: "./",
@@ -45,5 +82,5 @@ export default defineConfig({
worker: { format: "es" },
optimizeDeps: { exclude: ["replicad-opencascadejs"] },
build: { target: "es2022", chunkSizeWarningLimit: 4000 },
plugins: [offlineFiles()],
plugins: [offlineFiles(), versionFile()],
});