A modeler on this kernel runs one loop: show the model, find what the user
points at, run a verb on it, show the change, and let the user undo. This
page walks that loop with the public API of
@commonplace-technologies/kernel, nothing else. Every snippet here runs,
in this order, as src/core/integration/kernel-build-a-modeler.test.ts.
What the kernel does not do is listed under Where the kernel stops: input and snapping, scenes and rendering are the host's.
import { Matrix4 } from 'three';
import {
HalfEdgeMesh, draw, kernelQuery, kernelTessellation, loadKernel,
erase, loadMesh, meshVerbContext, offset, planTransform, saveMesh,
transformEntities, validate,
} from '@commonplace-technologies/kernel';
await loadKernel();
const mesh = new HalfEdgeMesh();
const ctx = meshVerbContext(mesh); // the mesh and its undo history
loadKernel() loads every part of the kernel that otherwise loads on
first use (solvers, evaluators, the exact Boolean, validator rules). Await
it once before the first edit; nothing after it waits for a load (a host
with a first-frame budget loads each part as it goes instead:
Loading). A
HalfEdgeMesh is one model: any number of solids, sheets, wires and
points, in one frame, Z up, unitless.
Frame and units. The kernel is Z up; three.js defaults to Y up, so set
camera.up.set(0, 0, 1)(or rotate the scene) before you draw. A mesh is unitless: the host says what a unit is. Where a unit has to be named, the kernel says which: STEP reads and writes meters, so a mesh read from STEP is in meters and one written to STEP is taken to be; paper output (paperModel,paperPageSVG,paperPDF) treats a model unit as a meter atscale: 1and sizes the page in millimeters.
meshVerbContext(mesh) pairs the mesh with a MeshHistory, the undo
stack every verb on that context commits to. Keep one per open model.
const box = await draw.cuboid(ctx, {
base: { shape: 'rectangle', corners: [[0, 0, 0], [4, 0, 0], [4, 3, 0], [0, 3, 0]] },
height: 2.5,
});
if (!box.ok) console.log(box.error?.code, box.error?.message);
console.log(box.created.faces); // the six new faces' ids
Shapes made from parameters are members of draw (draw.line,
draw.rectangle, draw.arc, draw.cuboid, …). Verbs that act on
geometry already there are bare names: offset (push a face, inset,
wall), develop, fold, loft, revolve, sweep, fillet, unite,
subtract, move and the rest; the API reference
lists them with their parameters.
Every verb resolves to a VerbResult:
| Field | Meaning |
|---|---|
ok |
It committed. |
value |
The verb's own answer, when it has one. |
error |
{ code, message } when it refused: code is a stable tag to branch on, message a sentence to show the user. |
notices |
Status lines and warnings it raised while it ran, each with a code. |
created, removed |
The ids of the vertices, half-edges and faces it made and removed. |
A refused verb leaves the mesh exactly as it was: no partial edit to clean up, and no step on the history.
const refused = await offset(ctx, { mode: 'push', faceIds: ['no-such-face'], distance: 1 });
refused.ok; // false
refused.error?.code; // a stable tag
Each verb's codes are a typed union (RefusalCode<'offset'>), so a
switch on code is checked, and canRun(ctx, verb, operands) asks
whether a verb would accept its operands before the amount is chosen,
changing nothing: Refusals and canRun.
To preview a drag or a typed value, pass { dryRun: true } as a verb's
third argument: the result is the commit's, with the frame of the model
it would leave, and nothing is kept: Dry runs.
const tess = kernelTessellation(mesh);
const frame = tess.frame({ curvature: false, faceDebug: false });
for (const f of frame.faces) {
// f.face.id, f.positions and f.normals (Float32Array, x y z per vertex),
// f.triangleVertexCount (three per triangle)
}
for (const e of frame.edges) {
// e.id, e.points (Float64Array, x y z per point, start to end), e.soft, e.crease
}
Keep one tessellation per mesh and call frame() once per redraw. A frame
re-emits only what changed since the last one: reemittedFaces and
reemittedEdges name them, and spliced says where each record of the
last frame went, so a renderer can update its buffers in place rather
than rebuild them. Triangles follow curved surfaces within a deviation
scaled to the model; pass linear (from the model's tolerance context) to
draw finer.
Faces and edges carry their kernel ids, so a GPU pick buffer can be
written straight from a frame. frame.faces[i].cornerIds names the model
vertex under each corner slot, for a host that drags vertices.
A host turns the cursor into a ray in the model's frame (through its own camera and, if it places the model, through the inverse of that placement) and asks:
const q = kernelQuery(mesh);
const hit = q.pickFace([1, 1, 10], [0, 0, -1]);
// { faceId, point: [x, y, z], distance } or null
const near = q.pickEdge([1, -0.01, 10], [0, 0, -1], 0.05);
// { edgeId, point, distance, gap } or null: the edge within 0.05 of the ray
pickFace meets each face on its own surface and inside its trim: a ray
through a window in a wall goes on to whatever is behind it. Hidden faces
are passed over. pickEdge takes a gap in model units; a host that wants
a pixel tolerance converts it at the hit's depth. Both scan the whole
model, which is fine at the sizes the kernel targets; a host with its own
spatial index can screen candidates first.
Then read what was picked, by id:
const roof = q.face(hit!.faceId)!;
roof.surface; // the face's surface kind
roof.flat; // true: flat whatever its kind
roof.area; // 12
q.neighborsOfFace(hit!.faceId); // the four walls
Reading the model covers the rest of the read side: edges and
their curves, vertex rings, surface evaluation at (u, v), point
classification, mass properties and unfolding.
Snapping is a host decision built on these reads. The kernel gives exact answers (the point of an edge's curve nearest a ray, a face's normal at a point); which of them the cursor should land on, and when, is the host's snapping.
const pushed = await offset(ctx, { mode: 'push', faceIds: [hit!.faceId], distance: 0.5 });
Ids the host holds stay good across an edit, except for the entities the
edit removed: pushed.removed lists them, and pushed.created lists the
new ones. The face pushed here keeps its id. A host keeps its selection by
dropping the removed ids from it.
The next frame() re-emits only the faces and edges the push touched.
To drag what was picked, plan the move from the drag's start on every pointer move and commit it on release:
const drag = { ids: [hit!.faceId], matrix: new Matrix4().makeTranslation(0, 0, 0.25) };
const plan = planTransform(mesh, drag); // the mesh is not touched
// draw kernelTessellation(plan.preview).frame(...) while dragging
await transformEntities(ctx, drag); // one undo step, the same result
Move, rotate and scale covers how neighbors bend, weld and split, which ids survive, and the refusals.
To delete what was picked, erase it by id:
const erased = await erase(ctx, { ids: [hit!.faceId] }); // one undo step
erased.removed; // the ids it removed: drop them from the selection
An edge between two flat faces in one plane merges them; any other edge takes its faces with it; a face goes and leaves its edges. Erase has the rules.
ctx.commandManager.undo(); // false when there is nothing to undo
ctx.commandManager.redo();
ctx.commandManager.canUndo();
ctx.commandManager.canRedo();
Each committed verb is one step. Undo puts the mesh back exactly as it was
before the step, ids included, so a selection made before the step is
good again after the undo; redo puts the step back the same way. A new
verb after an undo clears the redo side. The history keeps the last 50
steps by default (new MeshHistory({ maxStackSize }), passed as
meshVerbContext(mesh, history)).
Steps are applied to the mesh in place: hold on to the HalfEdgeMesh
object, not to snapshots of it. A kernelQuery or kernelTessellation
made before an undo reads the model as it is after it.
const text = JSON.stringify(saveMesh(mesh));
const loaded = loadMesh(JSON.parse(text));
if (loaded.ok) {
validate(loaded.mesh, { expectClosed: true }).ok; // true
kernelQuery(loaded.mesh).face(hit!.faceId) !== null; // true: ids survive
}
Save and load has the format, its version and the refusals.
validate(mesh, { expectClosed: true }): the validator's rules, with
the entity each problem is on.computeMassProperties(mesh): area, volume, centroid and inertia,
integrated on the faces' own surfaces.isMeshClosed, computeEulerPoincareCounts.develop makes a developable surface and
regrain sets the grain of a ruled one, fold, markCrease and
checkFlatFold work a folded sheet, unfold, layOutNet and
paperModel lay it flat for cutting.@commonplace-technologies/kernel-step, to bring catalog parts in and
send parts to fabrication.