diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md
index fd0d6e2..ecd4d1d 100644
--- a/ARCHITECTURE.md
+++ b/ARCHITECTURE.md
@@ -53,6 +53,14 @@ src/
│ │ ├── creasedMesh.ts render-ready meshes with creased normals
│ │ ├── stlExport.ts binary STL
│ │ └── scadExport.ts editable OpenSCAD source
+│ ├── dfm/
+│ │ ├── profile.ts the .ocdfm print-correction profile: parse, validate, hash
+│ │ ├── model.ts the lateral bleed model and its inverse
+│ │ ├── compensate.ts nominal design + profile → design to print + conflicts
+│ │ ├── exportPlan.ts what an export is built from and named, with or without a profile
+│ │ ├── coupon.ts the calibration coupon project and its measurement sheet
+│ │ ├── fit.ts coupon results → compensation parameters
+│ │ └── preview.ts outlines and cross-sections for the read-only preview
│ ├── validation/
│ │ ├── manufacturability.ts min feature, clearance, build volume, overhangs
│ │ ├── flow.ts dead ends, islands, abrupt tapers
@@ -76,6 +84,7 @@ src/
│ ├── editorStore.ts tool, selection, snapping, viewport
│ ├── cadStore.ts the built solid and the worker that produces it
│ ├── validationStore.ts focused warning and check thresholds
+│ ├── dfmStore.ts loaded print-correction profiles and the one selected
│ ├── fluidStore.ts selected metric and fluid being edited
│ └── uiStore.ts overlays and pending confirmations
├── components/ shell, onboarding, tour, dialogs, UI primitives, draw/
@@ -155,6 +164,70 @@ with no port at all. `planDrainage` iterates that to convergence, because
venting the worst spot exposes the next-worst and a "one-click" helper that
needs three clicks is not one-click.
+## How print correction is put together
+
+`lib/dfm/` compensates for resin overcure at export time, from a per-printer,
+per-resin profile. It is optional end to end: with no profile selected nothing
+in it runs, and `goldenExport.test.ts` holds the default export byte-identical
+to a recorded baseline.
+
+**One function, three callers.** `compensateDesign(nominal, profile)` is pure
+and returns a second design plus a conflict list. The STL export, the OpenSCAD
+export and the preview panel all call it and hand the result to the ordinary
+pipeline, so they cannot disagree. `preview.test.ts` goes further and compares
+the preview's cross-sections with a slice of the mesh the export path builds.
+
+**The compensated design is almost entirely ordinary data.** Lateral bleed
+becomes wider dimension markers on a copy of the graph, so the loft, the sweep
+and both exporters need to know nothing about it. Vertical cure-through is the
+one thing the graph cannot express — a ceiling that moves while the floor stays
+— so it travels as a single optional `ceilingRaiseMm`, default 0, through
+`placeChannel`, `profilePoints`, `buildChip` and `exportScad`.
+
+**The design file stays nominal.** Compensation is never written back. A
+`.openchip` file may carry an optional `dfmProfileRef` (the name and SHA-256 of
+the profile it was last exported with) and nothing else; the profile is a
+separate `.ocdfm` file kept in a browser-level store. The selection is not
+persisted, so every session starts on "None (uncompensated)".
+
+**The model is empirical, with a motivated shape.** Jacobs' working curve,
+C_d = D_p·ln(E/E_c), is Beer–Lambert attenuation solved for the depth at which
+dose falls to the cure threshold. Taking stray lateral light to fall off the
+same way, an isolated edge cures a fixed distance Δ past where it was drawn, and
+the two walls of a channel add their tails in the gap: each wall moves further
+as the channel narrows, and the channel closes at W = 2Δ + 2λ·ln 2. Δ and λ are
+fitted to coupon measurements directly; D_p and E_c are not recovered, because
+a coupon printed at one exposure cannot separate them. Vertical cure-through
+depends on dose rather than on channel width, so it is one number.
+
+**What it assumes**, each stated in `compensate.ts`: the chip prints flat, base
+down; the ceiling raise applies only to monolithic chips, since two-piece and
+glass-slide channels are open grooves with no printed roof; bleed is isotropic
+and uniform across the plate; ports and fittings are left nominal, because a
+Luer taper is a fit to a standard part; and a round channel is corrected as a
+larger circle, which also lowers its floor by the lateral offset.
+
+**Conflicts are found with the design checks themselves.** The channel-spacing
+check runs on the nominal and the compensated design, and a conflict is a
+failing measurement that compensation created or made worse — a wall that was
+already too thin as drawn is the design's own warning. Edge clearance and roof
+thickness are measured the same before-and-after way. Like every other check,
+a conflict is a caution box with numbers in it and is connected to no button.
+
+**An open/closed fit is a bracket, not a number.** Marking channels open or
+closed only says which side of a threshold each fell on, so `fit.ts` reports
+the interval between the largest size that closed and the smallest that stayed
+open, uses the constant model, and the dialog calls the result coarse. Measured
+dimensions give a least-squares fit with a residual, and the decay length is
+kept only when it cuts the squared error by more than a tenth.
+
+**The coupon is an ordinary project.** It is built from nodes, segments and
+drainage vents and exported through the same pipeline, so it measures the app's
+real output. Its channels deliberately run through the side walls to open both
+ends, which the design checks report as channels outside the chip. There is no
+text primitive, so groups are labelled with tally dots: blind holes made from
+drainage vents on nodes that carry no channel.
+
## How the fluid estimates are put together
`lib/fluids/` is a **one-dimensional network model**, and the tab says so
@@ -313,6 +386,12 @@ version opens in an earlier build with its unknown fields preserved through a sa
round-trip. `formatVersion` gates migrations; the hook lives in
`migrate()` in `lib/projectFile.ts`.
+Print-correction profiles are the deliberate exception. A `.ocdfm` file with a
+`schemaVersion` newer than the build understands is refused with a message
+rather than opened: its unknown fields would be terms of a model this build
+does not apply, and exporting with half a correction is worse than exporting
+with none.
+
## Deploying
Any static host works — the build output in `dist/` is plain files and the app
diff --git a/README.md b/README.md
index 71ca7c0..c7c9b2e 100644
--- a/README.md
+++ b/README.md
@@ -29,6 +29,13 @@ browser with no account and no install, and nothing you draw is uploaded.
channel plate and a lid), one sealed block, or an open plate capped with a
glass slide. Export STL for printing, editable OpenSCAD source, SVG
schematics, PNG snapshots and a presentation bundle.
+- **Correct for your printer's overcure, if you want to.** Resin printers cure
+ a little past where they are told to, which narrows small channels and lowers
+ their ceilings. Print a calibration coupon, record which channels came out
+ open, and OpenChip fits a print-correction profile (a `.ocdfm` file) that
+ enlarges channels at export so they print at the size you drew. It is off by
+ default, the design file always keeps the nominal geometry, and exporting
+ without a profile works exactly as before.
- **Estimate the flow.** A one-dimensional network model gives pressure drop,
Reynolds number, wall shear, residence time, heat exchange between
neighbouring channels, and reagent use, with heatmaps.
@@ -47,6 +54,7 @@ Good places to start:
- [Templates](https://wiki.openchip.tech/guide/templates/)
- [Design checks](https://wiki.openchip.tech/reference/design-checks/)
- [Export formats](https://wiki.openchip.tech/reference/export-formats/)
+- [Print correction](https://wiki.openchip.tech/printing/print-correction/)
- [3D printing microfluidic chips](https://wiki.openchip.tech/printing/3d-printing-microfluidic-chips/)
## First steps
@@ -59,6 +67,27 @@ take the guided tour from **Settings → Take the tour**.
Your working design is kept in browser storage as a safety net. To keep a design
or move it between machines, save it as a `.openchip` file.
+## Print correction
+
+Optional. If small channels come off your printer narrower than drawn, or
+closed:
+
+1. On the **CAD Preview** tab, open **Print correction** in the Export section
+ and choose **Calibrate a printer…**. Download the coupon, export its STL and
+ print it flat in the resin and exposure settings you use.
+2. Flush it, then mark each channel open, partial or closed. Measured widths and
+ heights are optional and give a much better fit.
+3. Save the profile. It is selected for export straight away, and **Preview
+ DFM** shows the corrected geometry over the design as drawn, with
+ cross-sections.
+
+Corrected files are named `…-dfm-.stl` and record the profile in the
+file. Choose **None (uncompensated)** to export the design as drawn. An
+open/closed-only fit is coarse and the app says so; print a test piece before
+trusting it. The
+[print correction guide](https://wiki.openchip.tech/printing/print-correction/)
+covers the file format, the model and its limits.
+
## Run it locally
Requires Node 20.19 or newer.
diff --git a/skills/openchip-design/references/SCHEMA.md b/skills/openchip-design/references/SCHEMA.md
index 239b6c9..5398fb9 100644
--- a/skills/openchip-design/references/SCHEMA.md
+++ b/skills/openchip-design/references/SCHEMA.md
@@ -192,3 +192,15 @@ enclosed — see `DESIGN-RULES.md`.
Leave `savedImages` as `[]`; it holds exported SVG/PNG data URIs the app writes
itself. `presetLibraryRef` is the id of the starter template a project began
from, or `null` — provenance only, nothing enforces it.
+
+## `dfmProfileRef` (optional)
+
+```json
+"dfmProfileRef": { "name": "Mars 4 — clear — 2.5 s", "sha256": "…64 hex characters…" }
+```
+
+A note of which print-correction profile the project was last exported with.
+The app writes it after a compensated export; **leave it out of a file you
+generate**. It carries no geometry: the profile lives in its own `.ocdfm` file,
+`channelGraph` is always the design as drawn, and a project opens and exports
+normally when the profile it names is not available.
diff --git a/src/components/cad/CadPanel.tsx b/src/components/cad/CadPanel.tsx
index edc4fae..646cdc6 100644
--- a/src/components/cad/CadPanel.tsx
+++ b/src/components/cad/CadPanel.tsx
@@ -8,14 +8,22 @@ import { exportStl } from '../../lib/cad/stlExport';
import { THREAD_APPROXIMATION_NOTE } from '../../lib/cad/portGeometry';
import { channelPlaneZ, slidePocket } from '../../lib/cad/slide';
import { slugify } from '../../lib/slug';
+import { compensateDesign } from '../../lib/dfm/compensate';
+import { planExport } from '../../lib/dfm/exportPlan';
import { useChipResize } from '../../hooks/useChipResize';
+import { useDfmCompensation } from '../../hooks/useDfmCompensation';
import { useCadStore } from '../../store/cadStore';
+import { selectedDfmEntry, useDfmStore } from '../../store/dfmStore';
import { useProjectStore } from '../../store/projectStore';
+import { useValidationStore } from '../../store/validationStore';
import type { ChipParams } from '../../types/project';
import { WikiLink } from '../ui/WikiLink';
import { Button } from '../ui/Button';
import { Field, NumberInput, Segmented } from '../ui/Field';
import { Section } from '../draw/InspectorPanel';
+import { DfmCalibrationDialog } from '../dfm/DfmCalibrationDialog';
+import { DfmPreviewToggle, DfmProfileSelect, DfmSummary } from '../dfm/DfmExportControls';
+import { DfmPreviewPanel } from '../dfm/DfmPreviewPanel';
import type { CadViewportHandle } from './CadViewport';
export function CadPanel({ viewport }: { viewport: RefObject }) {
@@ -25,6 +33,7 @@ export function CadPanel({ viewport }: { viewport: RefObject
+
);
}
@@ -422,19 +431,64 @@ function ExportSection({ viewport }: { viewport: RefObject s.addSavedImage);
const buildForExport = useCadStore((s) => s.buildForExport);
const model = useCadStore((s) => s.model);
+ // Null on "None (uncompensated)", and then nothing below is computed or drawn.
+ const dfm = useDfmCompensation();
+ const dfmPreviewOpen = useDfmStore((s) => s.previewOpen);
const [busy, setBusy] = useState(null);
const [highRes, setHighRes] = useState(true);
const slug = slugify(projectName);
+ /**
+ * What this export is built from. With no profile selected it is the project
+ * as it stands, untouched. With one, it is compensated here, from the store's
+ * state at the moment of the click — never from the debounced value the
+ * panel displays.
+ */
+ const plan = () => {
+ const entry = selectedDfmEntry(useDfmStore.getState());
+ const { printerProfile } = useProjectStore.getState().project;
+ const nominal = { graph, chipParams, drainageVents, printerProfile };
+ return planExport(
+ nominal,
+ projectName,
+ entry,
+ entry
+ ? compensateDesign(nominal, entry.profile, {
+ settings: useValidationStore.getState().settings,
+ })
+ : undefined,
+ );
+ };
+
+ /** After a compensated export: what the toast adds, and the note in the project. */
+ const afterCompensated = (planned: ReturnType): string => {
+ const entry = selectedDfmEntry(useDfmStore.getState());
+ if (!planned.compensated || !entry) return '';
+ useProjectStore
+ .getState()
+ .setDfmProfileRef({ name: entry.profile.meta.name, sha256: entry.sha256 });
+ const count = planned.compensated.conflicts.length;
+ return (
+ ` Print-corrected with “${entry.profile.meta.name}”.` +
+ (count > 0 ? ` ${count} conflict${count === 1 ? '' : 's'} — see the Export panel.` : '')
+ );
+ };
+
const exportStlFor = async (which: 'all' | 'body' | 'lid') => {
setBusy(`stl-${which}`);
try {
+ const planned = plan();
// Re-run at export quality rather than shipping the coarse preview mesh —
// the tessellation error in a preview circle is ~2%, which is real
// material on a 0.4 mm channel.
- const built = await buildForExport(graph, chipParams, drainageVents);
+ const built = await buildForExport(
+ planned.graph,
+ planned.chipParams,
+ planned.drainageVents,
+ planned.ceilingRaiseMm,
+ );
const pieces =
which === 'all' ? built.pieces : built.pieces.filter((p) => p.id === which);
@@ -443,13 +497,13 @@ function ExportSection({ viewport }: { viewport: RefObject sum + p.indices.length / 3, 0);
toast.success(`Exported ${slug}${suffix}.stl`, {
- description: `${tris.toLocaleString()} triangles, millimetre units.`,
+ description: `${tris.toLocaleString()} triangles, millimetre units.${afterCompensated(planned)}`,
});
} catch (error) {
toast.error("Couldn't build the STL", {
@@ -463,10 +517,16 @@ function ExportSection({ viewport }: { viewport: RefObject {
setBusy('scad');
try {
- const source = exportScad(graph, chipParams, { projectName, drainageVents });
- downloadBlob(source, `${slug}.scad`, 'text/plain');
- toast.success(`Exported ${slug}.scad`, {
- description: 'Parameters are at the top of the file, ready to edit.',
+ const planned = plan();
+ const source = exportScad(planned.graph, planned.chipParams, {
+ projectName,
+ drainageVents: planned.drainageVents,
+ ceilingRaiseMm: planned.ceilingRaiseMm,
+ headerNotes: planned.scadNotes,
+ });
+ downloadBlob(source, `${slug}${planned.fileSuffix}.scad`, 'text/plain');
+ toast.success(`Exported ${slug}${planned.fileSuffix}.scad`, {
+ description: `Parameters are at the top of the file, ready to edit.${afterCompensated(planned)}`,
});
} finally {
setBusy(null);
@@ -521,14 +581,25 @@ function ExportSection({ viewport }: { viewport: RefObjectWhich format when
- }
- disabled={busy !== null || !model}
- onClick={() => void exportStlFor('all')}
- >
- {busy === 'stl-all' ? 'Building…' : twoPiece ? 'STL — both pieces' : 'STL'}
-
+
+
+ {dfm ? : null}
+
+ {/* `contents` on None, so the STL button sits in the column exactly
+ as it always has; a two-column row only once there is a toggle
+ to put beside it. */}
+
+ }
+ disabled={busy !== null || !model}
+ className={dfm ? 'whitespace-nowrap px-2' : undefined}
+ onClick={() => void exportStlFor('all')}
+ >
+ {busy === 'stl-all' ? 'Building…' : twoPiece ? 'STL — both pieces' : 'STL'}
+
+ {dfm ? : null}
+
{twoPiece ? (
@@ -565,6 +636,8 @@ function ExportSection({ viewport }: { viewport: RefObject
+ {dfm && dfmPreviewOpen ? : null}
+
String(Number(value.toFixed(places)));
+const listText = (values: number[]): string => values.join(', ');
+const parseList = (text: string): number[] =>
+ text
+ .split(/[,;\s]+/)
+ .map((part) => Number(part))
+ .filter((value) => Number.isFinite(value) && value > 0);
+
+/**
+ * Calibrating a printer: generate a coupon, record what came off the plate, and
+ * save the fit as a profile.
+ *
+ * Opened on purpose from the print-correction menu and never offered
+ * unprompted. Nothing here touches the open project except the explicit "Open
+ * the coupon in the editor" button, which asks first if there is unsaved work.
+ */
+export function DfmCalibrationDialog() {
+ const open = useDfmStore((s) => s.calibrationOpen);
+ const setOpen = useDfmStore((s) => s.setCalibrationOpen);
+
+ return (
+
+ Print a test coupon, record which channels came out open, and save the result as a
+ profile for this printer and resin.{' '}
+ The full walkthrough
+ >
+ }
+ className="w-[min(calc(100vw-2rem),46rem)]"
+ >
+ {/* Mounted only while open, so each calibration starts from the current
+ printer profile rather than from whatever the last one left behind. */}
+ {open ? setOpen(false)} /> : null}
+
+ );
+}
+
+function Calibration({ onDone }: { onDone: () => void }) {
+ const printer = useProjectStore((s) => s.project.printerProfile);
+ const [step, setStep] = useState('coupon');
+ const [spec, setSpec] = useState(() => defaultCouponSpec(printer));
+ const [measurements, setMeasurements] = useState(() =>
+ blankMeasurements(couponLayout(defaultCouponSpec(printer))),
+ );
+
+ /** A new coupon is a new set of channels; results for the old one mean nothing. */
+ const changeSpec = (next: CouponSpec) => {
+ const clean = normaliseCouponSpec(next);
+ setSpec(clean);
+ setMeasurements(blankMeasurements(couponLayout(clean)));
+ };
+
+ return (
+
+
+ {STEPS.map((item) => (
+ setStep(item.id)}
+ aria-current={step === item.id ? 'step' : undefined}
+ className={cn(
+ 'oc-pressable flex-1 rounded-[6px] px-3 py-1.5 text-[13px] font-medium',
+ step === item.id ? 'bg-panel text-ink shadow-sm' : 'text-ink-muted hover:text-ink',
+ )}
+ >
+ {item.label}
+
+ ))}
+
+
+ {step === 'coupon' ? (
+
setStep('results')}
+ onDone={onDone}
+ />
+ ) : null}
+ {step === 'results' ? (
+ setStep('profile')}
+ />
+ ) : null}
+ {step === 'profile' ? (
+
+ ) : null}
+
+ );
+}
+
+// ---------------------------------------------------------------------------
+// 1 · coupon
+// ---------------------------------------------------------------------------
+
+function CouponStep({
+ spec,
+ onSpec,
+ printer,
+ measurements,
+ onNext,
+ onDone,
+}: {
+ spec: CouponSpec;
+ onSpec: (spec: CouponSpec) => void;
+ printer: PrinterProfile;
+ measurements: CouponMeasurement[];
+ onNext: () => void;
+ onDone: () => void;
+}) {
+ const [advanced, setAdvanced] = useState(false);
+ const loadProject = useProjectStore((s) => s.loadProject);
+ const requestConfirm = useUiStore((s) => s.requestConfirm);
+ const layout = useMemo(() => couponLayout(spec), [spec]);
+
+ const fits =
+ layout.chip.width <= printer.buildVolumeMm.x && layout.chip.length <= printer.buildVolumeMm.y;
+
+ const downloadCoupon = () => {
+ const { project } = buildCouponProject(spec, printer);
+ const name = `dfm-coupon-v${COUPON_VERSION}.openchip`;
+ downloadBlob(serializeProject(stampForSave(project)), name, `${OPENCHIP_MIME};charset=utf-8`);
+ toast.success(`Downloaded ${name}`, {
+ description: 'Open it like any project, then export its STL from the CAD tab with print correction set to None.',
+ });
+ };
+
+ const downloadSheet = () => {
+ const name = `dfm-coupon-v${COUPON_VERSION}-sheet.csv`;
+ downloadBlob(measurementSheetCsv(measurements), name, 'text/csv;charset=utf-8');
+ toast.success(`Downloaded ${name}`);
+ };
+
+ const openInEditor = async () => {
+ const { isDirty, project: current } = useProjectStore.getState();
+ if (isDirty) {
+ const confirmed = await requestConfirm({
+ title: 'Discard unsaved changes?',
+ message: `“${current.meta.name}” has changes that haven't been saved to a file. Opening the coupon will discard them.`,
+ confirmLabel: 'Discard and continue',
+ destructive: true,
+ });
+ if (!confirmed) return;
+ }
+ // Exporting the coupon itself with a profile applied would calibrate
+ // against a correction, so the selection is cleared along with it.
+ useDfmStore.getState().select(null);
+ loadProject(buildCouponProject(spec, printer).project, null);
+ onDone();
+ toast.success('The coupon is open', {
+ description: 'Export its STL from the CAD tab. Come back to Calibrate a printer… with the results.',
+ });
+ };
+
+ return (
+
+
+ The coupon is a strip of straight channels, one for each width and height below. Every
+ channel runs out through both long edges, so you can flush it and hold it up to a light.
+
+
+
+ widths
+ {listText(spec.widthsMm)} mm
+ heights
+ {listText(spec.heightsMm)} mm
+ channels
+
+ {layout.channels.length} ({spec.widthsMm.length} × {spec.heightsMm.length})
+
+ strip
+
+ {mm(layout.chip.width, 2)} × {mm(layout.chip.length, 2)} × {mm(layout.chip.baseThickness, 2)} mm,
+ monolithic
+
+
+
+ {!fits ? (
+
+ This strip is larger than the {printer.buildVolumeMm.x} × {printer.buildVolumeMm.y} mm build
+ plate in the printer profile. Remove some widths or heights under Advanced.
+
+ ) : null}
+
+
+ setAdvanced((v) => !v)}
+ >
+ {advanced ? 'Hide advanced' : 'Advanced: choose the sizes'}
+
+
+
+ {advanced ? (
+
+
+ onSpec({ ...spec, widthsMm })} />
+
+
+ onSpec({ ...spec, heightsMm })} />
+
+
+
+ onSpec({ ...spec, channelLengthMm })} />
+
+
+ onSpec({ ...spec, gapMm })} />
+
+
+ onSpec({ ...spec, dotDiameterMm })} />
+
+
+ onSpec({ ...spec, floorMm })} />
+
+
+ onSpec({ ...spec, roofMm })} />
+
+
+
+ Changing the sizes clears any results already entered, because they describe a
+ different coupon.
+
+
+ ) : null}
+
+
+
+ Print it flat, base down, with no tilt , in the resin and at
+ the exposure settings you will use for real chips.
+
+ Wash and flush every channel before curing. Resin left inside reads as a closed channel.
+
+ Groups are labelled by dots in the top face : one dot for group
+ 1, two for group 2. In each group, channel 1 is the one nearest the dots and is the widest.
+
+
+ Design checks will list every channel as running outside the chip. On the coupon that is
+ deliberate: it is what opens the ends.
+
+
+
+
+ } onClick={downloadCoupon}>
+ Download coupon (.openchip)
+
+ } onClick={downloadSheet}>
+ Measurement sheet (.csv)
+
+ } onClick={() => void openInEditor()}>
+ Open the coupon in the editor
+
+
+ I have results →
+
+
+
+ );
+}
+
+/** A comma-separated list of millimetre values, committed on blur. */
+function ListInput({
+ id,
+ values,
+ onChange,
+}: {
+ id: string;
+ values: number[];
+ onChange: (values: number[]) => void;
+}) {
+ const [draft, setDraft] = useState(null);
+ return (
+ setDraft(event.target.value)}
+ onBlur={() => {
+ if (draft === null) return;
+ const parsed = parseList(draft);
+ if (parsed.length > 0) onChange(parsed);
+ setDraft(null);
+ }}
+ className="font-mono"
+ />
+ );
+}
+
+// ---------------------------------------------------------------------------
+// 2 · results
+// ---------------------------------------------------------------------------
+
+const NEXT_RESULT: Record = {
+ none: 'open',
+ open: 'partial',
+ partial: 'closed',
+ closed: null,
+};
+
+/**
+ * Each state has its own glyph, word and border style as well as its colour,
+ * so the grid reads without colour vision and in either theme.
+ */
+const RESULT_STYLE: Record = {
+ none: { word: 'not set', className: 'border-dashed border-line text-ink-quiet' },
+ open: { word: 'open', className: 'border-success bg-panel text-ink' },
+ partial: { word: 'partial', className: 'border-dashed border-caution bg-caution-wash text-ink' },
+ closed: { word: 'closed', className: 'border-danger bg-danger-wash text-ink' },
+};
+
+/**
+ * The state as a drawn mark — an empty ring, a half-filled one, a filled one —
+ * rather than a Unicode glyph, which not every system font carries.
+ */
+function ResultMark({ result, size = 13 }: { result: ChannelResult | 'none'; size?: number }) {
+ return (
+
+ {result === 'none' ? (
+
+ ) : (
+ <>
+ {result === 'closed' ? : null}
+ {result === 'partial' ? : null}
+
+ >
+ )}
+
+ );
+}
+
+function ResultsStep({
+ measurements,
+ onMeasurements,
+ onNext,
+}: {
+ measurements: CouponMeasurement[];
+ onMeasurements: (measurements: CouponMeasurement[]) => void;
+ onNext: () => void;
+}) {
+ const [measured, setMeasured] = useState(() =>
+ measurements.some((m) => m.measuredWidthMm !== undefined || m.measuredHeightMm !== undefined),
+ );
+ const input = useRef(null);
+
+ const update = (id: string, patch: Partial) =>
+ onMeasurements(measurements.map((m) => (m.id === id ? { ...m, ...patch } : m)));
+
+ const groups = useMemo(() => {
+ const byHeight = new Map();
+ for (const m of measurements) {
+ const list = byHeight.get(m.nominalHeightMm) ?? [];
+ list.push(m);
+ byHeight.set(m.nominalHeightMm, list);
+ }
+ return [...byHeight.entries()].sort(([a], [b]) => a - b);
+ }, [measurements]);
+
+ const marked = measurements.filter((m) => m.result !== null).length;
+
+ const importSheet = async (file: File | undefined) => {
+ if (!file) return;
+ const text = await file.text();
+ // A profile carries its measurements, so it can be re-fitted from here too.
+ if (file.name.endsWith(DFM_PROFILE_EXTENSION)) {
+ const profile = parseDfmProfile(text);
+ if (!profile.ok) {
+ toast.error(profile.message, { description: profile.details.join(' ') || undefined });
+ return;
+ }
+ onMeasurements(profile.profile.measurements);
+ toast.success(`Loaded ${profile.profile.measurements.length} measurements from ${profile.profile.meta.name}`);
+ return;
+ }
+ const parsed = parseMeasurementSheet(text);
+ if (!parsed.ok) {
+ toast.error(parsed.message, { description: parsed.details.join(' ') || undefined });
+ return;
+ }
+ onMeasurements(parsed.measurements);
+ toast.success(`Imported ${parsed.measurements.length} channels`);
+ };
+
+ return (
+
+
+ Click a channel to mark it , or{' '}
+ . Leave any you did not check unset.
+
+
+
+ {groups.map(([heightMm, row], index) => (
+
+
+
+ Group {index + 1}{' '}
+
+ {'•'.repeat(index + 1)}
+
+
+
{mm(heightMm)} mm tall
+
+
+ {row.map((m) => {
+ const style = RESULT_STYLE[m.result ?? 'none'];
+ return (
+ update(m.id, { result: NEXT_RESULT[m.result ?? 'none'] })}
+ aria-label={`Channel ${m.id}, ${mm(m.nominalWidthMm)} mm wide: ${style.word}. Click to change.`}
+ title={`Channel ${m.id} — ${mm(m.nominalWidthMm)} × ${mm(m.nominalHeightMm)} mm`}
+ className={cn(
+ 'oc-pressable flex h-14 w-[3.6rem] flex-col items-center justify-center rounded-lg border-2',
+ style.className,
+ )}
+ >
+
+ {mm(m.nominalWidthMm)}
+ {style.word}
+
+ );
+ })}
+
+
+ ))}
+
+
+
+ onMeasurements(measurements.map((m) => (m.result === null ? { ...m, result: 'open' } : m)))}
+ >
+ Mark the rest open
+
+ onMeasurements(measurements.map((m) => ({ ...m, result: null })))}>
+ Clear
+
+ } onClick={() => input.current?.click()}>
+ Import a filled-in sheet or profile…
+
+ {
+ void importSheet(event.target.files?.[0]);
+ event.target.value = '';
+ }}
+ />
+
+
+
+ setMeasured((v) => !v)}
+ >
+ {measured ? 'Hide measured dimensions' : 'Advanced: enter measured dimensions'}
+
+
+
+ {measured ? (
+
+
+ Optional, and worth it: a measured width or height turns a coarse bracket into a real
+ fit. Fill in only the channels you measured. Widths can be read from above with a
+ microscope; heights need a section or a profilometer.
+
+
+
Channel
+
Drawn
+
Measured width
+
Measured height
+ {measurements.map((m) => (
+
update(m.id, patch)} />
+ ))}
+
+
+ ) : null}
+
+
+
+ {marked} of {measurements.length} channels marked
+
+
+ Fit the results →
+
+
+
+ );
+}
+
+function Glyph({ result }: { result: ChannelResult }) {
+ const style = RESULT_STYLE[result];
+ return (
+
+ {style.word}
+
+ );
+}
+
+function MeasuredRow({
+ measurement,
+ onChange,
+}: {
+ measurement: CouponMeasurement;
+ onChange: (patch: Partial) => void;
+}) {
+ return (
+ <>
+ {measurement.id}
+
+ {mm(measurement.nominalWidthMm)} × {mm(measurement.nominalHeightMm)}
+
+ onChange({ measuredWidthMm })}
+ />
+ onChange({ measuredHeightMm })}
+ />
+ >
+ );
+}
+
+/** A numeric field that may be left empty — `NumberInput` always holds a number. */
+function OptionalNumber({
+ value,
+ onChange,
+ unit,
+ label,
+ id,
+ compact,
+}: {
+ /** The denser size used inside the measured-dimensions table. */
+ compact?: boolean;
+ value: number | undefined | null;
+ onChange: (value: number | undefined) => void;
+ unit?: string;
+ label?: string;
+ id?: string;
+}) {
+ const [draft, setDraft] = useState(null);
+ const shown = draft ?? (value === undefined || value === null ? '' : String(value));
+ return (
+
+ {
+ const text = event.target.value;
+ setDraft(text);
+ if (text.trim() === '') {
+ onChange(undefined);
+ return;
+ }
+ const parsed = Number(text.replace(',', '.'));
+ if (Number.isFinite(parsed) && parsed >= 0) onChange(parsed);
+ }}
+ onBlur={() => setDraft(null)}
+ className={cn('font-mono', compact ? 'h-8 text-[12px]' : undefined, unit ? 'pr-9' : undefined)}
+ />
+ {unit ? (
+
+ {unit}
+
+ ) : null}
+
+ );
+}
+
+// ---------------------------------------------------------------------------
+// 3 · profile
+// ---------------------------------------------------------------------------
+
+function ProfileStep({
+ spec,
+ measurements,
+ printer,
+ onDone,
+}: {
+ spec: CouponSpec;
+ measurements: CouponMeasurement[];
+ printer: PrinterProfile;
+ onDone: () => void;
+}) {
+ const addProfile = useDfmStore((s) => s.addProfile);
+ const select = useDfmStore((s) => s.select);
+ const fit = useMemo(() => fitCompensation(measurements), [measurements]);
+
+ const [name, setName] = useState(`${printer.name} — `);
+ const [printerModel, setPrinterModel] = useState(printer.name);
+ const [resin, setResin] = useState('');
+ const [layerHeightMicrons, setLayerHeightMicrons] = useState(printer.layerHeightMicrons);
+ const [xyPixelMicrons, setXyPixelMicrons] = useState(printer.xyResolutionMicrons);
+ const [normalExposureS, setNormalExposureS] = useState();
+ const [bottomExposureS, setBottomExposureS] = useState();
+ const [bottomLayers, setBottomLayers] = useState();
+ const [exposureOther, setExposureOther] = useState('');
+ const [notes, setNotes] = useState('');
+ const [snapToPixelGrid, setSnap] = useState(false);
+
+ // Null until the user edits a value by hand; then the fit is theirs.
+ const [manual, setManual] = useState<{ deltaXyMm: number; lateralDecayMm: number; deltaZMm: number } | null>(null);
+ const [editing, setEditing] = useState(false);
+ const values = manual ?? fit;
+
+ const coarse = !manual && (fit.lateral.method === 'open-closed' || fit.vertical.method === 'open-closed');
+ const nothing = !manual && fit.lateral.method === 'none' && fit.vertical.method === 'none';
+ const nameOk = name.trim().length > 0 && !name.trim().endsWith('—');
+
+ const save = async () => {
+ const manualFit: AxisFit = { method: 'manual', dataPoints: 0 };
+ const measured = [...new Set(measurements.map((m) => m.nominalWidthMm))].sort((a, b) => a - b);
+ const heights = [...new Set(measurements.map((m) => m.nominalHeightMm))].sort((a, b) => a - b);
+
+ const profile: DfmProfile = {
+ kind: DFM_PROFILE_KIND,
+ schemaVersion: DFM_SCHEMA_VERSION,
+ meta: {
+ name: name.trim(),
+ printerModel: printerModel.trim(),
+ resin: resin.trim(),
+ layerHeightMicrons,
+ exposure: {
+ normalExposureS: normalExposureS ?? null,
+ bottomExposureS: bottomExposureS ?? null,
+ bottomLayers: bottomLayers ?? null,
+ other: exposureOther.trim(),
+ },
+ xyPixelMicrons: xyPixelMicrons ?? null,
+ createdAt: new Date().toISOString(),
+ notes: notes.trim(),
+ },
+ compensation: {
+ model: DFM_MODEL_ID,
+ deltaXyMm: values.deltaXyMm,
+ lateralDecayMm: values.lateralDecayMm,
+ deltaZMm: values.deltaZMm,
+ snapToPixelGrid: snapToPixelGrid && xyPixelMicrons !== undefined,
+ },
+ fit: manual ? { lateral: manualFit, vertical: manualFit } : { lateral: fit.lateral, vertical: fit.vertical },
+ // The lists actually measured, which is what a re-fit needs, rather than
+ // the spec on screen — the two differ when a sheet was imported.
+ coupon: {
+ version: spec.version,
+ widthsMm: measured.length > 0 ? measured : spec.widthsMm,
+ heightsMm: heights.length > 0 ? heights : spec.heightsMm,
+ },
+ measurements,
+ };
+
+ // Through the parser before it is written: a profile this build would
+ // refuse to load must never leave it.
+ const checked = parseDfmProfile(serializeDfmProfile(profile));
+ if (!checked.ok) {
+ toast.error(checked.message, { description: checked.details.join(' ') || undefined });
+ return;
+ }
+
+ const fileName = dfmProfileFileName(profile.meta.name);
+ downloadBlob(serializeDfmProfile(checked.profile), fileName, DFM_PROFILE_MIME);
+ const entry = await addProfile(checked.profile);
+ select(entry.sha256);
+ toast.success(`Saved ${fileName}`, {
+ description: 'It is selected for export now. Keep the file: it is how the profile moves between browsers and people.',
+ });
+ onDone();
+ };
+
+ return (
+
+
+
+
+ {manual ? 'Values entered by hand' : 'Fit'}
+
+
{
+ if (editing) setManual(null);
+ setEditing((v) => !v);
+ }}
+ >
+ {editing ? 'Use the fit' : 'Advanced: edit values'}
+
+
+
+ {editing ? (
+
+
+ setManual({ ...values, deltaXyMm })} />
+
+
+ setManual({ ...values, lateralDecayMm })} />
+
+
+ setManual({ ...values, deltaZMm })} />
+
+
+ ) : (
+
+
0 ? `decay length ${mm(values.lateralDecayMm)} mm` : 'same at every width'}
+ axis={fit.lateral}
+ unit="mm per side"
+ />
+
+
+ predicts channels drawn {mm(predictedClosureWidthMm(values))} mm wide or less close
+
+
+ )}
+
+
+ {nothing ? (
+
+ No results have been entered, so there is nothing to fit. Go back to step 2, or enter
+ values by hand under Advanced.
+
+ ) : null}
+
+ {coarse ? (
+
+
+ {fit.notes.map((note) => (
+ {note}
+ ))}
+
+
+ ) : !manual && fit.notes.length > 0 && !nothing ? (
+
+ {fit.notes.map((note) => (
+ {note}
+ ))}
+
+ ) : null}
+
+
+
+ setName(e.target.value)} placeholder="Mars 4 — clear resin — 2.5 s" />
+
+
+ setPrinterModel(e.target.value)} />
+
+
+ setResin(e.target.value)} placeholder="Maker and name" />
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ setExposureOther(e.target.value)} placeholder="Lift speed, rest time…" />
+
+
+ setNotes(e.target.value)} placeholder="Room temperature, resin batch, how it was measured…" />
+
+
+
+
+ setSnap(event.target.checked)}
+ className="mt-0.5 h-3.5 w-3.5 accent-[var(--accent)]"
+ />
+
+ Round compensated widths to whole pixels
+
+ {xyPixelMicrons === undefined
+ ? 'Needs the XY pixel size.'
+ : 'Sizes only: where a channel lands on the pixel grid is decided in the slicer.'}
+
+
+
+
+
+
+ The file keeps every measurement, so it can be re-fitted later.
+
+
}
+ disabled={!nameOk}
+ title={nameOk ? undefined : 'Give the profile a name first'}
+ onClick={() => void save()}
+ >
+ Save profile ({DFM_PROFILE_EXTENSION}) and use it
+
+
+
+ );
+}
+
+/** One axis of the fit: the number, what it rests on, and how well it is known. */
+function FitLine({
+ label,
+ value,
+ extra,
+ axis,
+ unit,
+}: {
+ label: string;
+ value: string;
+ extra: string;
+ axis: AxisFit;
+ unit: string;
+}) {
+ let basis: string;
+ if (axis.method === 'measured') {
+ basis = `least-squares fit to ${axis.dataPoints} measured channel${axis.dataPoints === 1 ? '' : 's'}, RMS residual ${mm(axis.rmsMm ?? 0, 4)} mm`;
+ } else if (axis.method === 'open-closed') {
+ const [lo, hi] = axis.bracketMm ?? [0, null];
+ basis =
+ `from open/closed results on ${axis.dataPoints} channels — somewhere in ` +
+ (hi === null ? `${mm(lo)} ${unit} or more` : `${mm(lo)}–${mm(hi)} ${unit}`) +
+ (axis.inconsistent ? `, ${axis.inconsistent} inconsistent` : '');
+ } else {
+ basis = 'no data';
+ }
+
+ return (
+
+
+ {label}: {' '}
+ {value}
+ {extra}
+
+
{basis}
+
+ );
+}
+
+function Caution({ title, children }: { title?: string; children: ReactNode }) {
+ return (
+
+
+
+ {title ?
{title}
: null}
+ {children}
+
+
+ );
+}
diff --git a/src/components/dfm/DfmExportControls.tsx b/src/components/dfm/DfmExportControls.tsx
new file mode 100644
index 0000000..5c808ad
--- /dev/null
+++ b/src/components/dfm/DfmExportControls.tsx
@@ -0,0 +1,239 @@
+import { AlertTriangle, Check, ChevronDown, Download, Eye, FlaskConical, Trash2, Upload } from 'lucide-react';
+import { useRef } from 'react';
+import { toast } from 'sonner';
+import type { DfmCompensation } from '../../hooks/useDfmCompensation';
+import { cn } from '../../lib/cn';
+import { downloadBlob } from '../../lib/download';
+import {
+ DFM_PROFILE_EXTENSION,
+ DFM_PROFILE_MIME,
+ dfmProfileFileName,
+ parseDfmProfile,
+ serializeDfmProfile,
+} from '../../lib/dfm/profile';
+import { selectedDfmEntry, useDfmStore } from '../../store/dfmStore';
+import { useProjectStore } from '../../store/projectStore';
+import { Button } from '../ui/Button';
+import { MenuContent, MenuItem, MenuLabel, MenuRoot, MenuSeparator, MenuTrigger } from '../ui/Menu';
+import { WikiLink } from '../ui/WikiLink';
+
+const NONE_LABEL = 'None (uncompensated)';
+
+/**
+ * The print-correction profile selector in the export block.
+ *
+ * It always starts on "None (uncompensated)", and on None it is the only thing
+ * this feature adds to the screen: no hint, no prompt, no badge. Everything
+ * else — the offsets, the conflict list, the preview toggle — appears only once
+ * a profile is chosen.
+ */
+export function DfmProfileSelect() {
+ const profiles = useDfmStore((s) => s.profiles);
+ const selected = useDfmStore(selectedDfmEntry);
+ const select = useDfmStore((s) => s.select);
+ const addProfile = useDfmStore((s) => s.addProfile);
+ const removeProfile = useDfmStore((s) => s.removeProfile);
+ const setCalibrationOpen = useDfmStore((s) => s.setCalibrationOpen);
+ const lastUsed = useProjectStore((s) => s.project.dfmProfileRef);
+ const input = useRef(null);
+
+ const load = async (file: File | undefined) => {
+ if (!file) return;
+ const parsed = parseDfmProfile(await file.text());
+ if (!parsed.ok) {
+ toast.error(parsed.message, { description: parsed.details.join(' ') || undefined });
+ return;
+ }
+ const entry = await addProfile(parsed.profile);
+ select(entry.sha256);
+ toast.success(`Loaded ${entry.profile.meta.name}`, {
+ description: 'Exports now use this profile. Choose None to export the design as drawn.',
+ });
+ };
+
+ // The project remembers what it was last exported with, but never selects it
+ // on its own: a compensated export is something chosen each session.
+ const remembered = lastUsed ? profiles.find((entry) => entry.sha256 === lastUsed.sha256) : undefined;
+
+ return (
+
+
+ Print correction
+
+
+
+
+
+ {selected ? selected.profile.meta.name : NONE_LABEL}
+
+
+
+
+ : }
+ onSelect={() => select(null)}
+ >
+ {NONE_LABEL}
+
+
+ {profiles.length > 0 ? Loaded profiles : null}
+ {profiles.map((entry) => (
+ :
+ }
+ onSelect={() => select(entry.sha256)}
+ >
+ {entry.profile.meta.name}
+
+ ))}
+
+
+ } onSelect={() => input.current?.click()}>
+ Load a profile…
+
+ } onSelect={() => setCalibrationOpen(true)}>
+ Calibrate a printer…
+
+
+ {selected ? (
+ <>
+
+ }
+ onSelect={() =>
+ downloadBlob(
+ serializeDfmProfile(selected.profile),
+ dfmProfileFileName(selected.profile.meta.name),
+ DFM_PROFILE_MIME,
+ )
+ }
+ >
+ Download this profile
+
+ }
+ destructive
+ onSelect={() => removeProfile(selected.sha256)}
+ >
+ Remove from this browser
+
+ >
+ ) : null}
+
+
+
+
{
+ void load(event.target.files?.[0]);
+ event.target.value = '';
+ }}
+ />
+
+ {!selected && lastUsed ? (
+
+ Last exported with “{lastUsed.name}”
+ {remembered ? (
+ <>
+ .{' '}
+ select(remembered.sha256)}
+ >
+ Use it
+
+ >
+ ) : (
+ ', which is not loaded in this browser.'
+ )}
+
+ ) : null}
+
+ );
+}
+
+const mm = (value: number): string => value.toFixed(3);
+
+/**
+ * What the selected profile does to this design: the offsets, and any
+ * conflicts. Rendered only while a profile is selected.
+ *
+ * Conflicts are a caution box, never a gate. The export buttons stay live, and
+ * the uncompensated export is one menu choice away.
+ */
+export function DfmSummary({ dfm }: { dfm: DfmCompensation }) {
+ const { applied, conflicts } = dfm.compensated;
+ const perSide = { min: applied.widthIncreaseMm.min / 2, max: applied.widthIncreaseMm.max / 2 };
+ const varies = perSide.max - perSide.min > 0.0005;
+
+ return (
+
+
+ Δxy {varies ? `${mm(perSide.min)}–${mm(perSide.max)}` : mm(applied.deltaXyMm)} mm per side · Δz{' '}
+ {applied.deltaZMm > 0 ? `${mm(applied.deltaZMm)} mm` : 'not applied'}
+
+
+ {conflicts.length > 0 ? (
+
+
+
+
+ {conflicts.length === 1
+ ? 'Compensation causes 1 conflict'
+ : `Compensation causes ${conflicts.length} conflicts`}
+
+
+ {conflicts.slice(0, 4).map((conflict) => (
+
+ {conflict.message}
+
+ ))}
+
+ {conflicts.length > 4 ? (
+
…and {conflicts.length - 4} more.
+ ) : null}
+
+ You can still export. Give the features more room, or choose {NONE_LABEL} to export
+ the design as drawn.
+
+
+
+ ) : null}
+
+
+ Exports are enlarged to print at the drawn size. The design itself is not changed.{' '}
+ How print correction works
+
+
+ );
+}
+
+/** Beside the STL button. Only rendered while a profile is selected. */
+export function DfmPreviewToggle() {
+ const previewOpen = useDfmStore((s) => s.previewOpen);
+ const setPreviewOpen = useDfmStore((s) => s.setPreviewOpen);
+
+ return (
+ }
+ aria-pressed={previewOpen}
+ title="Show the compensated geometry over the design as drawn"
+ className={cn(
+ 'whitespace-nowrap px-2 text-[12px]',
+ previewOpen && 'border-accent bg-accent-wash text-accent hover:bg-accent-wash',
+ )}
+ onClick={() => setPreviewOpen(!previewOpen)}
+ >
+ Preview DFM
+
+ );
+}
diff --git a/src/components/dfm/DfmPreviewPanel.tsx b/src/components/dfm/DfmPreviewPanel.tsx
new file mode 100644
index 0000000..d3eff85
--- /dev/null
+++ b/src/components/dfm/DfmPreviewPanel.tsx
@@ -0,0 +1,952 @@
+import { Maximize2, Minus, Plus, Scan } from 'lucide-react';
+import {
+ useEffect,
+ useId,
+ useMemo,
+ useRef,
+ useState,
+ type PointerEvent as ReactPointerEvent,
+ type ReactNode,
+} from 'react';
+import { cn } from '../../lib/cn';
+import type { DfmCompensation } from '../../hooks/useDfmCompensation';
+import {
+ buildDfmPreview,
+ sliceSections,
+ type DfmPreviewModel,
+ type DfmSection,
+ type SliceAxis,
+} from '../../lib/dfm/preview';
+import { shortHash } from '../../lib/dfm/profile';
+import { useDfmStore } from '../../store/dfmStore';
+import { Section } from '../draw/InspectorPanel';
+import { Dialog } from '../ui/Dialog';
+import { Segmented } from '../ui/Field';
+import { WikiLink } from '../ui/WikiLink';
+
+/**
+ * The compensated-geometry preview.
+ *
+ * Read-only. It is handed the result of `compensateDesign` — the same call an
+ * export makes — and draws it over the nominal design. It holds no reference to
+ * a store action that edits the project, so there is nothing in here that
+ * could change the design, its undo history or the saved file.
+ *
+ * ## How a change is shown
+ *
+ * Never by colour alone:
+ *
+ * - **as drawn** — a translucent fill with a *dashed* outline;
+ * - **material removed** — *diagonal hatching* between the drawn and the
+ * compensated outline;
+ * - **moved edge** — a *solid* outline in the accent colour;
+ * - **conflict** — *cross-hatching*, a heavier outline in the danger colour,
+ * and a diamond marker where it is;
+ * - **unchanged** — a thin solid neutral outline and no hatching.
+ *
+ * All of it is drawn from the theme tokens, so it follows light and dark.
+ */
+
+type Hover = { edgeId: string } | null;
+
+interface ViewState {
+ /** 1 fits the chip in the frame. */
+ zoom: number;
+ /** Chip-space point at the middle of the frame, mm. */
+ cx: number;
+ cy: number;
+}
+
+const mm = (value: number, places = 3): string => value.toFixed(places);
+
+// ---------------------------------------------------------------------------
+// the sidebar panel and its fullscreen twin
+// ---------------------------------------------------------------------------
+
+export function DfmPreviewPanel({ dfm }: { dfm: DfmCompensation }) {
+ const [fullscreen, setFullscreen] = useState(false);
+ const [axis, setAxis] = useState('x');
+ /** Slice position as a fraction of the chip, so it survives a chip resize. */
+ const [fraction, setFraction] = useState(0.5);
+ const setPreviewOpen = useDfmStore((s) => s.setPreviewOpen);
+
+ const { nominal, compensated, entry } = dfm;
+ const model = useMemo(() => buildDfmPreview(nominal, compensated), [nominal, compensated]);
+
+ const span = axis === 'x' ? model.chip.width : model.chip.length;
+ const position = fraction * span;
+ const sections = useMemo(
+ () => sliceSections(nominal, compensated, axis, position),
+ [nominal, compensated, axis, position],
+ );
+
+ const body = (large: boolean) => (
+ setFraction(Math.min(1, Math.max(0, value / span)))}
+ />
+ );
+
+ return (
+ <>
+
+ setFullscreen(true)}
+ className="oc-pressable rounded p-1 text-ink-muted hover:bg-sunken hover:text-ink"
+ >
+
+
+ setPreviewOpen(false)}
+ className="oc-pressable rounded px-1.5 py-0.5 text-[11px] text-accent hover:bg-accent-wash"
+ >
+ Hide
+
+
+ }
+ >
+ {/* Unmounted while the fullscreen view is up, so there is one live
+ view and the sidebar shows exactly what was left on return. */}
+ {fullscreen ? (
+ Shown full size.
+ ) : (
+ body(false)
+ )}
+
+
+
+ {fullscreen ? body(true) : null}
+
+ >
+ );
+}
+
+function PreviewBody({
+ large,
+ dfm,
+ model,
+ sections,
+ axis,
+ onAxis,
+ position,
+ onPosition,
+}: {
+ large: boolean;
+ dfm: DfmCompensation;
+ model: DfmPreviewModel;
+ sections: DfmSection[];
+ axis: SliceAxis;
+ onAxis: (axis: SliceAxis) => void;
+ position: number;
+ onPosition: (value: number) => void;
+}) {
+ const [hover, setHover] = useState(null);
+ const { compensated, entry } = dfm;
+ const { applied } = compensated;
+
+ const perSide = {
+ min: applied.widthIncreaseMm.min / 2,
+ max: applied.widthIncreaseMm.max / 2,
+ };
+ const varies = perSide.max - perSide.min > 0.0005;
+
+ const numbers = (
+
+
+ {entry.profile.meta.name}
+
+ {shortHash(entry.sha256)}
+
+
+
+ Δxy
+
+ {varies ? `${mm(perSide.min)}–${mm(perSide.max)}` : mm(applied.deltaXyMm)} mm per side
+ {varies ? · more in narrow channels : null}
+ {applied.snappedToPixelMm ? (
+ · snapped to {mm(applied.snappedToPixelMm)} mm pixels
+ ) : null}
+
+ Δz
+
+ {applied.deltaZMm > 0 ? (
+ <>{mm(applied.deltaZMm)} mm ceiling raise>
+ ) : applied.ceilingSkipped ? (
+
+ not applied (profile: {mm(applied.profileDeltaZMm)} mm)
+
+ ) : (
+ '0 mm'
+ )}
+
+
+ {applied.ceilingSkipped ? (
+
{applied.ceilingSkipped}
+ ) : null}
+
+ );
+
+ const slice = (
+
+
+
+ Slice at {axis} = {mm(position, 2)} mm
+
+
+
+
+
+ Drag the slice line in the top view, or click to place it. The ceiling correction only
+ shows here: it is invisible from above. How to read this
+
+
+ );
+
+ if (large) {
+ return (
+
+
+
+
+
+ {numbers}
+
+ {slice}
+
+
+ );
+ }
+
+ return (
+
+ {numbers}
+
+
+ {slice}
+
+ );
+}
+
+// ---------------------------------------------------------------------------
+// patterns and legend
+// ---------------------------------------------------------------------------
+
+/** The two hatches, in screen pixels so they read the same at every zoom. */
+function Patterns({ id }: { id: string }) {
+ return (
+
+
+
+
+
+
+
+
+ );
+}
+
+function Legend() {
+ const id = useId();
+ const swatch = (children: ReactNode) => (
+
+
+ {children}
+
+ );
+ const items: { label: string; swatch: ReactNode }[] = [
+ {
+ label: 'As drawn (dashed)',
+ swatch: swatch(
+ ,
+ ),
+ },
+ {
+ label: 'Material removed (hatched)',
+ swatch: swatch( ),
+ },
+ {
+ label: 'Moved edge (solid)',
+ swatch: swatch( ),
+ },
+ {
+ label: 'Conflict (cross-hatched)',
+ swatch: swatch(
+ ,
+ ),
+ },
+ {
+ label: 'Unchanged (thin)',
+ swatch: swatch(
+ ,
+ ),
+ },
+ ];
+
+ return (
+
+ {items.map((item) => (
+
+ {item.swatch}
+ {item.label}
+
+ ))}
+
+ );
+}
+
+// ---------------------------------------------------------------------------
+// top view
+// ---------------------------------------------------------------------------
+
+function useElementSize() {
+ const ref = useRef(null);
+ const [size, setSize] = useState({ width: 0, height: 0 });
+ useEffect(() => {
+ const element = ref.current;
+ if (!element) return;
+ const observer = new ResizeObserver(([entry]) => {
+ const { width, height } = entry.contentRect;
+ setSize({ width, height });
+ });
+ observer.observe(element);
+ return () => observer.disconnect();
+ }, []);
+ return { ref, size };
+}
+
+const PADDING_PX = 14;
+/** 0.05 mm of bleed is a few pixels at this zoom on a 40 mm chip; more is only empty canvas. */
+const MAX_ZOOM = 120;
+
+function TopView({
+ model,
+ axis,
+ position,
+ onPosition,
+ hover,
+ className,
+}: {
+ model: DfmPreviewModel;
+ axis: SliceAxis;
+ position: number;
+ onPosition: (value: number) => void;
+ hover: Hover;
+ className?: string;
+}) {
+ const id = useId();
+ const { ref, size } = useElementSize();
+ const { chip } = model;
+ const [view, setView] = useState({ zoom: 1, cx: chip.width / 2, cy: chip.length / 2 });
+ const drag = useRef<
+ | { kind: 'pan'; x: number; y: number; cx: number; cy: number }
+ | { kind: 'slice' }
+ | null
+ >(null);
+
+ const fit =
+ size.width > 0
+ ? Math.min(
+ (size.width - PADDING_PX * 2) / chip.width,
+ (size.height - PADDING_PX * 2) / chip.length,
+ )
+ : 1;
+ const scale = Math.max(1e-6, fit * view.zoom);
+
+ // Chip space is y-up; the screen is y-down.
+ const px = (x: number) => size.width / 2 + (x - view.cx) * scale;
+ const py = (y: number) => size.height / 2 - (y - view.cy) * scale;
+ const toChip = (sx: number, sy: number) => ({
+ x: view.cx + (sx - size.width / 2) / scale,
+ y: view.cy - (sy - size.height / 2) / scale,
+ });
+
+ const zoomBy = (factor: number, at?: { x: number; y: number }) =>
+ setView((current) => {
+ const zoom = Math.min(MAX_ZOOM, Math.max(1, current.zoom * factor));
+ if (zoom === 1) return { zoom, cx: chip.width / 2, cy: chip.length / 2 };
+ if (!at) return { ...current, zoom };
+ // Keep the chip point under the cursor where it is.
+ const k = current.zoom / zoom;
+ return { zoom, cx: at.x + (current.cx - at.x) * k, cy: at.y + (current.cy - at.y) * k };
+ });
+
+ // React registers wheel listeners as passive, which cannot stop the sidebar
+ // scrolling underneath the zoom. A native listener can.
+ const wheel = useRef<(event: WheelEvent) => void>(() => {});
+ wheel.current = (event) => {
+ event.preventDefault();
+ const rect = ref.current?.getBoundingClientRect();
+ if (!rect) return;
+ zoomBy(Math.exp(-event.deltaY * 0.0025), toChip(event.clientX - rect.left, event.clientY - rect.top));
+ };
+ useEffect(() => {
+ const element = ref.current;
+ if (!element) return;
+ const listener = (event: WheelEvent) => wheel.current(event);
+ element.addEventListener('wheel', listener, { passive: false });
+ return () => element.removeEventListener('wheel', listener);
+ }, [ref]);
+
+ const local = (event: ReactPointerEvent) => {
+ const rect = ref.current?.getBoundingClientRect();
+ return { x: event.clientX - (rect?.left ?? 0), y: event.clientY - (rect?.top ?? 0) };
+ };
+
+ const moveSlice = (event: ReactPointerEvent) => {
+ const point = local(event);
+ const chipPoint = toChip(point.x, point.y);
+ onPosition(axis === 'x' ? chipPoint.x : chipPoint.y);
+ };
+
+ const onPointerDown = (event: ReactPointerEvent) => {
+ event.currentTarget.setPointerCapture(event.pointerId);
+ const onSlice = (event.target as Element).closest('[data-slice]') !== null;
+ if (onSlice) {
+ drag.current = { kind: 'slice' };
+ moveSlice(event);
+ } else {
+ drag.current = { kind: 'pan', x: event.clientX, y: event.clientY, cx: view.cx, cy: view.cy };
+ }
+ };
+
+ const onPointerMove = (event: ReactPointerEvent) => {
+ const active = drag.current;
+ if (!active) return;
+ if (active.kind === 'slice') {
+ moveSlice(event);
+ return;
+ }
+ setView((current) => ({
+ ...current,
+ cx: active.cx - (event.clientX - active.x) / scale,
+ cy: active.cy + (event.clientY - active.y) / scale,
+ }));
+ };
+
+ const endDrag = (event: ReactPointerEvent) => {
+ const active = drag.current;
+ drag.current = null;
+ // A click that did not turn into a pan drops the slice line there. Once
+ // zoomed in, the line is usually off-screen and cannot be dragged back.
+ if (
+ active?.kind === 'pan' &&
+ event.type === 'pointerup' &&
+ Math.hypot(event.clientX - active.x, event.clientY - active.y) < 4
+ ) {
+ moveSlice(event);
+ }
+ };
+
+ const polygon = (points: { x: number; y: number }[]) =>
+ points.map((p) => `${px(p.x).toFixed(2)},${py(p.y).toFixed(2)}`).join(' ');
+
+ const changedEdges = model.edges.filter((e) => e.changed);
+ const changedCircles = model.circles.filter((c) => c.changed);
+ const ports = model.circles.filter((c) => c.kind === 'port');
+ const drawn = model.circles.filter((c) => c.kind !== 'port');
+
+ const sliceX = axis === 'x' ? px(position) : null;
+ const sliceY = axis === 'y' ? py(position) : null;
+
+ return (
+
+ {size.width > 0 ? (
+
+
+
+ {/* The block: solid material. Channels are cut out of it below. */}
+
+
+ {/* Compensated outlines. Stroke first, then an opaque fill over the
+ inner half of it, so where two segments meet their butt ends are
+ hidden and only the outer boundary of the network shows. */}
+ {changedEdges.map((edge) => (
+
+ ))}
+ {changedCircles.map((circle) => (
+
+ ))}
+ {changedEdges.map((edge) => (
+
+ ))}
+ {changedCircles.map((circle) => (
+
+ ))}
+ {changedEdges.map((edge) => (
+
+ ))}
+ {changedCircles.map((circle) => (
+
+ ))}
+
+ {/* The design as drawn, on top: same stroke-then-mask order, so the
+ hatching survives only between the two outlines. */}
+ {model.edges.map((edge) => (
+
+ ))}
+ {drawn.map((circle) => (
+
+ ))}
+ {model.edges.map((edge) => (
+
+ ))}
+ {drawn.map((circle) => (
+
+ ))}
+ {/* One group opacity, so overlapping segments do not darken twice. */}
+
+ {model.edges.map((edge) => (
+
+ ))}
+ {drawn.map((circle) => (
+
+ ))}
+
+
+ {/* Ports are not compensated: a thin neutral ring, nothing more. */}
+ {ports.map((circle) => (
+
+ ))}
+
+ {/* The channel under the pointer in the cross-section strip. */}
+ {model.edges
+ .filter((edge) => edge.id === hover?.edgeId)
+ .map((edge) => (
+
+ ))}
+
+ {model.conflictMarks.map((mark) => (
+
+
+
+
+
+ ))}
+
+ {/* The slice line: a visible rule, a grip, and a wide invisible
+ stroke so it can be grabbed without pixel-hunting. */}
+
+
+
+
+
+
+
+ ) : null}
+
+
+
zoomBy(1 / 1.6)}>
+
+
+
+ {view.zoom < 10 ? view.zoom.toFixed(1) : Math.round(view.zoom)}×
+
+
zoomBy(1.6)}>
+
+
+
setView({ zoom: 1, cx: chip.width / 2, cy: chip.length / 2 })}
+ >
+
+
+
+
+ {view.zoom === 1 ? (
+
+ Scroll to zoom
+
+ ) : null}
+
+ );
+}
+
+function ViewButton({
+ label,
+ onClick,
+ children,
+}: {
+ label: string;
+ onClick: () => void;
+ children: ReactNode;
+}) {
+ return (
+
+ {children}
+
+ );
+}
+
+// ---------------------------------------------------------------------------
+// cross-sections
+// ---------------------------------------------------------------------------
+
+const MAX_SECTIONS_SMALL = 6;
+const MAX_SECTIONS_LARGE = 24;
+
+function Sections({
+ sections,
+ axis,
+ large,
+ hover,
+ onHover,
+ chipTopZ,
+}: {
+ sections: DfmSection[];
+ axis: SliceAxis;
+ large: boolean;
+ hover: Hover;
+ onHover: (hover: Hover) => void;
+ chipTopZ: number;
+}) {
+ if (sections.length === 0) {
+ return (
+
+ The slice line does not cross a channel here. Drag it onto one.
+
+ );
+ }
+
+ const limit = large ? MAX_SECTIONS_LARGE : MAX_SECTIONS_SMALL;
+ const shown = sections.slice(0, limit);
+ const along = axis === 'x' ? 'y' : 'x';
+
+ return (
+
+
+ {shown.map((section, index) => (
+ onHover({ edgeId: section.edgeId })}
+ onPointerLeave={() => onHover(null)}
+ className={cn(
+ 'rounded-lg border bg-elevated p-1.5',
+ hover?.edgeId === section.edgeId ? 'border-line-strong' : 'border-line',
+ )}
+ >
+
+
+ {along} = {mm(section.alongMm, 2)}
+ {section.conflict ? conflict : null}
+
+
+ w {mm(section.nominal.widthMm)} → {mm(section.compensated.widthMm)}
+
+
+ h {mm(section.nominal.heightMm)} → {mm(section.compensated.heightMm)}
+
+ {section.obliqueStretch > 1.02 ? (
+
+ cut at an angle, drawn {section.obliqueStretch.toFixed(2)}× wide
+
+ ) : null}
+
+ ))}
+
+ {sections.length > shown.length ? (
+
+ +{sections.length - shown.length} more on this line
+ {large ? '' : ' — open the preview full size to see them'}.
+
+ ) : null}
+
+ );
+}
+
+const CELL = { width: 116, height: 78, pad: 9 };
+
+/** One channel profile, scaled to fill its cell. */
+function SectionCell({ section, chipTopZ }: { section: DfmSection; chipTopZ: number }) {
+ const id = useId();
+ const all = [...section.nominal.points, ...section.compensated.points];
+ const sMin = Math.min(...all.map((p) => p.s));
+ const sMax = Math.max(...all.map((p) => p.s));
+ const zMin = Math.min(...all.map((p) => p.z));
+ const zMax = Math.max(...all.map((p) => p.z));
+
+ const scale = Math.min(
+ (CELL.width - CELL.pad * 2) / Math.max(sMax - sMin, 1e-6),
+ (CELL.height - CELL.pad * 2) / Math.max(zMax - zMin, 1e-6),
+ );
+ const x = (s: number) => CELL.width / 2 + (s - (sMin + sMax) / 2) * scale;
+ const y = (z: number) => CELL.height / 2 - (z - (zMin + zMax) / 2) * scale;
+ const polygon = (points: { s: number; z: number }[]) =>
+ points.map((p) => `${x(p.s).toFixed(2)},${y(p.z).toFixed(2)}`).join(' ');
+
+ const changed =
+ section.compensated.widthMm !== section.nominal.widthMm ||
+ section.compensated.ceilingZ !== section.nominal.ceilingZ;
+ const tone = section.conflict ? 'var(--danger)' : 'var(--accent)';
+ const topY = y(chipTopZ);
+ // A 0.1 mm scale bar, when it fits, so the cell is not a shape without a size.
+ const barPx = 0.1 * scale;
+
+ return (
+
+
+ {/* The top face of the chip, when the roof is thin enough to be in frame. */}
+ {topY > 1 && topY < CELL.height - 1 ? (
+ <>
+
+
+ >
+ ) : null}
+
+ {changed ? (
+ <>
+
+
+ >
+ ) : null}
+
+
+
+
+ {barPx > 6 && barPx < CELL.width / 2 ? (
+
+
+
+ 0.1
+
+
+ ) : null}
+
+ );
+}
diff --git a/src/hooks/useDfmCompensation.ts b/src/hooks/useDfmCompensation.ts
new file mode 100644
index 0000000..1d67ea7
--- /dev/null
+++ b/src/hooks/useDfmCompensation.ts
@@ -0,0 +1,62 @@
+import { useEffect, useMemo, useState } from 'react';
+import { compensateDesign, type CompensatedDesign, type NominalDesign } from '../lib/dfm/compensate';
+import type { DfmEntry } from '../lib/dfm/exportPlan';
+import { selectedDfmEntry, useDfmStore } from '../store/dfmStore';
+import { useProjectStore } from '../store/projectStore';
+import { useValidationStore } from '../store/validationStore';
+
+/**
+ * Long enough that a node drag or a held arrow key collapses into one
+ * recompute, short enough that the panel reads as following the edit.
+ */
+const RECOMPUTE_DEBOUNCE_MS = 150;
+
+function useDebouncedValue(value: T, delayMs: number): T {
+ const [settled, setSettled] = useState(value);
+ useEffect(() => {
+ const timer = setTimeout(() => setSettled(value), delayMs);
+ return () => clearTimeout(timer);
+ }, [value, delayMs]);
+ return settled;
+}
+
+export interface DfmCompensation {
+ entry: DfmEntry;
+ nominal: NominalDesign;
+ compensated: CompensatedDesign;
+}
+
+/**
+ * The compensated design for the open project and the selected profile, or
+ * null when no profile is selected — in which case nothing is computed at all.
+ *
+ * This is what the CAD panel *shows*: the offsets, the conflict list and the
+ * preview. It only reads the project. An export does not use it; it calls
+ * `planExport` against the store's current state at the moment of the click, so
+ * a file can never be written from a value that is 150 ms stale.
+ *
+ * Recomputation is debounced and stays on the main thread. One pass —
+ * compensation, both spacing checks and the preview geometry — measures about
+ * 15 ms on the largest template (`preview.test.ts` holds it under a budget),
+ * which is under a frame at the rate the debounce lets it run. It is the same
+ * order of work the Design checks panel already does on every edit.
+ */
+export function useDfmCompensation(): DfmCompensation | null {
+ const entry = useDfmStore(selectedDfmEntry);
+ const graph = useProjectStore((s) => s.project.channelGraph);
+ const chipParams = useProjectStore((s) => s.project.chipParams);
+ const drainageVents = useProjectStore((s) => s.project.drainageVents);
+ const printerProfile = useProjectStore((s) => s.project.printerProfile);
+ const settings = useValidationStore((s) => s.settings);
+
+ const live = useMemo(
+ () => ({ graph, chipParams, drainageVents, printerProfile }),
+ [graph, chipParams, drainageVents, printerProfile],
+ );
+ const nominal = useDebouncedValue(live, RECOMPUTE_DEBOUNCE_MS);
+
+ return useMemo(() => {
+ if (!entry) return null;
+ return { entry, nominal, compensated: compensateDesign(nominal, entry.profile, { settings }) };
+ }, [entry, nominal, settings]);
+}
diff --git a/src/lib/cad/buildChip.ts b/src/lib/cad/buildChip.ts
index d34b56b..8a9fc78 100644
--- a/src/lib/cad/buildChip.ts
+++ b/src/lib/cad/buildChip.ts
@@ -23,7 +23,7 @@ import type {
DrainageVent,
PortNode,
} from '../../types/project';
-import { placeChannel, profilePoints, radialSegmentsFor } from './placement';
+import { ceilingZ, placeChannel, profilePoints, radialSegmentsFor } from './placement';
import { slidePocket, withChannelPlane } from './slide';
import { buildPort, coneMesh, filletedBossMesh } from './portGeometry';
import { planarFrame, sweepStations, type RawMesh, type SweepStation } from './sweep';
@@ -88,6 +88,12 @@ export interface BuildOptions {
* an STL.
*/
includeChannelSolid?: boolean;
+ /**
+ * Lifts every channel, joint and chamber ceiling by this much, mm, leaving
+ * floors where they were drawn. Print correction for cure-through into a
+ * roofed channel; see `lib/dfm`. Zero — the default — is the nominal build.
+ */
+ ceilingRaiseMm?: number;
}
export interface ChipPiece {
@@ -161,8 +167,18 @@ function buildChannelNetwork(
loft: LoftSolution,
adjacency: Map,
own: Own,
+ ceilingRaiseMm = 0,
): { solid: ManifoldLike | null; volume: number } {
const parts: ManifoldLike[] = [];
+ // A joint or a chamber is a primitive, with no profile to stretch. Unioning
+ // a second copy lifted by the raise extends its top by exactly that much —
+ // exactly for a cylinder, as a capsule for a sphere — and leaves its floor
+ // alone. Nothing is added when there is no raise, so a nominal build is the
+ // same list of solids it always was.
+ const place3 = (solid: ManifoldLike, x: number, y: number, z: number) => {
+ parts.push(own(solid.translate([x, y, z])));
+ if (ceilingRaiseMm > 0) parts.push(own(solid.translate([x, y, z + ceilingRaiseMm])));
+ };
for (const edge of graph.edges) {
const solved = loft.edges.get(edge.id);
@@ -181,7 +197,13 @@ function buildChannelNetwork(
center: { x: sample.point.x, y: sample.point.y, z: place.centerZ },
across: frame.across,
up: frame.up,
- profile: profilePoints(edge.crossSection, sample.widthMm, sample.heightMm, segments),
+ profile: profilePoints(
+ edge.crossSection,
+ sample.widthMm,
+ sample.heightMm,
+ segments,
+ ceilingRaiseMm,
+ ),
};
});
@@ -220,7 +242,7 @@ function buildChannelNetwork(
),
);
- parts.push(own(joint.translate([node.x, node.y, place.centerZ])));
+ place3(joint, node.x, node.y, place.centerZ);
}
// Chambers.
@@ -247,7 +269,7 @@ function buildChannelNetwork(
: api.Manifold.cylinder(node.sizeMm, node.sizeMm / 2, node.sizeMm / 2, segments, true),
);
- parts.push(own(chamber.translate([node.x, node.y, place.centerZ])));
+ place3(chamber, node.x, node.y, place.centerZ);
}
if (parts.length === 0) return { solid: null, volume: 0 };
@@ -265,6 +287,7 @@ function channelAtNode(
chipParams: ChipParams,
nodeId: string,
loft: LoftSolution,
+ ceilingRaiseMm = 0,
): { centerZ: number; topZ: number } {
const touching = edgesFrom(adjacency, nodeId);
const edge = touching[0];
@@ -277,8 +300,9 @@ function channelAtNode(
sample?.widthMm ?? chipParams.defaultChannelWidthMm,
sample?.heightMm ?? chipParams.defaultChannelHeightMm,
chipParams.splitHeight,
+ ceilingRaiseMm,
);
- return { centerZ: place.centerZ, topZ: place.centerZ + place.halfHeight };
+ return { centerZ: place.centerZ, topZ: ceilingZ(place) };
}
const channelZAtNode = (
@@ -324,6 +348,7 @@ function buildChipOwned(
const quality = options.quality ?? 1;
const vents = options.drainageVents ?? [];
const includeChannelSolid = options.includeChannelSolid ?? false;
+ const ceilingRaiseMm = Math.max(0, options.ceilingRaiseMm ?? 0);
const warnings: string[] = [];
// Ports and chambers are the largest curved features on the chip and there
// are only a handful of them, so they carry a finer ring than the channels:
@@ -341,7 +366,16 @@ function buildChipOwned(
const adjacency = buildAdjacency(graph.edges);
// --- 1-2. channel network + chambers -------------------------------------
- const network = buildChannelNetwork(api, graph, placed, quality, loft, adjacency, own);
+ const network = buildChannelNetwork(
+ api,
+ graph,
+ placed,
+ quality,
+ loft,
+ adjacency,
+ own,
+ ceilingRaiseMm,
+ );
const cavityParts: ManifoldLike[] = network.solid ? [network.solid] : [];
// --- 3. ports -------------------------------------------------------------
@@ -354,7 +388,7 @@ function buildChipOwned(
if (node.type !== 'port') continue;
portCount += 1;
- const channel = channelAtNode(adjacency, placed, node.id, loft);
+ const channel = channelAtNode(adjacency, placed, node.id, loft, ceilingRaiseMm);
const port = buildPort(node as PortNode, topZ, channel.centerZ, segments, channel.topZ);
usedThreadApproximation ||= port.approximated;
diff --git a/src/lib/cad/golden/default-exports.json b/src/lib/cad/golden/default-exports.json
new file mode 100644
index 0000000..477746d
--- /dev/null
+++ b/src/lib/cad/golden/default-exports.json
@@ -0,0 +1,442 @@
+{
+ "template:serpentine-mixer": {
+ "all.stl": {
+ "sha256": "9a869ae0dc39474ccffa11e0e944755bb54fd995559a4f45090be8417049f334",
+ "bytes": 486384,
+ "triangles": 9726,
+ "volumeMm3": 9580.258,
+ "boundsMm": [
+ 0,
+ 0,
+ 0,
+ 40,
+ 60,
+ 7.5
+ ]
+ },
+ "body.stl": {
+ "sha256": "b4a07029078d7f476befbcd91bc91fdb45895afa25f5794d15bbbbacab6ab1c3",
+ "bytes": 252284,
+ "triangles": 5044,
+ "volumeMm3": 4706.268,
+ "boundsMm": [
+ 0,
+ 0,
+ 0,
+ 40,
+ 60,
+ 2
+ ]
+ },
+ "lid.stl": {
+ "sha256": "a5207e18d50a64a1b99f8b0910ea718369d8b8e222aab1a14319e5bd681347cf",
+ "bytes": 234184,
+ "triangles": 4682,
+ "volumeMm3": 4873.99,
+ "boundsMm": [
+ 0,
+ 0,
+ 2,
+ 40,
+ 60,
+ 7.5
+ ]
+ },
+ "source.scad": {
+ "sha256": "8fc9bf2deb2bcfd73b1c480d95fb70f922febf0b5978e065f6cd1b5e3e56aab8",
+ "bytes": 34375
+ },
+ "schematic.svg": {
+ "sha256": "c0ce229792ed46d5d0cc1c6cf33e859fe594ea75393fc96519dcebe492a9f020",
+ "bytes": 16433
+ }
+ },
+ "template:t-junction-mixer": {
+ "all.stl": {
+ "sha256": "c43c87c025ee3dbf65e7588b319b1c5f7a2e51b966e1abe649a9635b68c2b5d3",
+ "bytes": 289384,
+ "triangles": 5786,
+ "volumeMm3": 5805.963,
+ "boundsMm": [
+ 0,
+ 0,
+ 0,
+ 36,
+ 40,
+ 7.5
+ ]
+ },
+ "body.stl": {
+ "sha256": "28f7000134723b494dbe1b5b19ec64bafdee849cc4b391eb65000e9c35a6d368",
+ "bytes": 89784,
+ "triangles": 1794,
+ "volumeMm3": 2851.973,
+ "boundsMm": [
+ 0,
+ 0,
+ 0,
+ 36,
+ 40,
+ 2
+ ]
+ },
+ "lid.stl": {
+ "sha256": "939924889686d7854050e85378d6317326f9828551a13ffb14b8dfe0c53f7a87",
+ "bytes": 199684,
+ "triangles": 3992,
+ "volumeMm3": 2953.99,
+ "boundsMm": [
+ 0,
+ 0,
+ 2,
+ 36,
+ 40,
+ 7.5
+ ]
+ },
+ "source.scad": {
+ "sha256": "0ff3a1e3028574a355c1ac56f9886a231804df1c9b505ef3bd046fb1e1db0681",
+ "bytes": 14626
+ },
+ "schematic.svg": {
+ "sha256": "6dc46ecc0d69d3c9bdb87031cafb00d73a5defb35fdedebf52e69f385bfbd1b9",
+ "bytes": 5971
+ }
+ },
+ "template:y-junction-mixer": {
+ "all.stl": {
+ "sha256": "98487488d5f69f7eeea4581da147442ce45bfb20ad2351f2ce28255d7696468f",
+ "bytes": 381534,
+ "triangles": 7629,
+ "volumeMm3": 6383.156,
+ "boundsMm": [
+ 0,
+ 0,
+ 0,
+ 36,
+ 44,
+ 7.5
+ ]
+ },
+ "body.stl": {
+ "sha256": "98418ab40a25d3797b202072c09a3ee4115c2e1c37d726e89ace8a9c58d909b8",
+ "bytes": 146584,
+ "triangles": 2930,
+ "volumeMm3": 3141.166,
+ "boundsMm": [
+ 0,
+ 0,
+ 0,
+ 36,
+ 44,
+ 2
+ ]
+ },
+ "lid.stl": {
+ "sha256": "8420791aef61e9fce7311980227f87a81ea0d867adf70e085ed405137bbe93e7",
+ "bytes": 235034,
+ "triangles": 4699,
+ "volumeMm3": 3241.99,
+ "boundsMm": [
+ 0,
+ 0,
+ 2,
+ 36,
+ 44,
+ 7.5
+ ]
+ },
+ "source.scad": {
+ "sha256": "9fae5b04812a43d59f436c974fa06dff9e5d38bb8f369a1715b001067590815e",
+ "bytes": 12960
+ },
+ "schematic.svg": {
+ "sha256": "6e3b20cbe5684b4e3b1a7c7451ff3ddda4e0c808d85c52c7a5bfd363300d5ca7",
+ "bytes": 7645
+ }
+ },
+ "template:herringbone-mixer": {
+ "all.stl": {
+ "sha256": "94fdc1036348493b09a8bc861480cd5dd3873d8d795e843195edb1e606f236f3",
+ "bytes": 449684,
+ "triangles": 8992,
+ "volumeMm3": 9147.23,
+ "boundsMm": [
+ 0,
+ 0,
+ 0,
+ 30,
+ 76,
+ 7.5
+ ]
+ },
+ "body.stl": {
+ "sha256": "6d1e972f49b836378aad6c74277ce7078d1c76fb3c90d7efa25e81bd04b028c5",
+ "bytes": 178184,
+ "triangles": 3562,
+ "volumeMm3": 4513.24,
+ "boundsMm": [
+ 0,
+ 0,
+ 0,
+ 30,
+ 76,
+ 2
+ ]
+ },
+ "lid.stl": {
+ "sha256": "ba7ef026f74c1742d4dbf75dee758d3b1e860873543aa6b0b091ebfba4990a4c",
+ "bytes": 271584,
+ "triangles": 5430,
+ "volumeMm3": 4633.99,
+ "boundsMm": [
+ 0,
+ 0,
+ 2,
+ 30,
+ 76,
+ 7.5
+ ]
+ },
+ "source.scad": {
+ "sha256": "610fa6d25cb0dfc24649c46c0003fc761d4a0a8a52b1e4e5dd9f83f02e7b275f",
+ "bytes": 30291
+ },
+ "schematic.svg": {
+ "sha256": "66c10b99d3f48a9c1ee4bbaa554ec42c680601af66304d982a4c9a685ab241ba",
+ "bytes": 12435
+ }
+ },
+ "template:spiral-mixer": {
+ "all.stl": {
+ "sha256": "c73467f9ea655e3404584d71cf112913a14c76dd89988c5049b16ea890ce5889",
+ "bytes": 865784,
+ "triangles": 17314,
+ "volumeMm3": 14364.102,
+ "boundsMm": [
+ 0,
+ 0,
+ 0,
+ 60,
+ 60,
+ 7.5
+ ]
+ },
+ "body.stl": {
+ "sha256": "d72327481963da7e5653209e688499a9a2a586ccddd9c08554f86bd4eb40e6d2",
+ "bytes": 468584,
+ "triangles": 9370,
+ "volumeMm3": 7090.112,
+ "boundsMm": [
+ 0,
+ 0,
+ 0,
+ 60,
+ 60,
+ 2
+ ]
+ },
+ "lid.stl": {
+ "sha256": "09f347a69f794fcd571cdfa8151e7824c54211dbd63f85f6dc5628709e085d69",
+ "bytes": 397284,
+ "triangles": 7944,
+ "volumeMm3": 7273.99,
+ "boundsMm": [
+ 0,
+ 0,
+ 2,
+ 60,
+ 60,
+ 7.5
+ ]
+ },
+ "source.scad": {
+ "sha256": "d3d27f6eb38c863a91e3eab02b2dfdaefea69e067479e6bbcc109d2c4f79efc5",
+ "bytes": 53824
+ },
+ "schematic.svg": {
+ "sha256": "142cf0c4fb6a908ba3c688f2025bcc151311b804fab9df2b5fb7fe457594ccca",
+ "bytes": 26431
+ }
+ },
+ "template:gradient-generator": {
+ "all.stl": {
+ "sha256": "30f40657175d60f75c418e4883a46275026209284496af239b60efed79b86582",
+ "bytes": 1024484,
+ "triangles": 20488,
+ "volumeMm3": 16823.089,
+ "boundsMm": [
+ 0,
+ 0,
+ 0,
+ 60,
+ 70,
+ 7.5
+ ]
+ },
+ "body.stl": {
+ "sha256": "c8b997d696c476931c2702311e81650f428957ff28a7f998f2dd642271b9adde",
+ "bytes": 429984,
+ "triangles": 8598,
+ "volumeMm3": 8275.109,
+ "boundsMm": [
+ 0,
+ 0,
+ 0,
+ 60,
+ 70,
+ 2
+ ]
+ },
+ "lid.stl": {
+ "sha256": "4a44329eed16be6cc2e0b7ed0a975a48b27c7219a9a1812af7ce25dd9f2e073d",
+ "bytes": 594584,
+ "triangles": 11890,
+ "volumeMm3": 8547.98,
+ "boundsMm": [
+ 0,
+ 0,
+ 2,
+ 60,
+ 70,
+ 7.5
+ ]
+ },
+ "source.scad": {
+ "sha256": "9332f7ff671f638df782ead12d88e7c8dd63589b260a7353def281aa3b3b1dae",
+ "bytes": 97653
+ },
+ "schematic.svg": {
+ "sha256": "56c058e3d3d543f5451a1ca9889710c3e1c2534593006c3e7783bfdee3b4b2a5",
+ "bytes": 33835
+ }
+ },
+ "template:droplet-generator": {
+ "all.stl": {
+ "sha256": "eb64450a64ee2e7d597dd821c947526d2efa299d65fda608ec29a5222e0858bc",
+ "bytes": 410934,
+ "triangles": 8217,
+ "volumeMm3": 8148.7,
+ "boundsMm": [
+ 0,
+ 0,
+ 0,
+ 40,
+ 50,
+ 9
+ ]
+ },
+ "body.stl": {
+ "sha256": "d46e46d62c8512c7adcb027377a827a6d55c137b72ae7ef31cd0f4ab4b8439e0",
+ "bytes": 115084,
+ "triangles": 2300,
+ "volumeMm3": 3967.474,
+ "boundsMm": [
+ 0,
+ 0,
+ 0,
+ 40,
+ 50,
+ 2
+ ]
+ },
+ "lid.stl": {
+ "sha256": "1039e60bb42ff41615c862992d4db972e86b6bd473216541990a7f70274ba28e",
+ "bytes": 295934,
+ "triangles": 5917,
+ "volumeMm3": 4181.226,
+ "boundsMm": [
+ 0,
+ 0,
+ 2,
+ 40,
+ 50,
+ 9
+ ]
+ },
+ "source.scad": {
+ "sha256": "9d088e94448d69f50816b4cf8c98d4eb9052952b755cfaf7a71ebc3873e03f0b",
+ "bytes": 16048
+ },
+ "schematic.svg": {
+ "sha256": "8ae268cc9b10d6273c5f172e5e5f59fdff366fcf39ddd0b712881a056e3f0715",
+ "bytes": 8568
+ }
+ },
+ "file:examples/counter-flow-exchanger.openchip": {
+ "all.stl": {
+ "sha256": "1759639ba1e969339c8b7e0c676769056797edbccfdd1e212aad0c0ba8b4a988",
+ "bytes": 248784,
+ "triangles": 4974,
+ "volumeMm3": 9616.684,
+ "boundsMm": [
+ 0,
+ 0,
+ 0,
+ 40,
+ 60,
+ 7.5
+ ]
+ },
+ "body.stl": {
+ "sha256": "defa17eaa5a3cc045bc31fb3673636bdc6ef9097d779298ccd8c5d1b0b5882a3",
+ "bytes": 83184,
+ "triangles": 1662,
+ "volumeMm3": 4770.85,
+ "boundsMm": [
+ 0,
+ 0,
+ 0,
+ 40,
+ 60,
+ 2
+ ]
+ },
+ "lid.stl": {
+ "sha256": "a79db1c2b3c67432f1af39cdd2eba165bc5feacfd17a4ad8faa1e707fd98a005",
+ "bytes": 165684,
+ "triangles": 3312,
+ "volumeMm3": 4845.833,
+ "boundsMm": [
+ 0,
+ 0,
+ 2,
+ 40,
+ 60,
+ 7.5
+ ]
+ },
+ "source.scad": {
+ "sha256": "c72ecb10c5c7ec1536c3c0c843355cb38504b51716d01726283fa4164da6f57d",
+ "bytes": 14709
+ },
+ "schematic.svg": {
+ "sha256": "b36f8674cc3eb67d0ac4f14c182e7c26ff69b418047cc75a776220855b782d75",
+ "bytes": 6635
+ }
+ },
+ "file:skills/openchip-design/examples/chamber-mixer.openchip": {
+ "all.stl": {
+ "sha256": "968e2614de7ccc0b83512e179ba288c8f2caa82056b3dc71d6011c06d1c6d92d",
+ "bytes": 442734,
+ "triangles": 8853,
+ "volumeMm3": 14338.121,
+ "boundsMm": [
+ 0,
+ 0,
+ 0,
+ 40,
+ 60,
+ 9.5
+ ]
+ },
+ "source.scad": {
+ "sha256": "7f6c097305f8ceb8417d4d711379e23d1af30de435c392843cf9a7f15274643c",
+ "bytes": 16706
+ },
+ "schematic.svg": {
+ "sha256": "b404b63952fa0974fb01738ff1bc1864d42a36fac6218b0e009461fb817eb7af",
+ "bytes": 7146
+ }
+ }
+}
diff --git a/src/lib/cad/goldenExport.test.ts b/src/lib/cad/goldenExport.test.ts
new file mode 100644
index 0000000..c82f04f
--- /dev/null
+++ b/src/lib/cad/goldenExport.test.ts
@@ -0,0 +1,236 @@
+/**
+ * Default-export regression baseline.
+ *
+ * Every starter template and every shipped example project is exported the way
+ * the app exports it — STL at export quality, OpenSCAD source and the schematic
+ * SVG — and the bytes are compared with a recorded baseline in
+ * `golden/default-exports.json`. A change that is meant to leave the default
+ * export alone has to leave every one of these files byte-identical.
+ *
+ * The baseline stores a SHA-256 of each file rather than the file: nine chips'
+ * worth of binary STL is tens of megabytes, which does not belong in the
+ * repository. Beside each hash it keeps the byte length and, for STL, the
+ * triangle count, volume and bounding box, so a mismatch reports *what* moved
+ * rather than only that something did.
+ *
+ * Byte equality is achievable because the exporter is deterministic: the graph
+ * builders are pure, manifold-3d runs single-threaded as WASM, and the STL
+ * writer emits triangles in the order the kernel returns them. This file builds
+ * each chip twice and asserts that directly, so a kernel upgrade that broke the
+ * assumption would say so here instead of producing a flaky baseline.
+ *
+ * To record a new baseline after an intended change to default output:
+ *
+ * UPDATE_GOLDEN=1 npm test -- goldenExport
+ *
+ * and say in the pull request why the default export changed.
+ */
+
+import assert from 'node:assert/strict';
+import { createHash } from 'node:crypto';
+import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs';
+import { dirname, join } from 'node:path';
+import { beforeAll, describe, it } from 'vitest';
+import Module from 'manifold-3d';
+import { DEFAULT_CHIP_PARAMS, FALLBACK_PRINTER_PROFILE } from '../defaults';
+import { planExport } from '../dfm/exportPlan';
+import { CHIP_PRESETS, presetBuild } from '../presets';
+import { parseProject } from '../projectFile';
+import { exportSchematicSvg } from '../svgExport';
+import { buildChip, type ChipPiece, type ManifoldApi } from './buildChip';
+import { exportScad } from './scadExport';
+import { exportStl, stlTriangleCount } from './stlExport';
+import type { ChannelGraph, ChipParams, DrainageVent } from '../../types/project';
+
+const GOLDEN_PATH = join(process.cwd(), 'src/lib/cad/golden/default-exports.json');
+const UPDATE = process.env.UPDATE_GOLDEN === '1';
+
+/** The quality `buildForExport` requests. */
+const EXPORT_QUALITY = 2;
+
+interface Design {
+ id: string;
+ name: string;
+ graph: ChannelGraph;
+ chipParams: ChipParams;
+ drainageVents: DrainageVent[];
+}
+
+interface GoldenFile {
+ sha256: string;
+ bytes: number;
+ triangles?: number;
+ volumeMm3?: number;
+ boundsMm?: number[];
+}
+
+type GoldenDesign = Record;
+
+let api: ManifoldApi;
+
+beforeAll(async () => {
+ const raw = await Module();
+ raw.setup();
+ api = { Manifold: raw.Manifold, Mesh: raw.Mesh } as unknown as ManifoldApi;
+}, 60_000);
+
+// ---------------------------------------------------------------------------
+// the designs
+// ---------------------------------------------------------------------------
+
+function designs(): Design[] {
+ const out: Design[] = CHIP_PRESETS.map((preset) => ({
+ id: `template:${preset.id}`,
+ name: preset.name,
+ graph: presetBuild(preset).graph,
+ chipParams: { ...DEFAULT_CHIP_PARAMS, ...preset.chipParams },
+ drainageVents: [],
+ }));
+
+ // Saved files go through the real loader, so the baseline also covers what a
+ // user's existing project exports as after a schema change.
+ for (const dir of ['examples', 'skills/openchip-design/examples']) {
+ const abs = join(process.cwd(), dir);
+ for (const file of readdirSync(abs).filter((f) => f.endsWith('.openchip')).sort()) {
+ const parsed = parseProject(readFileSync(join(abs, file), 'utf8'));
+ assert.equal(parsed.ok, true, `${dir}/${file} should open`);
+ if (!parsed.ok) continue;
+ out.push({
+ id: `file:${dir}/${file}`,
+ name: parsed.project.meta.name,
+ graph: parsed.project.channelGraph,
+ chipParams: parsed.project.chipParams,
+ drainageVents: parsed.project.drainageVents,
+ });
+ }
+ }
+
+ return out;
+}
+
+// ---------------------------------------------------------------------------
+// exporting, exactly as the CAD panel and the Draw tab do
+// ---------------------------------------------------------------------------
+
+const sha256 = (data: ArrayBuffer | string): string =>
+ createHash('sha256')
+ .update(typeof data === 'string' ? data : new Uint8Array(data))
+ .digest('hex');
+
+const round = (n: number, places: number): number => Number(n.toFixed(places));
+
+function bounds(pieces: ChipPiece[]): number[] {
+ const min = [Infinity, Infinity, Infinity];
+ const max = [-Infinity, -Infinity, -Infinity];
+ for (const piece of pieces) {
+ for (let i = 0; i < piece.positions.length; i += 3) {
+ for (let axis = 0; axis < 3; axis += 1) {
+ min[axis] = Math.min(min[axis], piece.positions[i + axis]);
+ max[axis] = Math.max(max[axis], piece.positions[i + axis]);
+ }
+ }
+ }
+ return [...min, ...max].map((v) => round(v, 4));
+}
+
+function stlEntry(pieces: ChipPiece[], header: string): GoldenFile {
+ const buffer = exportStl(pieces, header);
+ return {
+ sha256: sha256(buffer),
+ bytes: buffer.byteLength,
+ triangles: stlTriangleCount(buffer),
+ volumeMm3: round(pieces.reduce((sum, p) => sum + p.volumeMm3, 0), 3),
+ boundsMm: bounds(pieces),
+ };
+}
+
+function exportAll(design: Design): GoldenDesign {
+ // Through `planExport` with no profile, as the CAD panel does it, so the
+ // baseline covers the path a user who never touches print correction takes
+ // rather than a shortcut around it.
+ const plan = planExport(
+ {
+ graph: design.graph,
+ chipParams: design.chipParams,
+ drainageVents: design.drainageVents,
+ printerProfile: FALLBACK_PRINTER_PROFILE,
+ },
+ design.name,
+ null,
+ );
+ assert.equal(plan.graph, design.graph);
+ assert.equal(plan.chipParams, design.chipParams);
+ assert.equal(plan.fileSuffix, '');
+
+ const built = buildChip(api, plan.graph, plan.chipParams, {
+ quality: EXPORT_QUALITY,
+ drainageVents: plan.drainageVents,
+ includeChannelSolid: false,
+ ceilingRaiseMm: plan.ceilingRaiseMm,
+ });
+ const header = plan.stlHeader;
+
+ const files: GoldenDesign = { 'all.stl': stlEntry(built.pieces, header) };
+ // The per-piece buttons a two-piece chip offers.
+ for (const id of ['body', 'lid'] as const) {
+ const piece = built.pieces.filter((p) => p.id === id);
+ if (piece.length > 0) files[`${id}.stl`] = stlEntry(piece, header);
+ }
+
+ const scad = exportScad(plan.graph, plan.chipParams, {
+ projectName: design.name,
+ drainageVents: plan.drainageVents,
+ ceilingRaiseMm: plan.ceilingRaiseMm,
+ headerNotes: plan.scadNotes,
+ });
+ files['source.scad'] = { sha256: sha256(scad), bytes: Buffer.byteLength(scad) };
+
+ const svg = exportSchematicSvg(design.graph, design.chipParams);
+ files['schematic.svg'] = { sha256: sha256(svg), bytes: Buffer.byteLength(svg) };
+
+ return files;
+}
+
+// ---------------------------------------------------------------------------
+
+describe('default export output', () => {
+ const all = designs();
+ const golden: Record =
+ !UPDATE && existsSync(GOLDEN_PATH) ? JSON.parse(readFileSync(GOLDEN_PATH, 'utf8')) : {};
+ const recorded: Record = {};
+
+ it('covers every template and every shipped project file', () => {
+ assert.ok(all.length >= CHIP_PRESETS.length + 2, `only ${all.length} designs`);
+ if (!UPDATE) {
+ assert.deepEqual(
+ Object.keys(golden).sort(),
+ all.map((d) => d.id).sort(),
+ 'the baseline and the shipped designs list different chips — record a new baseline',
+ );
+ }
+ });
+
+ for (const design of all) {
+ it(`${design.id} exports byte-identically to the baseline`, () => {
+ const first = exportAll(design);
+ // The premise of comparing bytes at all: the same input twice gives the
+ // same file twice.
+ assert.deepEqual(exportAll(design), first, 'the exporter is not deterministic');
+
+ recorded[design.id] = first;
+ if (UPDATE) return;
+
+ const expected = golden[design.id];
+ assert.ok(expected, `no baseline for ${design.id} — run with UPDATE_GOLDEN=1`);
+ // Whole-entry comparison, so a failure prints the triangle count, volume
+ // and bounds next to the hash and shows which of them moved.
+ assert.deepEqual(first, expected, `default export of ${design.id} changed`);
+ }, 120_000);
+ }
+
+ it('records the baseline when asked to', () => {
+ if (!UPDATE) return;
+ mkdirSync(dirname(GOLDEN_PATH), { recursive: true });
+ writeFileSync(GOLDEN_PATH, `${JSON.stringify(recorded, null, 2)}\n`);
+ });
+});
diff --git a/src/lib/cad/placement.ts b/src/lib/cad/placement.ts
index 9110fb1..445729a 100644
--- a/src/lib/cad/placement.ts
+++ b/src/lib/cad/placement.ts
@@ -32,28 +32,45 @@ export interface ChannelPlacement {
halfHeight: number;
/** True when the section straddles the split plane rather than hanging below it. */
straddlesSplit: boolean;
+ /**
+ * How far the ceiling is lifted above `centerZ + halfHeight`, mm. Zero for a
+ * nominal build. `centerZ` and `halfHeight` always describe the channel as
+ * drawn, so nothing sized from them moves; the roof alone is at
+ * `centerZ + halfHeight + ceilingRaiseMm`.
+ */
+ ceilingRaiseMm: number;
}
/**
* `widthMm` and `heightMm` are the local values from the loft solution.
* `heightMm` is ignored for `round`, where the diameter is the width.
+ *
+ * `ceilingRaiseMm` is print correction for cure-through into a roofed channel:
+ * the floor stays where it was drawn and only the ceiling goes up. It is zero
+ * everywhere except a compensated export or its preview.
*/
export function placeChannel(
crossSection: CrossSection,
widthMm: number,
heightMm: number,
splitHeight: number,
+ ceilingRaiseMm = 0,
): ChannelPlacement {
if (crossSection === 'round') {
- return { centerZ: splitHeight, halfHeight: widthMm / 2, straddlesSplit: true };
+ return { centerZ: splitHeight, halfHeight: widthMm / 2, straddlesSplit: true, ceilingRaiseMm };
}
return {
centerZ: splitHeight - heightMm / 2,
halfHeight: heightMm / 2,
straddlesSplit: false,
+ ceilingRaiseMm,
};
}
+/** Z of a placed channel's roof, including any ceiling raise. */
+export const ceilingZ = (place: ChannelPlacement): number =>
+ place.centerZ + place.halfHeight + place.ceilingRaiseMm;
+
/**
* The 2D profile of a channel, in (across, up) coordinates relative to the
* centerline. Swept along the path to make the solid.
@@ -66,13 +83,19 @@ export function profilePoints(
widthMm: number,
heightMm: number,
radialSegments: number,
+ ceilingRaiseMm = 0,
): { u: number; v: number }[] {
if (crossSection === 'round') {
const r = widthMm / 2;
+ // A raised round channel keeps its lower semicircle and stretches the
+ // upper one into a half-ellipse, so the floor and the widest point stay
+ // exactly where they were drawn.
+ const stretch = ceilingRaiseMm > 0 && r > 0 ? (r + ceilingRaiseMm) / r : 1;
const points: { u: number; v: number }[] = [];
for (let i = 0; i < radialSegments; i += 1) {
const theta = (i / radialSegments) * Math.PI * 2;
- points.push({ u: Math.cos(theta) * r, v: Math.sin(theta) * r });
+ const v = Math.sin(theta) * r;
+ points.push({ u: Math.cos(theta) * r, v: v > 0 ? v * stretch : v });
}
return points;
}
@@ -82,10 +105,11 @@ export function profilePoints(
const halfBottom = crossSection === 'trapezoid' ? (widthMm * TRAPEZOID_DRAFT) / 2 : halfTop;
// CCW: bottom-right → top-right → top-left → bottom-left.
+ const top = halfH + Math.max(0, ceilingRaiseMm);
return [
{ u: halfBottom, v: -halfH },
- { u: halfTop, v: halfH },
- { u: -halfTop, v: halfH },
+ { u: halfTop, v: top },
+ { u: -halfTop, v: top },
{ u: -halfBottom, v: -halfH },
];
}
diff --git a/src/lib/cad/scadExport.ts b/src/lib/cad/scadExport.ts
index 6463d6a..94f6660 100644
--- a/src/lib/cad/scadExport.ts
+++ b/src/lib/cad/scadExport.ts
@@ -49,6 +49,16 @@ export interface ScadOptions {
* are no longer in the graph are skipped, as they are there.
*/
drainageVents?: DrainageVent[];
+ /**
+ * Lifts every channel, joint and chamber ceiling by this much, mm, exactly
+ * as `buildChip` does for the STL. Zero — the default — is the nominal file.
+ */
+ ceilingRaiseMm?: number;
+ /**
+ * Extra comment lines for the header, written under the title. Used to
+ * record the print-correction profile a compensated file was made with.
+ */
+ headerNotes?: string[];
}
function sectionAt(
@@ -59,12 +69,18 @@ function sectionAt(
angle: number,
widthMm: number,
heightMm: number,
+ raise = 0,
): string {
const place = `translate([${f(x)}, ${f(y)}, ${f(z)}]) rotate([0, 0, ${f(angle)}])`;
if (crossSection === 'round') {
// Lay the disc's axis along the path.
- return `${place} rotate([0, 90, 0]) cylinder(h = ${f(SLICE)}, d = ${f(widthMm)}, center = true, $fn = channel_fn);`;
+ const disc = `rotate([0, 90, 0]) cylinder(h = ${f(SLICE)}, d = ${f(widthMm)}, center = true, $fn = channel_fn);`;
+ if (raise <= 0) return `${place} ${disc}`;
+ // A second disc lifted by the raise. Both sit inside the caller's hull(),
+ // which makes the pair a section with the floor where it was drawn and the
+ // ceiling higher — the nearest OpenSCAD comes to the STL's half-ellipse.
+ return `${place} ${disc} translate([${f(x)}, ${f(y)}, ${f(z + raise)}]) rotate([0, 0, ${f(angle)}]) ${disc}`;
}
if (crossSection === 'trapezoid') {
@@ -74,11 +90,17 @@ function sectionAt(
return (
`${place} linear_extrude(height = ${f(SLICE)}, center = true) ` +
`polygon([[${f(-botW / 2)}, ${f(-heightMm / 2)}], [${f(botW / 2)}, ${f(-heightMm / 2)}], ` +
- `[${f(topW / 2)}, ${f(heightMm / 2)}], [${f(-topW / 2)}, ${f(heightMm / 2)}]]);`
+ `[${f(topW / 2)}, ${f(heightMm / 2 + raise)}], [${f(-topW / 2)}, ${f(heightMm / 2 + raise)}]]);`
);
}
- return `${place} cube([${f(SLICE)}, ${f(widthMm)}, ${f(heightMm)}], center = true);`;
+ if (raise <= 0) {
+ return `${place} cube([${f(SLICE)}, ${f(widthMm)}, ${f(heightMm)}], center = true);`;
+ }
+ return (
+ `translate([${f(x)}, ${f(y)}, ${f(z + raise / 2)}]) rotate([0, 0, ${f(angle)}]) ` +
+ `cube([${f(SLICE)}, ${f(widthMm)}, ${f(heightMm + raise)}], center = true);`
+ );
}
export function exportScad(
@@ -87,6 +109,7 @@ export function exportScad(
options: ScadOptions = {},
): string {
const { stationsPerEdge = 10, projectName = 'OpenChip chip' } = options;
+ const raise = Math.max(0, options.ceilingRaiseMm ?? 0);
// A slide chip's channels sit on the pocket floor, not on the split plane.
// Every `split_height` below — the placement calls and the emitted variable
@@ -103,6 +126,7 @@ export function exportScad(
// --- header ---------------------------------------------------------------
w(`// ${projectName}`);
w('// Generated by OpenChip. All dimensions in millimetres.');
+ for (const note of options.headerNotes ?? []) w(`// ${note}`);
w('//');
w('// Edit the parameters below and re-render. The channel network is');
w('// subtracted from the chip block, so growing a channel removes material.');
@@ -184,6 +208,7 @@ export function exportScad(
deg(a.tangent.x, a.tangent.y),
a.widthMm,
a.heightMm,
+ raise,
),
);
w(
@@ -196,6 +221,7 @@ export function exportScad(
deg(b.tangent.x, b.tangent.y),
b.widthMm,
b.heightMm,
+ raise,
),
);
w(' }');
@@ -220,14 +246,14 @@ export function exportScad(
);
w(` // joint at ${node.id}`);
- if (edge.crossSection === 'round') {
- w(
- ` translate([${f(node.x)}, ${f(node.y)}, ${f(place.centerZ)}]) sphere(d = ${f(sample.widthMm)}, $fn = feature_fn);`,
- );
- } else {
- w(
- ` translate([${f(node.x)}, ${f(node.y)}, ${f(place.centerZ)}]) cylinder(h = ${f(place.halfHeight * 2)}, d = ${f(sample.widthMm)}, center = true, $fn = feature_fn);`,
- );
+ const jointBody =
+ edge.crossSection === 'round'
+ ? `sphere(d = ${f(sample.widthMm)}, $fn = feature_fn);`
+ : `cylinder(h = ${f(place.halfHeight * 2)}, d = ${f(sample.widthMm)}, center = true, $fn = feature_fn);`;
+ w(` translate([${f(node.x)}, ${f(node.y)}, ${f(place.centerZ)}]) ${jointBody}`);
+ // As in the STL: a second copy lifted by the raise extends the top only.
+ if (raise > 0) {
+ w(` translate([${f(node.x)}, ${f(node.y)}, ${f(place.centerZ + raise)}]) ${jointBody}`);
}
emittedAny = true;
}
@@ -257,6 +283,9 @@ export function exportScad(
? `sphere(d = ${f(node.sizeMm)}, $fn = feature_fn);`
: `cylinder(h = ${f(node.sizeMm)}, d = ${f(node.sizeMm)}, center = true, $fn = feature_fn);`;
w(` translate([${f(node.x)}, ${f(node.y)}, ${f(place.centerZ)}]) ${body}`);
+ if (raise > 0) {
+ w(` translate([${f(node.x)}, ${f(node.y)}, ${f(place.centerZ + raise)}]) ${body}`);
+ }
}
w('}');
w();
@@ -280,7 +309,7 @@ export function exportScad(
return luerLockLayout(
node.customSpec as Record | undefined,
chipParams.baseThickness,
- place.centerZ + place.halfHeight,
+ place.centerZ + place.halfHeight + raise,
);
};
diff --git a/src/lib/dfm/compensate.test.ts b/src/lib/dfm/compensate.test.ts
new file mode 100644
index 0000000..9003d8a
--- /dev/null
+++ b/src/lib/dfm/compensate.test.ts
@@ -0,0 +1,450 @@
+/**
+ * Compensation tests: the model's arithmetic, the transform on hand-checked
+ * designs, conflict detection, and the solid the pipeline builds from it.
+ */
+
+import assert from 'node:assert/strict';
+import { beforeAll, describe, it } from 'vitest';
+import Module from 'manifold-3d';
+import { buildChip, type ManifoldApi } from '../cad/buildChip';
+import { placeChannel, profilePoints } from '../cad/placement';
+import { exportScad } from '../cad/scadExport';
+import { getLoft } from '../loft';
+import type { ChannelGraph } from '../../types/project';
+import { compensateDesign, lateralOffsetAtMm } from './compensate';
+import { bleedPerSideMm, closureWidthMm, drawnWidthForMm, printedWidthMm } from './model';
+import { design, makeProfile, parallelChannels } from './testFixtures';
+
+let api: ManifoldApi;
+
+beforeAll(async () => {
+ const raw = await Module();
+ raw.setup();
+ api = { Manifold: raw.Manifold, Mesh: raw.Mesh } as unknown as ManifoldApi;
+}, 60_000);
+
+const near = (actual: number, expected: number, tolerance = 1e-6, label = '') =>
+ assert.ok(Math.abs(actual - expected) <= tolerance, `${label} expected ${expected}, got ${actual}`);
+
+/** One straight rect channel, 20 mm long, with whatever markers are given. */
+const single = (dimensionPoints: ChannelGraph['edges'][number]['dimensionPoints'] = []): ChannelGraph => ({
+ nodes: [
+ { id: 'a', x: 10, y: 30, type: 'waypoint' },
+ { id: 'b', x: 30, y: 30, type: 'waypoint' },
+ ],
+ edges: [
+ { id: 'e', fromNodeId: 'a', toNodeId: 'b', curveType: 'straight', crossSection: 'rect', dimensionPoints },
+ ],
+});
+
+// ---------------------------------------------------------------------------
+
+describe('lateral bleed model', () => {
+ it('is a constant offset per side when the decay length is zero', () => {
+ const model = { deltaXyMm: 0.05, lateralDecayMm: 0 };
+ near(bleedPerSideMm(0.4, model), 0.05);
+ near(printedWidthMm(0.4, model), 0.3);
+ near(drawnWidthForMm(0.4, model), 0.5);
+ near(closureWidthMm(model), 0.1);
+ });
+
+ it('closes a channel no wider than twice the offset', () => {
+ const model = { deltaXyMm: 0.05, lateralDecayMm: 0 };
+ assert.equal(printedWidthMm(0.1, model), 0);
+ assert.equal(printedWidthMm(0.06, model), 0);
+ });
+
+ it('tends to the isolated-edge offset in a wide channel', () => {
+ const model = { deltaXyMm: 0.05, lateralDecayMm: 0.04 };
+ near(bleedPerSideMm(5, model), 0.05, 1e-9);
+ // Far enough that e^(-W/λ) underflows: the stable form must not return NaN.
+ near(bleedPerSideMm(500, model), 0.05, 1e-9);
+ });
+
+ it('takes more from a narrow channel than a wide one', () => {
+ const model = { deltaXyMm: 0.05, lateralDecayMm: 0.04 };
+ assert.ok(bleedPerSideMm(0.2, model) > bleedPerSideMm(0.4, model));
+ assert.ok(bleedPerSideMm(0.4, model) > bleedPerSideMm(1, model));
+ });
+
+ it('closes exactly at 2Δ + 2λ·ln 2', () => {
+ // Hand check: Δ = 0.05, λ = 0.04 → 0.1 + 0.08 × 0.693147 = 0.155452.
+ const model = { deltaXyMm: 0.05, lateralDecayMm: 0.04 };
+ near(closureWidthMm(model), 0.155452, 1e-6);
+ assert.equal(printedWidthMm(0.155, model), 0);
+ assert.ok(printedWidthMm(0.16, model) > 0);
+ });
+
+ it('satisfies the dose balance it is derived from', () => {
+ // At the solved wall position x, e^(-x/λ) + e^(-(W-x)/λ) must equal e^(-Δ/λ).
+ const model = { deltaXyMm: 0.05, lateralDecayMm: 0.04 };
+ for (const width of [0.2, 0.3, 0.6]) {
+ const x = bleedPerSideMm(width, model);
+ const dose = Math.exp(-x / 0.04) + Math.exp(-(width - x) / 0.04);
+ near(dose, Math.exp(-0.05 / 0.04), 1e-9, `W=${width}`);
+ }
+ });
+
+ it('inverts: drawing the compensated width prints the target', () => {
+ for (const model of [
+ { deltaXyMm: 0.05, lateralDecayMm: 0 },
+ { deltaXyMm: 0.05, lateralDecayMm: 0.04 },
+ { deltaXyMm: 0.02, lateralDecayMm: 0.15 },
+ ]) {
+ for (const target of [0.05, 0.2, 0.4, 0.8, 2]) {
+ near(printedWidthMm(drawnWidthForMm(target, model), model), target, 1e-9);
+ }
+ }
+ });
+});
+
+// ---------------------------------------------------------------------------
+
+describe('compensateDesign', () => {
+ it('returns the design itself when the profile changes nothing', () => {
+ const nominal = design(single(), { splitType: 'monolithic' });
+ const out = compensateDesign(nominal, makeProfile({ deltaXyMm: 0, deltaZMm: 0 }));
+ assert.equal(out.graph, nominal.graph);
+ assert.equal(out.chipParams, nominal.chipParams);
+ assert.equal(out.drainageVents, nominal.drainageVents);
+ assert.equal(out.ceilingRaiseMm, 0);
+ assert.deepEqual(out.conflicts, []);
+ });
+
+ it('never modifies the nominal design', () => {
+ const nominal = design(single([{ t: 0, widthMm: 0.4, heightMm: 0.3 }]), { splitType: 'monolithic' });
+ const before = JSON.stringify(nominal);
+ compensateDesign(nominal, makeProfile({ lateralDecayMm: 0.04 }));
+ assert.equal(JSON.stringify(nominal), before);
+ });
+
+ it('widens a marker by twice the per-side offset and leaves its height', () => {
+ // Hand check: 0.4 mm drawn, Δxy 0.05 per side → 0.5 mm.
+ const out = compensateDesign(
+ design(single([{ t: 0.5, widthMm: 0.4, heightMm: 0.3 }])),
+ makeProfile(),
+ );
+ assert.deepEqual(out.graph.edges[0].dimensionPoints, [{ t: 0.5, widthMm: 0.5, heightMm: 0.3 }]);
+ near(out.applied.widthIncreaseMm.min, 0.1);
+ near(out.applied.widthIncreaseMm.max, 0.1);
+ });
+
+ it('gives an unmarked channel one marker carrying the corrected default', () => {
+ // The default is 0.8 × 0.5 mm; the project default itself must not move.
+ const nominal = design(single());
+ const out = compensateDesign(nominal, makeProfile());
+ assert.deepEqual(out.graph.edges[0].dimensionPoints, [{ t: 0, widthMm: 0.9, heightMm: 0.5 }]);
+ assert.equal(out.chipParams.defaultChannelWidthMm, 0.8);
+
+ const sample = getLoft(out.graph, out.chipParams).edges.get('e')?.samples[5];
+ near(sample?.widthMm ?? 0, 0.9);
+ near(sample?.heightMm ?? 0, 0.5);
+ });
+
+ it('corrects a taper along its whole length', () => {
+ const nominal = design(
+ single([
+ { t: 0, widthMm: 0.3, heightMm: 0.4 },
+ { t: 1, widthMm: 1.1, heightMm: 0.4 },
+ ]),
+ );
+ const profile = makeProfile({ lateralDecayMm: 0.06 });
+ const out = compensateDesign(nominal, profile);
+
+ const before = getLoft(nominal.graph, nominal.chipParams).edges.get('e')?.samples ?? [];
+ const after = getLoft(out.graph, out.chipParams).edges.get('e')?.samples ?? [];
+ assert.equal(after.length, before.length);
+ assert.ok(out.graph.edges[0].dimensionPoints.length > 2, 'a non-linear correction adds markers');
+
+ // Every station, not only the two the user marked, prints at its nominal
+ // width to within a micron.
+ const model = { deltaXyMm: 0.05, lateralDecayMm: 0.06 };
+ for (let i = 0; i < before.length; i += 1) {
+ near(printedWidthMm(after[i].widthMm, model), before[i].widthMm, 1e-3, `station ${i}`);
+ }
+ // And the narrow end got the larger correction.
+ assert.ok(after[0].widthMm - before[0].widthMm > after.at(-1)!.widthMm - before.at(-1)!.widthMm);
+ });
+
+ it('corrects chambers and drainage vents, and leaves ports alone', () => {
+ const graph: ChannelGraph = {
+ nodes: [
+ { id: 'in', x: 10, y: 30, type: 'port', portType: 'luer', diameterMm: 1.6, customSpec: { taperLargeDiameterMm: 4.27 } },
+ { id: 'mid', x: 20, y: 30, type: 'chamber', shape: 'cylinder', sizeMm: 3, autoPlaced: false },
+ { id: 'out', x: 30, y: 30, type: 'waypoint' },
+ ],
+ edges: [
+ { id: 'e1', fromNodeId: 'in', toNodeId: 'mid', curveType: 'straight', crossSection: 'rect', dimensionPoints: [] },
+ { id: 'e2', fromNodeId: 'mid', toNodeId: 'out', curveType: 'straight', crossSection: 'rect', dimensionPoints: [] },
+ ],
+ };
+ const nominal = {
+ ...design(graph),
+ drainageVents: [{ id: 'v', nodeId: 'out', diameterMm: 0.8, autoPlaced: false }],
+ };
+ const out = compensateDesign(nominal, makeProfile());
+
+ assert.deepEqual(out.graph.nodes[0], graph.nodes[0], 'port geometry stays nominal');
+ assert.equal(out.graph.nodes[1].type === 'chamber' && out.graph.nodes[1].sizeMm, 3.1);
+ near(out.drainageVents[0].diameterMm, 0.9);
+ });
+
+ it('snaps compensated widths to whole pixels when asked', () => {
+ // 0.4 + 0.1 = 0.5 mm; at 35 µm per pixel the nearest whole count is 14 → 0.49 mm.
+ const out = compensateDesign(
+ design(single([{ t: 0, widthMm: 0.4, heightMm: 0.3 }])),
+ makeProfile({ snapToPixelGrid: true }),
+ );
+ near(out.graph.edges[0].dimensionPoints[0].widthMm, 0.49);
+ near(out.applied.snappedToPixelMm ?? 0, 0.035);
+ });
+
+ it('does not snap when the pixel size is unknown', () => {
+ const out = compensateDesign(
+ design(single([{ t: 0, widthMm: 0.4, heightMm: 0.3 }])),
+ makeProfile({ snapToPixelGrid: true }, { xyPixelMicrons: null }),
+ );
+ near(out.graph.edges[0].dimensionPoints[0].widthMm, 0.5);
+ assert.equal(out.applied.snappedToPixelMm, null);
+ });
+
+ it('raises ceilings only on a monolithic chip', () => {
+ const profile = makeProfile({ deltaZMm: 0.12 });
+
+ const mono = compensateDesign(design(single(), { splitType: 'monolithic' }), profile);
+ assert.equal(mono.ceilingRaiseMm, 0.12);
+ assert.equal(mono.applied.ceilingSkipped, null);
+
+ const twoPiece = compensateDesign(design(single(), { splitType: 'two-piece' }), profile);
+ assert.equal(twoPiece.ceilingRaiseMm, 0);
+ assert.equal(twoPiece.applied.profileDeltaZMm, 0.12);
+ assert.match(twoPiece.applied.ceilingSkipped ?? '', /open grooves/);
+
+ const slide = compensateDesign(design(single(), { splitType: 'glass-slide' }), profile);
+ assert.equal(slide.ceilingRaiseMm, 0);
+ assert.match(slide.applied.ceilingSkipped ?? '', /glass slide/);
+ });
+
+ it('reports the per-side offset the profile applies at a width', () => {
+ near(lateralOffsetAtMm(0.4, makeProfile()), 0.05);
+ assert.ok(lateralOffsetAtMm(0.2, makeProfile({ lateralDecayMm: 0.05 })) > 0.05);
+ });
+});
+
+// ---------------------------------------------------------------------------
+
+describe('conflicts', () => {
+ // Default channels are 0.8 mm wide; the wall limit is 0.4 mm (the smaller
+ // wall thickness set here hands the decision to the printable minimum).
+ const chip = { wallThickness: 0.3 };
+
+ it('is silent when compensation leaves enough wall', () => {
+ // 2.0 pitch − 0.9 = 1.1 mm of wall.
+ const out = compensateDesign(design(parallelChannels(2), chip), makeProfile());
+ assert.deepEqual(out.conflicts, []);
+ });
+
+ it('reports a wall pushed below the printable minimum, and by how much', () => {
+ // Nominal wall 1.3 − 0.8 = 0.5 mm. Δxy 0.1 → 1.0 mm channels → 0.3 mm wall,
+ // 0.1 mm short of the 0.4 mm minimum.
+ const out = compensateDesign(design(parallelChannels(1.3), chip), makeProfile({ deltaXyMm: 0.1 }));
+ assert.equal(out.conflicts.length, 1);
+ const [conflict] = out.conflicts;
+ assert.equal(conflict.kind, 'wall-too-thin');
+ assert.deepEqual(conflict.edgeIds, ['ea', 'eb']);
+ near(conflict.compensatedMm, 0.3);
+ near(conflict.limitMm, 0.4);
+ near(conflict.shortfallMm, 0.1);
+ assert.match(conflict.message, /0\.3 mm of wall between segments ea and eb/);
+ assert.match(conflict.message, /0\.1 mm short/);
+ });
+
+ it('reports two channels merging', () => {
+ // Δxy 0.3 → 1.4 mm channels on a 1.3 mm pitch overlap by 0.1 mm.
+ const out = compensateDesign(design(parallelChannels(1.3), chip), makeProfile({ deltaXyMm: 0.3 }));
+ const merge = out.conflicts.find((c) => c.kind === 'channels-merge');
+ assert.ok(merge, JSON.stringify(out.conflicts));
+ near(merge.compensatedMm, -0.1);
+ assert.match(merge.message, /overlap by 0\.1 mm/);
+ });
+
+ it('does not blame compensation for a wall that was already too thin and did not change', () => {
+ // 0.3 mm of wall as drawn. A ceiling-only correction leaves it at 0.3.
+ const out = compensateDesign(
+ design(parallelChannels(1.1), { ...chip, splitType: 'monolithic' }),
+ makeProfile({ deltaXyMm: 0, deltaZMm: 0.05 }),
+ );
+ assert.equal(out.conflicts.filter((c) => c.kind === 'wall-too-thin').length, 0);
+ });
+
+ it('reports an already-thin wall that compensation makes thinner, with both numbers', () => {
+ const out = compensateDesign(design(parallelChannels(1.1), chip), makeProfile({ deltaXyMm: 0.05 }));
+ const [conflict] = out.conflicts;
+ assert.equal(conflict.kind, 'wall-too-thin');
+ near(conflict.nominalMm ?? 0, 0.3);
+ near(conflict.compensatedMm, 0.2);
+ assert.match(conflict.message, /was 0\.3 mm/);
+ });
+
+ it('reports a channel pushed into the edge spacing', () => {
+ const graph = parallelChannels(5);
+ // 3.45 mm from the y = 0 edge to the channel wall as drawn; limit 3 mm.
+ graph.nodes[0].y = 3.85;
+ graph.nodes[1].y = 3.85;
+ const out = compensateDesign(design(graph, chip), makeProfile({ deltaXyMm: 0.5 }));
+ const edge = out.conflicts.find((c) => c.kind === 'edge-clearance');
+ assert.ok(edge, JSON.stringify(out.conflicts));
+ near(edge.nominalMm ?? 0, 3.45);
+ near(edge.compensatedMm, 2.95);
+ assert.match(edge.message, /2\.95 mm from the chip edge/);
+ near(edge.shortfallMm, 0.05);
+ });
+
+ it('reports a raised ceiling that leaves too thin a roof', () => {
+ // Block 4 mm, split 3.5 → a 0.5 mm roof over a rect channel. Raising 0.3
+ // leaves 0.2 mm against a 0.3 mm wall thickness.
+ const out = compensateDesign(
+ design(single(), { splitType: 'monolithic', splitHeight: 3.5, wallThickness: 0.3 }),
+ makeProfile({ deltaXyMm: 0, deltaZMm: 0.3 }),
+ );
+ assert.equal(out.conflicts.length, 1);
+ const [conflict] = out.conflicts;
+ assert.equal(conflict.kind, 'ceiling-too-thin');
+ near(conflict.nominalMm ?? 0, 0.5);
+ near(conflict.compensatedMm, 0.2);
+ near(conflict.shortfallMm, 0.1);
+ assert.deepEqual(conflict.edgeIds, ['e']);
+ });
+
+ it('reports a raised ceiling that breaks through the top face', () => {
+ const out = compensateDesign(
+ design(single(), { splitType: 'monolithic', splitHeight: 3.9, wallThickness: 0.3 }),
+ makeProfile({ deltaXyMm: 0, deltaZMm: 0.2 }),
+ );
+ assert.equal(out.conflicts[0].kind, 'ceiling-breakthrough');
+ assert.match(out.conflicts[0].message, /breaks through the top face/);
+ });
+
+ it('does not report a roof that was already broken through as drawn', () => {
+ // A 1.2 mm round channel centred 0.4 mm under the top face pokes through
+ // it before any correction. That is the design's own warning.
+ const graph = single([{ t: 0, widthMm: 1.2 }]);
+ graph.edges[0].crossSection = 'round';
+ const out = compensateDesign(
+ design(graph, { splitType: 'monolithic', splitHeight: 3.6, wallThickness: 0.3 }),
+ makeProfile({ deltaXyMm: 0, deltaZMm: 0.1 }),
+ );
+ assert.deepEqual(out.conflicts, []);
+ });
+
+ it('still returns the compensated design when there are conflicts', () => {
+ const out = compensateDesign(design(parallelChannels(1.3), chip), makeProfile({ deltaXyMm: 0.3 }));
+ assert.ok(out.conflicts.length > 0);
+ near(out.graph.edges[0].dimensionPoints[0].widthMm, 1.4);
+ });
+});
+
+// ---------------------------------------------------------------------------
+
+describe('the ceiling raise in the pipeline', () => {
+ it('lifts a rectangular roof and leaves the floor', () => {
+ const points = profilePoints('rect', 0.8, 0.5, 4, 0.1);
+ assert.deepEqual(points.map((p) => p.v), [-0.25, 0.35, 0.35, -0.25]);
+ assert.deepEqual(points.map((p) => p.u), [0.4, 0.4, -0.4, -0.4]);
+ });
+
+ it('stretches only the upper half of a round channel', () => {
+ const points = profilePoints('round', 1, 0, 16, 0.2);
+ near(Math.max(...points.map((p) => p.v)), 0.7);
+ near(Math.min(...points.map((p) => p.v)), -0.5);
+ near(Math.max(...points.map((p) => p.u)), 0.5);
+ });
+
+ it('is the nominal profile when the raise is zero', () => {
+ for (const section of ['rect', 'trapezoid', 'round'] as const) {
+ assert.deepEqual(profilePoints(section, 0.8, 0.5, 16, 0), profilePoints(section, 0.8, 0.5, 16));
+ }
+ assert.deepEqual(placeChannel('rect', 0.8, 0.5, 2, 0), placeChannel('rect', 0.8, 0.5, 2));
+ });
+
+ it('removes exactly the extra volume a compensated channel should', () => {
+ // 20 mm of straight rect channel in a monolithic block, with a joint-free
+ // graph so the swept prism is the whole cavity.
+ const nominal = design(single(), { splitType: 'monolithic' });
+ const out = compensateDesign(nominal, makeProfile({ deltaXyMm: 0.05, deltaZMm: 0.1 }));
+
+ const before = buildChip(api, nominal.graph, nominal.chipParams, { quality: 2 });
+ const after = buildChip(api, out.graph, out.chipParams, {
+ quality: 2,
+ ceilingRaiseMm: out.ceilingRaiseMm,
+ });
+
+ // Hand check: 0.8 × 0.5 → 0.9 × 0.6 over 20 mm.
+ near(before.stats.channelVolumeMm3, 20 * 0.8 * 0.5, 1e-3);
+ near(after.stats.channelVolumeMm3, 20 * 0.9 * 0.6, 1e-3);
+ near(before.stats.chipVolumeMm3 - after.stats.chipVolumeMm3, 20 * (0.54 - 0.4), 1e-3);
+ });
+
+ it('raises the roof in the mesh, not the floor', () => {
+ const nominal = design(single(), { splitType: 'monolithic' });
+ const out = compensateDesign(nominal, makeProfile({ deltaXyMm: 0, deltaZMm: 0.1 }));
+ const zRange = (raise: number) => {
+ const built = buildChip(api, nominal.graph, nominal.chipParams, {
+ includeChannelSolid: true,
+ ceilingRaiseMm: raise,
+ });
+ const z = Array.from(built.channelSolid?.positions ?? []).filter((_, i) => i % 3 === 2);
+ return [Math.min(...z), Math.max(...z)];
+ };
+ const [floor, roof] = zRange(0);
+ const [floorAfter, roofAfter] = zRange(out.ceilingRaiseMm);
+ near(floorAfter, floor, 1e-5);
+ near(roofAfter, roof + 0.1, 1e-5);
+ });
+
+ it('extends joints and chambers upward with the channels', () => {
+ const graph: ChannelGraph = {
+ nodes: [
+ { id: 'a', x: 10, y: 30, type: 'waypoint' },
+ { id: 'b', x: 20, y: 30, type: 'chamber', shape: 'cylinder', sizeMm: 3, autoPlaced: false },
+ { id: 'c', x: 20, y: 40, type: 'waypoint' },
+ { id: 'd', x: 30, y: 40, type: 'waypoint' },
+ ],
+ edges: ['ab', 'bc', 'cd'].map((id) => ({
+ id,
+ fromNodeId: id[0],
+ toNodeId: id[1],
+ curveType: 'straight' as const,
+ crossSection: 'rect' as const,
+ dimensionPoints: [],
+ })),
+ };
+ const chipParams = design(graph, { splitType: 'monolithic' }).chipParams;
+ const top = (raise: number) => {
+ const built = buildChip(api, graph, chipParams, { includeChannelSolid: true, ceilingRaiseMm: raise });
+ const z = Array.from(built.channelSolid?.positions ?? []).filter((_, i) => i % 3 === 2);
+ return { max: Math.max(...z), min: Math.min(...z), volume: built.stats.channelVolumeMm3 };
+ };
+ const before = top(0);
+ const after = top(0.2);
+ near(after.max, before.max + 0.2, 1e-5);
+ near(after.min, before.min, 1e-5);
+ assert.ok(after.volume > before.volume);
+ });
+
+ it('writes the same raise into the OpenSCAD source', () => {
+ const nominal = design(single(), { splitType: 'monolithic' });
+ const plain = exportScad(nominal.graph, nominal.chipParams);
+ assert.equal(exportScad(nominal.graph, nominal.chipParams, { ceilingRaiseMm: 0 }), plain);
+
+ const raised = exportScad(nominal.graph, nominal.chipParams, {
+ ceilingRaiseMm: 0.1,
+ headerNotes: ['Print correction: Bench printer'],
+ });
+ // 0.5 mm tall → 0.6 mm, centred 0.05 mm higher (1.75 → 1.8).
+ assert.match(raised, /cube\(\[0\.01, 0\.8, 0\.6\], center = true\)/);
+ assert.match(raised, /translate\(\[10\.0, 30\.0, 1\.8\]\)/);
+ assert.match(raised, /\/\/ Print correction: Bench printer/);
+ assert.doesNotMatch(plain, /Print correction/);
+ });
+});
diff --git a/src/lib/dfm/compensate.ts b/src/lib/dfm/compensate.ts
new file mode 100644
index 0000000..b8e448e
--- /dev/null
+++ b/src/lib/dfm/compensate.ts
@@ -0,0 +1,562 @@
+/**
+ * Print correction: nominal design + profile → the design to send to the printer.
+ *
+ * `compensateDesign` is the **only** place compensation is computed. The STL
+ * export, the OpenSCAD export and the read-only preview all call it and hand
+ * its result to the ordinary pipeline, so they cannot disagree about what a
+ * compensated chip looks like.
+ *
+ * It is pure: nothing here touches a store, and the nominal design passed in is
+ * never modified. The result is a second design, expressed almost entirely in
+ * the terms the pipeline already understands —
+ *
+ * - **lateral bleed** becomes wider dimension markers on a copy of the graph,
+ * and larger chamber and drainage-vent diameters;
+ * - **vertical cure-through** becomes one number, `ceilingRaiseMm`, which the
+ * pipeline applies to every roof while leaving floors where they were drawn.
+ *
+ * ## Assumptions, stated once
+ *
+ * 1. The chip is printed flat with its base (z = 0) on the build plate, so the
+ * layers that form a channel's roof are printed after the channel. Tilted or
+ * inverted prints put the cure-through on a different face.
+ * 2. The ceiling raise applies only to **roofed** channels, which means
+ * monolithic chips. A two-piece or glass-slide chip prints its channels as
+ * open grooves; there is no printed ceiling to cure downwards.
+ * 3. Lateral bleed is the same on both walls and in every direction in XY.
+ * 4. **Port and fitting geometry is left nominal.** A Luer taper is a fit to a
+ * standard part, and widening it from channel measurements would loosen the
+ * seal. Channels, corner joints, chambers and drainage vents are corrected.
+ * 5. The same coupon-derived lateral offset is used for open grooves as for
+ * enclosed channels, although the coupon measures enclosed ones.
+ * 6. Cross-sections keep their kind. A round channel is corrected as a larger
+ * circle, which also lowers its lowest point by the lateral offset; a
+ * trapezoid is widened at the top and keeps its draft ratio, so its floor
+ * widens by 0.7 of what the top does. Both err towards a slightly larger
+ * channel.
+ */
+
+import {
+ buildChains,
+ chainMarkers,
+ getLoft,
+ sizeAtDistance,
+ type Chain,
+ type ChainMarker,
+} from '../loft';
+import { ceilingZ, placeChannel } from '../cad/placement';
+import { withChannelPlane } from '../cad/slide';
+import { checkChannelSpacing } from '../validation/manufacturability';
+import {
+ DEFAULT_VALIDATION_SETTINGS,
+ type ValidationSettings,
+ type Warning,
+} from '../validation/types';
+import type {
+ ChannelEdge,
+ ChannelGraph,
+ ChipParams,
+ DimensionPoint,
+ DrainageVent,
+ Point2,
+ PrinterProfile,
+} from '../../types/project';
+import { bleedPerSideMm, drawnWidthForMm, type LateralModel } from './model';
+import type { DfmProfile } from './profile';
+
+// ---------------------------------------------------------------------------
+// types
+// ---------------------------------------------------------------------------
+
+/** Everything about a design that compensation reads. */
+export interface NominalDesign {
+ graph: ChannelGraph;
+ chipParams: ChipParams;
+ drainageVents: DrainageVent[];
+ printerProfile: PrinterProfile;
+}
+
+export type DfmConflictKind =
+ /** Two channels left with less wall between them than the printable minimum. */
+ | 'wall-too-thin'
+ /** Two channels that now touch or overlap. */
+ | 'channels-merge'
+ /** A channel pushed closer to the chip edge than the edge spacing allows. */
+ | 'edge-clearance'
+ /** A raised ceiling left with less material above it than the wall thickness. */
+ | 'ceiling-too-thin'
+ /** A raised ceiling that reaches the top face. */
+ | 'ceiling-breakthrough';
+
+export interface DfmConflict {
+ /** Stable for the same offending features, so a list keeps its order between runs. */
+ id: string;
+ kind: DfmConflictKind;
+ edgeIds: string[];
+ nodeIds: string[];
+ /** Where it is, in chip mm. */
+ focus?: Point2;
+ /** The measurement before compensation, when the nominal design already reported it. */
+ nominalMm: number | null;
+ /** The measurement after compensation, mm. Negative means overlap. */
+ compensatedMm: number;
+ /** What it has to be to pass, mm. */
+ limitMm: number;
+ /** `limitMm − compensatedMm`: how much is missing. */
+ shortfallMm: number;
+ /** One sentence naming the features and the numbers. */
+ message: string;
+}
+
+export interface AppliedCompensation {
+ /** Isolated-edge lateral offset per side, mm. */
+ deltaXyMm: number;
+ lateralDecayMm: number;
+ /** Ceiling raise actually applied, mm. Zero when the chip has no roofed channels. */
+ deltaZMm: number;
+ /** The profile's vertical offset, whether or not it was applied. */
+ profileDeltaZMm: number;
+ /** Why the ceiling raise was skipped, or null when it was applied. */
+ ceilingSkipped: string | null;
+ /** Smallest and largest total width increase across the channel markers, mm. */
+ widthIncreaseMm: { min: number; max: number };
+ /** Pixel size widths were snapped to, mm, or null when not snapped. */
+ snappedToPixelMm: number | null;
+}
+
+export interface CompensatedDesign {
+ graph: ChannelGraph;
+ chipParams: ChipParams;
+ drainageVents: DrainageVent[];
+ /** Hand to `buildChip` / `exportScad` as `ceilingRaiseMm`. */
+ ceilingRaiseMm: number;
+ applied: AppliedCompensation;
+ conflicts: DfmConflict[];
+}
+
+export interface CompensateOptions {
+ /** Thresholds for the conflict check. Defaults to the app's own. */
+ settings?: ValidationSettings;
+}
+
+// ---------------------------------------------------------------------------
+// lateral
+// ---------------------------------------------------------------------------
+
+/**
+ * Widest nominal step between two inserted markers on a taper, mm.
+ *
+ * The loft interpolates width linearly between markers. With λ > 0 the
+ * correction is not linear in width, so correcting only the user's own markers
+ * would leave the middle of a long taper slightly under-corrected. Extra
+ * markers every 0.05 mm of nominal width keep that under a micron.
+ */
+const TAPER_STEP_MM = 0.05;
+const MAX_TAPER_INSERTS = 24;
+
+/** Where a distance along a chain falls: which edge, and at what `t` on it. */
+function locateOnChain(chain: Chain, distanceMm: number): { edge: ChannelEdge; t: number } | null {
+ for (const member of chain.members) {
+ const end = member.startDistance + member.lengthMm;
+ if (distanceMm > end + 1e-9) continue;
+ const local =
+ member.lengthMm < 1e-9 ? 0 : (distanceMm - member.startDistance) / member.lengthMm;
+ const clamped = Math.min(1, Math.max(0, local));
+ return { edge: member.edge, t: member.reversed ? 1 - clamped : clamped };
+ }
+ return null;
+}
+
+function compensateGraph(
+ graph: ChannelGraph,
+ chipParams: ChipParams,
+ widen: (widthMm: number) => number,
+ nonLinear: boolean,
+): { graph: ChannelGraph; increase: { min: number; max: number } } {
+ const fallback = {
+ widthMm: chipParams.defaultChannelWidthMm,
+ heightMm: chipParams.defaultChannelHeightMm,
+ };
+ const points = new Map();
+ const increase = { min: Infinity, max: 0 };
+
+ const put = (edge: ChannelEdge, t: number, widthMm: number, heightMm: number | undefined) => {
+ const out = widen(widthMm);
+ increase.min = Math.min(increase.min, out - widthMm);
+ increase.max = Math.max(increase.max, out - widthMm);
+ const list = points.get(edge.id) ?? [];
+ list.push(heightMm === undefined ? { t, widthMm: out } : { t, widthMm: out, heightMm });
+ points.set(edge.id, list);
+ };
+
+ for (const chain of buildChains(graph)) {
+ const markers: ChainMarker[] = chainMarkers(chain);
+
+ if (markers.length === 0) {
+ // No markers means "the project default everywhere". The default itself
+ // is not touched — it belongs to the design — so the chain gets one
+ // explicit marker carrying the corrected default instead.
+ const first = chain.members[0];
+ if (first) {
+ put(
+ first.edge,
+ 0,
+ fallback.widthMm,
+ first.edge.crossSection === 'round' ? undefined : fallback.heightMm,
+ );
+ }
+ continue;
+ }
+
+ const byId = new Map(chain.members.map((m) => [m.edge.id, m.edge]));
+ for (let i = 0; i < markers.length; i += 1) {
+ const marker = markers[i];
+ const edge = byId.get(marker.edgeId);
+ if (edge) put(edge, marker.t, marker.widthMm, marker.heightMm);
+
+ const next = markers[i + 1];
+ if (!nonLinear || !next) continue;
+
+ const steps = Math.min(
+ MAX_TAPER_INSERTS,
+ Math.ceil(Math.abs(next.widthMm - marker.widthMm) / TAPER_STEP_MM),
+ );
+ for (let k = 1; k < steps; k += 1) {
+ const distanceMm = marker.distanceMm + ((next.distanceMm - marker.distanceMm) * k) / steps;
+ const at = locateOnChain(chain, distanceMm);
+ if (!at) continue;
+ const size = sizeAtDistance(markers, distanceMm, fallback);
+ put(at.edge, at.t, size.widthMm, size.heightMm);
+ }
+ }
+ }
+
+ const edges = graph.edges.map((edge) => {
+ const next = points.get(edge.id);
+ if (!next) return edge;
+ return { ...edge, dimensionPoints: next.sort((a, b) => a.t - b.t) };
+ });
+
+ // A chamber's wall bleeds like any other; ports are deliberately left alone.
+ const nodes = graph.nodes.map((node) =>
+ node.type === 'chamber' ? { ...node, sizeMm: widen(node.sizeMm) } : node,
+ );
+
+ if (increase.min === Infinity) increase.min = 0;
+ return { graph: { ...graph, nodes, edges }, increase };
+}
+
+// ---------------------------------------------------------------------------
+// conflicts
+// ---------------------------------------------------------------------------
+
+const mm = (value: number): string => String(Number(value.toFixed(3)));
+
+/**
+ * Thin-wall and merge conflicts, found with the design check itself.
+ *
+ * The same spacing check the Design checks panel runs is run on the nominal
+ * and on the compensated design. A conflict is a failing measurement that
+ * compensation created or made worse — a wall that was already too thin as
+ * drawn is the design's own warning, not something this transform did, unless
+ * it got thinner.
+ */
+function wallConflicts(
+ nominal: NominalDesign,
+ compensated: ChannelGraph,
+ settings: ValidationSettings,
+): DfmConflict[] {
+ const run = (graph: ChannelGraph): Warning[] =>
+ checkChannelSpacing({
+ graph,
+ chipParams: nominal.chipParams,
+ printerProfile: nominal.printerProfile,
+ settings,
+ });
+
+ const before = new Map(run(nominal.graph).map((w) => [w.id, w]));
+ const conflicts: DfmConflict[] = [];
+
+ for (const warning of run(compensated)) {
+ if (!warning.measurement) continue;
+ const { value, limit } = warning.measurement;
+ const nominalMm = before.get(warning.id)?.measurement?.value ?? null;
+ if (nominalMm !== null && value >= nominalMm - 1e-6) continue;
+
+ const [a, b] = warning.target.edgeIds;
+ const features = `segments ${a} and ${b}`;
+ const was = nominalMm === null ? '' : ` (was ${mm(nominalMm)} mm)`;
+ const merged = value < 0;
+
+ conflicts.push({
+ id: `dfm:${warning.id}`,
+ kind: merged ? 'channels-merge' : 'wall-too-thin',
+ edgeIds: warning.target.edgeIds,
+ nodeIds: [],
+ focus: warning.target.focus,
+ nominalMm,
+ compensatedMm: value,
+ limitMm: limit,
+ shortfallMm: limit - value,
+ message: merged
+ ? `Compensation makes ${features} overlap by ${mm(-value)} mm${was}, so they would print as one cavity.`
+ : `Compensation leaves ${mm(value)} mm of wall between ${features}${was}; ` +
+ `the minimum is ${mm(limit)} mm, so it is ${mm(limit - value)} mm short.`,
+ });
+ }
+
+ return conflicts;
+}
+
+/**
+ * Channels and chambers pushed closer to the chip edge than the edge spacing.
+ *
+ * Measured here rather than with the boundary design check, which sizes a
+ * plain waypoint from the project default width and so cannot see a channel
+ * that compensation widened. A feature that already ran off the chip as drawn
+ * is skipped: it is cut open by the edge either way, which on a calibration
+ * coupon is deliberate.
+ */
+function edgeConflicts(nominal: NominalDesign, compensated: ChannelGraph): DfmConflict[] {
+ const { chipParams } = nominal;
+ const limit = chipParams.minEdgeSpacing;
+ const clearance = (x: number, y: number, half: number): number =>
+ Math.min(x - half, chipParams.width - (x + half), y - half, chipParams.length - (y + half));
+
+ const conflicts: DfmConflict[] = [];
+ const report = (
+ id: string,
+ features: string,
+ target: Pick,
+ before: number,
+ after: number,
+ focus: Point2,
+ ) => {
+ if (before < 0 || after >= limit || after >= before - 1e-6) return;
+ conflicts.push({
+ id,
+ kind: 'edge-clearance',
+ ...target,
+ focus,
+ nominalMm: before,
+ compensatedMm: after,
+ limitMm: limit,
+ shortfallMm: limit - after,
+ message:
+ after < 0
+ ? `Compensation pushes ${features} ${mm(-after)} mm past the chip edge (was ${mm(before)} mm inside it).`
+ : `Compensation leaves ${features} ${mm(after)} mm from the chip edge (was ${mm(before)} mm); ` +
+ `the edge spacing is ${mm(limit)} mm, so it is ${mm(limit - after)} mm short.`,
+ });
+ };
+
+ const loftBefore = getLoft(nominal.graph, chipParams);
+ const loftAfter = getLoft(compensated, chipParams);
+ for (const edge of nominal.graph.edges) {
+ const worst = (samples: { point: Point2; widthMm: number }[] | undefined) => {
+ let value = Infinity;
+ let where: Point2 = { x: 0, y: 0 };
+ for (const sample of samples ?? []) {
+ const c = clearance(sample.point.x, sample.point.y, sample.widthMm / 2);
+ if (c < value) {
+ value = c;
+ where = sample.point;
+ }
+ }
+ return { value, where };
+ };
+ const before = worst(loftBefore.edges.get(edge.id)?.samples);
+ const after = worst(loftAfter.edges.get(edge.id)?.samples);
+ report(
+ `dfm:boundary-edge:${edge.id}`,
+ `segment ${edge.id}`,
+ { edgeIds: [edge.id], nodeIds: [] },
+ before.value,
+ after.value,
+ after.where,
+ );
+ }
+
+ const chambersAfter = new Map(compensated.nodes.map((n) => [n.id, n]));
+ for (const node of nominal.graph.nodes) {
+ const after = chambersAfter.get(node.id);
+ if (node.type !== 'chamber' || after?.type !== 'chamber') continue;
+ report(
+ `dfm:boundary:${node.id}`,
+ `chamber ${node.id}`,
+ { edgeIds: [], nodeIds: [node.id] },
+ clearance(node.x, node.y, node.sizeMm / 2),
+ clearance(node.x, node.y, after.sizeMm / 2),
+ { x: node.x, y: node.y },
+ );
+ }
+
+ return conflicts;
+}
+
+/** Material left above the highest ceiling, before and after the raise. */
+function ceilingConflicts(nominal: NominalDesign, ceilingRaiseMm: number): DfmConflict[] {
+ if (ceilingRaiseMm <= 0) return [];
+
+ const chipParams = withChannelPlane(nominal.chipParams);
+ const loft = getLoft(nominal.graph, chipParams);
+ const limit = chipParams.wallThickness;
+
+ // The thinnest roof among the segments compensation leaves too thin. A
+ // segment that already broke through the top face as drawn is skipped: that
+ // is the design's own problem, which the raise neither caused nor can worsen.
+ let worstNominal = Infinity;
+ let where: Point2 | undefined;
+ const edgeIds: string[] = [];
+
+ for (const edge of nominal.graph.edges) {
+ const solved = loft.edges.get(edge.id);
+ if (!solved) continue;
+
+ let edgeWorst = Infinity;
+ let edgeWhere: Point2 | undefined;
+ for (const sample of solved.samples) {
+ // The roof height does not depend on the lateral correction for a
+ // rectangular or trapezoidal channel, so the nominal loft serves both.
+ const roof = ceilingZ(
+ placeChannel(edge.crossSection, sample.widthMm, sample.heightMm, chipParams.splitHeight),
+ );
+ const skin = chipParams.baseThickness - roof;
+ if (skin < edgeWorst) {
+ edgeWorst = skin;
+ edgeWhere = sample.point;
+ }
+ }
+ if (edgeWorst <= 0 || edgeWorst - ceilingRaiseMm >= limit) continue;
+
+ edgeIds.push(edge.id);
+ if (edgeWorst < worstNominal) {
+ worstNominal = edgeWorst;
+ where = edgeWhere;
+ }
+ }
+
+ if (edgeIds.length === 0) return [];
+
+ const after = worstNominal - ceilingRaiseMm;
+ const through = after <= 0;
+ const count = `${edgeIds.length} segment${edgeIds.length === 1 ? '' : 's'}`;
+
+ return [
+ {
+ id: 'dfm:ceiling',
+ kind: through ? 'ceiling-breakthrough' : 'ceiling-too-thin',
+ edgeIds,
+ nodeIds: [],
+ focus: where,
+ nominalMm: worstNominal,
+ compensatedMm: after,
+ limitMm: limit,
+ shortfallMm: limit - after,
+ message: through
+ ? `Raising the ceilings by ${mm(ceilingRaiseMm)} mm breaks through the top face on ${count} ` +
+ `(the roof was ${mm(worstNominal)} mm thick). Make the chip thicker or lower the split height.`
+ : `Raising the ceilings by ${mm(ceilingRaiseMm)} mm leaves a ${mm(after)} mm roof over ${count} ` +
+ `(was ${mm(worstNominal)} mm); the wall thickness is ${mm(limit)} mm, so it is ${mm(limit - after)} mm short.`,
+ },
+ ];
+}
+
+// ---------------------------------------------------------------------------
+// the transform
+// ---------------------------------------------------------------------------
+
+export function compensateDesign(
+ nominal: NominalDesign,
+ profile: DfmProfile,
+ options: CompensateOptions = {},
+): CompensatedDesign {
+ const settings = options.settings ?? DEFAULT_VALIDATION_SETTINGS;
+ const { compensation, meta } = profile;
+
+ const model: LateralModel = {
+ deltaXyMm: Math.max(0, compensation.deltaXyMm),
+ lateralDecayMm: Math.max(0, compensation.lateralDecayMm),
+ };
+ const lateral = model.deltaXyMm > 0 || model.lateralDecayMm > 0;
+
+ // Only the size is snapped. Where a channel lands on the pixel grid is
+ // decided by where the slicer puts the part on the plate, which is not known
+ // here; a width that is a whole number of pixels at least can be aligned.
+ const pixelMm =
+ compensation.snapToPixelGrid && meta.xyPixelMicrons ? meta.xyPixelMicrons / 1000 : null;
+
+ const widen = (widthMm: number): number => {
+ if (!lateral) return widthMm;
+ const drawn = drawnWidthForMm(widthMm, model);
+ if (!pixelMm) return drawn;
+ // Never snap below the nominal width: rounding a correction away entirely
+ // would leave the channel narrower than an uncompensated export.
+ return Math.max(widthMm, Math.round(drawn / pixelMm) * pixelMm);
+ };
+
+ const roofed = nominal.chipParams.splitType === 'monolithic';
+ const profileDeltaZMm = Math.max(0, compensation.deltaZMm);
+ const ceilingRaiseMm = roofed ? profileDeltaZMm : 0;
+ const ceilingSkipped =
+ roofed || profileDeltaZMm === 0
+ ? null
+ : nominal.chipParams.splitType === 'glass-slide'
+ ? 'The channels are open grooves closed by the glass slide, so there is no printed ceiling to correct.'
+ : 'A two-piece chip prints its channels as open grooves, so there is no printed ceiling to correct.';
+
+ const appliedBase = {
+ deltaXyMm: model.deltaXyMm,
+ lateralDecayMm: model.lateralDecayMm,
+ deltaZMm: ceilingRaiseMm,
+ profileDeltaZMm,
+ ceilingSkipped,
+ snappedToPixelMm: lateral ? pixelMm : null,
+ };
+
+ // A profile that changes nothing returns the design it was given, by
+ // identity — the cheapest possible proof that a null correction is a no-op.
+ if (!lateral && ceilingRaiseMm === 0) {
+ return {
+ graph: nominal.graph,
+ chipParams: nominal.chipParams,
+ drainageVents: nominal.drainageVents,
+ ceilingRaiseMm: 0,
+ applied: { ...appliedBase, widthIncreaseMm: { min: 0, max: 0 } },
+ conflicts: [],
+ };
+ }
+
+ const widened = lateral
+ ? compensateGraph(nominal.graph, nominal.chipParams, widen, model.lateralDecayMm > 0)
+ : { graph: nominal.graph, increase: { min: 0, max: 0 } };
+
+ const drainageVents = lateral
+ ? nominal.drainageVents.map((vent) => ({ ...vent, diameterMm: widen(vent.diameterMm) }))
+ : nominal.drainageVents;
+
+ const conflicts = [
+ ...(lateral ? wallConflicts(nominal, widened.graph, settings) : []),
+ ...(lateral ? edgeConflicts(nominal, widened.graph) : []),
+ ...ceilingConflicts(nominal, ceilingRaiseMm),
+ ].sort((a, b) => b.shortfallMm - a.shortfallMm);
+
+ return {
+ graph: widened.graph,
+ chipParams: nominal.chipParams,
+ drainageVents,
+ ceilingRaiseMm,
+ applied: { ...appliedBase, widthIncreaseMm: widened.increase },
+ conflicts,
+ };
+}
+
+/** Per-side lateral offset the profile applies at a given nominal width, mm. */
+export function lateralOffsetAtMm(nominalWidthMm: number, profile: DfmProfile): number {
+ const model: LateralModel = {
+ deltaXyMm: Math.max(0, profile.compensation.deltaXyMm),
+ lateralDecayMm: Math.max(0, profile.compensation.lateralDecayMm),
+ };
+ const drawn = drawnWidthForMm(nominalWidthMm, model);
+ return bleedPerSideMm(drawn, model);
+}
diff --git a/src/lib/dfm/coupon.test.ts b/src/lib/dfm/coupon.test.ts
new file mode 100644
index 0000000..8f0fd2c
--- /dev/null
+++ b/src/lib/dfm/coupon.test.ts
@@ -0,0 +1,257 @@
+/**
+ * Calibration coupon tests: it is a valid project, it builds, every channel is
+ * open at both ends, and its measurement sheet reads back.
+ */
+
+import assert from 'node:assert/strict';
+import { beforeAll, describe, it } from 'vitest';
+import Module from 'manifold-3d';
+import { buildChip, type ManifoldApi } from '../cad/buildChip';
+import { exportScad } from '../cad/scadExport';
+import { exportStl, stlTriangleCount } from '../cad/stlExport';
+import { FALLBACK_PRINTER_PROFILE, PRINTER_PRESETS } from '../defaults';
+import { parseProject, serializeProject } from '../projectFile';
+import { runValidation } from '../validation';
+import { compensateDesign } from './compensate';
+import {
+ COUPON_VERSION,
+ blankMeasurements,
+ buildCouponProject,
+ couponLayout,
+ defaultCouponSpec,
+ measurementSheetCsv,
+ parseMeasurementSheet,
+} from './coupon';
+import { makeProfile } from './testFixtures';
+
+let api: ManifoldApi;
+
+beforeAll(async () => {
+ const raw = await Module();
+ raw.setup();
+ api = { Manifold: raw.Manifold, Mesh: raw.Mesh } as unknown as ManifoldApi;
+}, 60_000);
+
+const spec = defaultCouponSpec(FALLBACK_PRINTER_PROFILE);
+
+describe('the default coupon', () => {
+ it('spans sizes below and above the printer minimum feature', () => {
+ const feature = FALLBACK_PRINTER_PROFILE.minFeatureSizeMm;
+ assert.ok(Math.min(...spec.widthsMm) < feature, 'something should be expected to close');
+ assert.ok(Math.max(...spec.widthsMm) >= feature * 2.5, 'something should be expected to stay open');
+ assert.ok(Math.min(...spec.heightsMm) < feature);
+ assert.ok(Math.max(...spec.heightsMm) >= feature * 2);
+ assert.equal(spec.version, COUPON_VERSION);
+ });
+
+ it('uses heights the printer can actually stack', () => {
+ const layerMm = FALLBACK_PRINTER_PROFILE.layerHeightMicrons / 1000;
+ for (const height of spec.heightsMm) {
+ assert.ok(Math.abs(height / layerMm - Math.round(height / layerMm)) < 1e-6, `${height}`);
+ }
+ });
+
+ it('fits every printer preset the app ships', () => {
+ for (const preset of PRINTER_PRESETS) {
+ const { chip } = couponLayout(defaultCouponSpec(preset.profile));
+ const volume = preset.profile.buildVolumeMm;
+ assert.ok(chip.width <= volume.x && chip.length <= volume.y, `${preset.id}: ${chip.length} mm`);
+ }
+ });
+
+ it('has one channel per width × height, labelled group.index', () => {
+ const layout = couponLayout(spec);
+ assert.equal(layout.channels.length, spec.widthsMm.length * spec.heightsMm.length);
+ assert.equal(new Set(layout.channels.map((c) => c.id)).size, layout.channels.length);
+
+ const first = layout.channels[0];
+ assert.equal(first.id, '1.1');
+ assert.equal(first.widthMm, Math.max(...spec.widthsMm), 'channel 1 is the widest');
+ assert.equal(first.heightMm, Math.min(...spec.heightsMm), 'group 1 is the lowest');
+ });
+
+ it('labels each group with that many tally dots', () => {
+ const layout = couponLayout(spec);
+ spec.heightsMm.forEach((_, g) => {
+ assert.equal(layout.dots.filter((d) => d.group === g + 1).length, g + 1);
+ });
+ });
+
+ it('keeps a full gap of solid material between neighbours', () => {
+ const layout = couponLayout(spec);
+ const spans = [
+ ...layout.channels.map((c) => ({ lo: c.yMm - c.widthMm / 2, hi: c.yMm + c.widthMm / 2 })),
+ ...layout.dots.map((d) => ({ lo: d.y - spec.dotDiameterMm / 2, hi: d.y + spec.dotDiameterMm / 2 })),
+ ].sort((a, b) => a.lo - b.lo);
+ for (let i = 1; i < spans.length; i += 1) {
+ const gap = spans[i].lo - spans[i - 1].hi;
+ // Dots of one group share a row, so they overlap in y; everything else
+ // is a gap apart.
+ assert.ok(gap >= spec.gapMm - 1e-6 || gap < 0, `gap ${gap}`);
+ }
+ });
+});
+
+describe('the coupon as a project', () => {
+ const { project, layout } = buildCouponProject(spec, FALLBACK_PRINTER_PROFILE);
+
+ it('is a valid .openchip file that round-trips', () => {
+ const parsed = parseProject(serializeProject(project));
+ assert.equal(parsed.ok, true, parsed.ok ? '' : parsed.details.join(' '));
+ if (!parsed.ok) return;
+ assert.deepEqual(parsed.project, project);
+ assert.deepEqual(parsed.warnings, []);
+ });
+
+ it('is monolithic, so its channels have printed ceilings', () => {
+ assert.equal(project.chipParams.splitType, 'monolithic');
+ assert.ok(project.chipParams.baseThickness > project.chipParams.splitHeight);
+ });
+
+ it('goes through the design checks without throwing, and they cannot block it', () => {
+ const result = runValidation({
+ graph: project.channelGraph,
+ chipParams: project.chipParams,
+ printerProfile: project.printerProfile,
+ drainageVents: project.drainageVents,
+ });
+ assert.deepEqual(Object.keys(result).sort(), ['counts', 'warnings']);
+ });
+
+ it('builds one non-empty solid through the normal pipeline', () => {
+ const built = buildChip(api, project.channelGraph, project.chipParams, {
+ quality: 2,
+ drainageVents: project.drainageVents,
+ });
+ assert.deepEqual(built.warnings, []);
+ assert.deepEqual(built.pieces.map((p) => p.id), ['solid']);
+ assert.equal(built.stats.ventCount, layout.dots.length);
+
+ const stl = exportStl(built.pieces, 'coupon');
+ assert.ok(stlTriangleCount(stl) > 100);
+ });
+
+ it('opens every channel at both ends', () => {
+ const built = buildChip(api, project.channelGraph, project.chipParams, {
+ quality: 2,
+ drainageVents: project.drainageVents,
+ });
+ const { positions } = built.pieces[0];
+ const { width, splitHeight } = layout.chip;
+
+ // A channel cut clean through the side wall leaves its rectangular mouth
+ // in that wall: four mesh vertices on the face, at the channel's corners.
+ const hasVertex = (x: number, y: number, z: number) => {
+ for (let i = 0; i < positions.length; i += 3) {
+ if (
+ Math.abs(positions[i] - x) < 1e-4 &&
+ Math.abs(positions[i + 1] - y) < 1e-4 &&
+ Math.abs(positions[i + 2] - z) < 1e-4
+ ) {
+ return true;
+ }
+ }
+ return false;
+ };
+
+ for (const channel of layout.channels) {
+ for (const x of [0, width]) {
+ for (const y of [channel.yMm - channel.widthMm / 2, channel.yMm + channel.widthMm / 2]) {
+ for (const z of [splitHeight, splitHeight - channel.heightMm]) {
+ assert.ok(hasVertex(x, y, z), `channel ${channel.id} mouth corner at x=${x}`);
+ }
+ }
+ }
+ }
+
+ // And the material removed is exactly a through-prism per channel, plus
+ // the dots: nothing is left as a skin over a mouth.
+ const block = width * layout.chip.length * layout.chip.baseThickness;
+ const channels = layout.channels.reduce((sum, c) => sum + c.widthMm * c.heightMm * width, 0);
+ const removed = block - built.stats.chipVolumeMm3;
+ const dotCeiling =
+ layout.dots.length * Math.PI * (spec.dotDiameterMm / 2) ** 2 * (spec.roofMm + 0.01);
+ assert.ok(removed > channels + dotCeiling * 0.9, `removed ${removed}, channels ${channels}`);
+ assert.ok(removed < channels + dotCeiling * 1.001, `removed ${removed}, channels ${channels}`);
+ });
+
+ it('gives the tally dots as blind holes that stop at the channel plane', () => {
+ const built = buildChip(api, project.channelGraph, project.chipParams, {
+ includeChannelSolid: true,
+ drainageVents: project.drainageVents,
+ });
+ const z = Array.from(built.channelSolid?.positions ?? []).filter((_, i) => i % 3 === 2);
+ // Nothing in the cavity goes below the deepest channel floor.
+ assert.ok(Math.min(...z) >= spec.floorMm - 1e-4);
+ });
+
+ it('exports as OpenSCAD too', () => {
+ const scad = exportScad(project.channelGraph, project.chipParams, {
+ drainageVents: project.drainageVents,
+ });
+ assert.equal((scad.match(/{/g) ?? []).length, (scad.match(/}/g) ?? []).length);
+ });
+
+ it('can itself be compensated without its open ends counting as conflicts', () => {
+ const out = compensateDesign(
+ {
+ graph: project.channelGraph,
+ chipParams: project.chipParams,
+ drainageVents: project.drainageVents,
+ printerProfile: project.printerProfile,
+ },
+ makeProfile({ deltaXyMm: 0.03, deltaZMm: 0.05 }),
+ );
+ assert.deepEqual(out.conflicts.filter((c) => c.kind === 'edge-clearance'), []);
+ });
+});
+
+describe('the measurement sheet', () => {
+ const layout = couponLayout(spec);
+
+ it('lists every channel with its nominal size and blank results', () => {
+ const csv = measurementSheetCsv(blankMeasurements(layout));
+ const lines = csv.trim().split('\n');
+ assert.equal(lines.length, layout.channels.length + 1);
+ assert.match(lines[0], /^channel,group_dots,position_in_group,nominal_width_mm/);
+ const first = layout.channels[0];
+ assert.equal(lines[1], `1.1,1,1,${first.widthMm},${first.heightMm},,,`);
+ });
+
+ it('reads a filled-in sheet back', () => {
+ const filled = blankMeasurements(layout);
+ filled[0] = { ...filled[0], result: 'open', measuredWidthMm: 0.52, measuredHeightMm: 0.07 };
+ filled[1] = { ...filled[1], result: 'closed' };
+ const parsed = parseMeasurementSheet(measurementSheetCsv(filled));
+ assert.equal(parsed.ok, true);
+ if (!parsed.ok) return;
+ assert.deepEqual(parsed.measurements, filled);
+ });
+
+ it('accepts what a spreadsheet does to a CSV', () => {
+ const csv =
+ 'Channel;group_dots;position_in_group;nominal_width_mm;nominal_height_mm;result_open_partial_closed;measured_width_mm;measured_height_mm\r\n' +
+ '"1.1";1;1;0.6;0.1;Open;0,52;\r\n' +
+ '1.2;1;2;0.4;0.1;P;;\r\n';
+ const parsed = parseMeasurementSheet(csv);
+ assert.equal(parsed.ok, true, parsed.ok ? '' : parsed.details.join(' '));
+ if (!parsed.ok) return;
+ assert.deepEqual(parsed.measurements, [
+ { id: '1.1', nominalWidthMm: 0.6, nominalHeightMm: 0.1, result: 'open', measuredWidthMm: 0.52 },
+ { id: '1.2', nominalWidthMm: 0.4, nominalHeightMm: 0.1, result: 'partial' },
+ ]);
+ });
+
+ it('names the row it could not read, and imports nothing', () => {
+ const csv = `${measurementSheetCsv(blankMeasurements(layout)).trim()}\n9.9,9,9,0.3,0.3,sort of,,\n`;
+ const parsed = parseMeasurementSheet(csv);
+ assert.equal(parsed.ok, false);
+ if (parsed.ok) return;
+ assert.ok(parsed.details.some((d) => /Row \d+: result "sort of"/.test(d)));
+ });
+
+ it('rejects a file that is not a sheet', () => {
+ const parsed = parseMeasurementSheet('a,b\n1,2\n');
+ assert.equal(parsed.ok, false);
+ });
+});
diff --git a/src/lib/dfm/coupon.ts b/src/lib/dfm/coupon.ts
new file mode 100644
index 0000000..f489e49
--- /dev/null
+++ b/src/lib/dfm/coupon.ts
@@ -0,0 +1,409 @@
+/**
+ * The calibration coupon, and the sheet its results are written on.
+ *
+ * The coupon is an ordinary OpenChip project. It is built from the same nodes,
+ * segments and drainage vents as any other design and goes through the same
+ * pipeline to an STL, so what it measures is the app's real output rather than
+ * a special case of it.
+ *
+ * ## Layout
+ *
+ * A narrow monolithic strip crossed by straight rectangular channels, one per
+ * width × height combination. Monolithic, because the vertical correction is
+ * about printed ceilings and only an enclosed channel has one.
+ *
+ * - Every channel runs past both long edges of the strip, so it is open at
+ * both ends: it can be flushed through, and held up to a light it either
+ * shows through or does not. The Design checks panel reports these channels
+ * as running outside the chip. On the coupon that is the point.
+ * - Channels are grouped by height. Each group starts with a row of **tally
+ * dots** — blind holes in the top face, one for group 1, two for group 2 —
+ * which is the printed label. OpenChip has no text primitive, and a counted
+ * dot survives a resolution at which an engraved digit would not.
+ * - Within a group, channel 1 is nearest the dots and is the widest; they
+ * narrow going away from the dots. A channel's id is `group.index`.
+ *
+ * The widths and heights default to a spread around the printer profile's
+ * minimum feature size — from well below it, where channels are expected to
+ * close, to several times it, where they should not — because the fit needs
+ * both outcomes to bracket the threshold.
+ */
+
+import { createProject } from '../defaults';
+import type {
+ ChannelEdge,
+ ChannelNode,
+ DrainageVent,
+ OpenChipProject,
+ PrinterProfile,
+} from '../../types/project';
+import type { ChannelResult, CouponMeasurement } from './profile';
+
+/** Bumped when the layout changes in a way that changes what is measured. */
+export const COUPON_VERSION = 1;
+
+export interface CouponSpec {
+ version: number;
+ /** Channel widths, mm. Any order; laid out widest first. */
+ widthsMm: number[];
+ /** Channel heights, mm. One group per height, lowest first. */
+ heightsMm: number[];
+ /** Length of each channel, which is the width of the strip, mm. */
+ channelLengthMm: number;
+ /** Solid material between neighbouring channels, mm. */
+ gapMm: number;
+ /** Solid material under the deepest channel, mm. */
+ floorMm: number;
+ /** Solid material over every channel, mm. */
+ roofMm: number;
+ /** Diameter of a tally dot, mm. */
+ dotDiameterMm: number;
+}
+
+/** How far each channel runs past the strip's edge, so the end is cut clean open. */
+const OVERSHOOT_MM = 0.5;
+const MAX_GROUPS = 6;
+
+const roundTo = (value: number, step: number): number =>
+ Number((Math.round(value / step) * step).toFixed(4));
+
+const distinctSorted = (values: number[]): number[] =>
+ [...new Set(values.filter((v) => Number.isFinite(v) && v > 0).map((v) => Number(v.toFixed(4))))].sort(
+ (a, b) => a - b,
+ );
+
+/** A coupon spread around what this printer claims it can resolve. */
+export function defaultCouponSpec(printer: PrinterProfile): CouponSpec {
+ const feature = printer.minFeatureSizeMm;
+ const layerMm = printer.layerHeightMicrons / 1000;
+
+ // Widths on a 0.05 mm grid: fine enough to bracket a threshold, coarse
+ // enough that neighbouring channels are meaningfully different on a desktop
+ // printer.
+ const widthsMm = distinctSorted(
+ [0.5, 0.75, 1, 1.25, 1.5, 2, 3].map((k) => Math.max(0.1, roundTo(k * feature, 0.05))),
+ );
+ // Heights in whole layers, since no other height can be printed.
+ const heightsMm = distinctSorted(
+ [0.5, 1, 1.5, 2.5].map((k) => Math.max(layerMm * 2, roundTo(k * feature, layerMm))),
+ );
+
+ return {
+ version: COUPON_VERSION,
+ widthsMm,
+ heightsMm,
+ channelLengthMm: 14,
+ gapMm: 1,
+ floorMm: 1,
+ roofMm: 1.5,
+ dotDiameterMm: Math.max(0.8, roundTo(feature * 2.5, 0.1)),
+ };
+}
+
+/** A spec with its lists cleaned up, so hand-edited values cannot break the layout. */
+export function normaliseCouponSpec(spec: CouponSpec): CouponSpec {
+ return {
+ ...spec,
+ version: COUPON_VERSION,
+ widthsMm: distinctSorted(spec.widthsMm),
+ heightsMm: distinctSorted(spec.heightsMm).slice(0, MAX_GROUPS),
+ channelLengthMm: Math.max(4, spec.channelLengthMm),
+ gapMm: Math.max(0.2, spec.gapMm),
+ floorMm: Math.max(0.2, spec.floorMm),
+ roofMm: Math.max(0.2, spec.roofMm),
+ dotDiameterMm: Math.max(0.2, spec.dotDiameterMm),
+ };
+}
+
+// ---------------------------------------------------------------------------
+// layout
+// ---------------------------------------------------------------------------
+
+export interface CouponChannel {
+ /** `group.index`. */
+ id: string;
+ group: number;
+ index: number;
+ widthMm: number;
+ heightMm: number;
+ /** Centreline position along the strip, mm from the y = 0 end. */
+ yMm: number;
+ edgeId: string;
+}
+
+export interface CouponLayout {
+ spec: CouponSpec;
+ channels: CouponChannel[];
+ /** Tally dots: centre position and which group they label. */
+ dots: { group: number; x: number; y: number; nodeId: string }[];
+ /** Strip footprint and thickness, mm. */
+ chip: { width: number; length: number; baseThickness: number; splitHeight: number };
+}
+
+export function couponLayout(input: CouponSpec): CouponLayout {
+ const spec = normaliseCouponSpec(input);
+ const widest = [...spec.widthsMm].sort((a, b) => b - a);
+ const dotPitch = spec.dotDiameterMm + 0.8;
+
+ const channels: CouponChannel[] = [];
+ const dots: CouponLayout['dots'] = [];
+ let y = spec.gapMm;
+
+ spec.heightsMm.forEach((heightMm, g) => {
+ const group = g + 1;
+
+ // The label row. Dots start from the x = 0 end, which also tells the two
+ // ends of the strip apart.
+ y += spec.dotDiameterMm / 2;
+ for (let d = 0; d < group; d += 1) {
+ dots.push({
+ group,
+ x: 2 + d * dotPitch,
+ y,
+ nodeId: `coupon-g${group}-dot${d + 1}`,
+ });
+ }
+ y += spec.dotDiameterMm / 2 + spec.gapMm;
+
+ widest.forEach((widthMm, i) => {
+ const index = i + 1;
+ y += widthMm / 2;
+ channels.push({
+ id: `${group}.${index}`,
+ group,
+ index,
+ widthMm,
+ heightMm,
+ yMm: Number(y.toFixed(4)),
+ edgeId: `coupon-g${group}-c${index}`,
+ });
+ y += widthMm / 2 + spec.gapMm;
+ });
+ });
+
+ const tallest = spec.heightsMm.length > 0 ? Math.max(...spec.heightsMm) : 0;
+ const splitHeight = Number((spec.floorMm + tallest).toFixed(4));
+
+ return {
+ spec,
+ channels,
+ dots,
+ chip: {
+ width: spec.channelLengthMm,
+ length: Number(Math.max(y, 4).toFixed(2)),
+ baseThickness: Number((splitHeight + spec.roofMm).toFixed(4)),
+ splitHeight,
+ },
+ };
+}
+
+// ---------------------------------------------------------------------------
+// the project
+// ---------------------------------------------------------------------------
+
+/** The coupon as a project, ready to save as `.openchip` or open in the editor. */
+export function buildCouponProject(
+ input: CouponSpec,
+ printerProfile: PrinterProfile,
+): { project: OpenChipProject; layout: CouponLayout } {
+ const layout = couponLayout(input);
+ const { spec, chip } = layout;
+
+ const nodes: ChannelNode[] = [];
+ const edges: ChannelEdge[] = [];
+
+ for (const channel of layout.channels) {
+ const from = `${channel.edgeId}-a`;
+ const to = `${channel.edgeId}-b`;
+ nodes.push({ id: from, x: -OVERSHOOT_MM, y: channel.yMm, type: 'waypoint' });
+ nodes.push({ id: to, x: chip.width + OVERSHOOT_MM, y: channel.yMm, type: 'waypoint' });
+ edges.push({
+ id: channel.edgeId,
+ fromNodeId: from,
+ toNodeId: to,
+ curveType: 'straight',
+ crossSection: 'rect',
+ dimensionPoints: [{ t: 0, widthMm: channel.widthMm, heightMm: channel.heightMm }],
+ });
+ }
+
+ // A tally dot is a drainage vent on a node with no channel under it: the
+ // pipeline bores it from the top face down to the channel plane, which on a
+ // bare node is simply a blind hole.
+ const drainageVents: DrainageVent[] = [];
+ for (const dot of layout.dots) {
+ nodes.push({ id: dot.nodeId, x: dot.x, y: dot.y, type: 'waypoint' });
+ drainageVents.push({
+ id: `${dot.nodeId}-vent`,
+ nodeId: dot.nodeId,
+ diameterMm: spec.dotDiameterMm,
+ autoPlaced: false,
+ });
+ }
+
+ const project = createProject({
+ name: `DFM calibration coupon v${COUPON_VERSION}`,
+ printerProfile,
+ chipParams: {
+ width: chip.width,
+ length: chip.length,
+ baseThickness: chip.baseThickness,
+ splitType: 'monolithic',
+ splitHeight: chip.splitHeight,
+ wallThickness: Math.min(spec.gapMm, spec.roofMm),
+ minEdgeSpacing: 0,
+ defaultCrossSection: 'rect',
+ defaultChannelWidthMm: spec.widthsMm[spec.widthsMm.length - 1] ?? 0.8,
+ defaultChannelHeightMm: spec.heightsMm[spec.heightsMm.length - 1] ?? 0.5,
+ },
+ channelGraph: { nodes, edges },
+ });
+
+ return { project: { ...project, drainageVents }, layout };
+}
+
+/** One blank measurement per coupon channel, in sheet order. */
+export function blankMeasurements(layout: CouponLayout): CouponMeasurement[] {
+ return layout.channels.map((channel) => ({
+ id: channel.id,
+ nominalWidthMm: channel.widthMm,
+ nominalHeightMm: channel.heightMm,
+ result: null,
+ }));
+}
+
+// ---------------------------------------------------------------------------
+// the measurement sheet
+// ---------------------------------------------------------------------------
+
+const SHEET_COLUMNS = [
+ 'channel',
+ 'group_dots',
+ 'position_in_group',
+ 'nominal_width_mm',
+ 'nominal_height_mm',
+ 'result_open_partial_closed',
+ 'measured_width_mm',
+ 'measured_height_mm',
+] as const;
+
+/**
+ * The sheet as CSV: one row per channel, blank where the user writes.
+ *
+ * CSV because it prints from any spreadsheet, can be filled in on a laptop at
+ * the bench, and reads straight back in with `parseMeasurementSheet`.
+ */
+export function measurementSheetCsv(measurements: CouponMeasurement[]): string {
+ const rows = measurements.map((m) => {
+ const [group = '', index = ''] = m.id.split('.');
+ return [
+ m.id,
+ group,
+ index,
+ m.nominalWidthMm,
+ m.nominalHeightMm,
+ m.result ?? '',
+ m.measuredWidthMm ?? '',
+ m.measuredHeightMm ?? '',
+ ].join(',');
+ });
+ return `${[SHEET_COLUMNS.join(','), ...rows].join('\n')}\n`;
+}
+
+export type SheetParseResult =
+ | { ok: true; measurements: CouponMeasurement[] }
+ | { ok: false; message: string; details: string[] };
+
+const RESULT_WORDS: Record = {
+ open: 'open',
+ o: 'open',
+ partial: 'partial',
+ 'partially open': 'partial',
+ p: 'partial',
+ closed: 'closed',
+ c: 'closed',
+ blocked: 'closed',
+};
+
+/** Reads a filled-in sheet back. Tolerant of quoting, semicolons and blank cells. */
+export function parseMeasurementSheet(text: string): SheetParseResult {
+ const lines = text.split(/\r?\n/).filter((line) => line.trim().length > 0);
+ if (lines.length < 2) {
+ return { ok: false, message: 'That sheet has no channel rows.', details: [] };
+ }
+
+ const separator = lines[0].includes(';') && !lines[0].includes(',') ? ';' : ',';
+ const cells = (line: string) =>
+ line.split(separator).map((cell) => cell.trim().replace(/^"|"$/g, '').trim());
+
+ const header = cells(lines[0]).map((h) => h.toLowerCase());
+ const column = (name: string) => header.indexOf(name);
+ const at = {
+ id: column('channel'),
+ width: column('nominal_width_mm'),
+ height: column('nominal_height_mm'),
+ result: column('result_open_partial_closed'),
+ measuredWidth: column('measured_width_mm'),
+ measuredHeight: column('measured_height_mm'),
+ };
+
+ if (at.id < 0 || at.width < 0 || at.height < 0) {
+ return {
+ ok: false,
+ message: "That file isn't an OpenChip measurement sheet.",
+ details: ['It needs the columns channel, nominal_width_mm and nominal_height_mm.'],
+ };
+ }
+
+ const measurements: CouponMeasurement[] = [];
+ const problems: string[] = [];
+ const optional = (row: string[], index: number, label: string, line: number) => {
+ const raw = index >= 0 ? (row[index] ?? '') : '';
+ if (raw === '') return undefined;
+ const value = Number(raw.replace(',', '.'));
+ if (!Number.isFinite(value) || value < 0) {
+ problems.push(`Row ${line}: ${label} "${raw}" is not a number.`);
+ return undefined;
+ }
+ return value;
+ };
+
+ lines.slice(1).forEach((line, i) => {
+ const row = cells(line);
+ const lineNo = i + 2;
+ const id = row[at.id] ?? '';
+ const width = Number(row[at.width]);
+ const height = Number(row[at.height]);
+ if (!id || !(width > 0) || !(height > 0)) {
+ problems.push(`Row ${lineNo}: the channel id or its nominal size is missing.`);
+ return;
+ }
+
+ const word = (at.result >= 0 ? (row[at.result] ?? '') : '').toLowerCase();
+ const result = word === '' ? null : (RESULT_WORDS[word] ?? undefined);
+ if (result === undefined) {
+ problems.push(`Row ${lineNo}: result "${word}" should be open, partial or closed.`);
+ return;
+ }
+
+ const measuredWidthMm = optional(row, at.measuredWidth, 'measured width', lineNo);
+ const measuredHeightMm = optional(row, at.measuredHeight, 'measured height', lineNo);
+ measurements.push({
+ id,
+ nominalWidthMm: width,
+ nominalHeightMm: height,
+ result,
+ ...(measuredWidthMm === undefined ? {} : { measuredWidthMm }),
+ ...(measuredHeightMm === undefined ? {} : { measuredHeightMm }),
+ });
+ });
+
+ if (problems.length > 0) {
+ return {
+ ok: false,
+ message: "That sheet has rows that couldn't be read, so nothing was imported.",
+ details: problems.slice(0, 6),
+ };
+ }
+ return { ok: true, measurements };
+}
diff --git a/src/lib/dfm/exportPlan.test.ts b/src/lib/dfm/exportPlan.test.ts
new file mode 100644
index 0000000..cf9ebad
--- /dev/null
+++ b/src/lib/dfm/exportPlan.test.ts
@@ -0,0 +1,154 @@
+/**
+ * Export plan and project-reference tests: an uncompensated export is the
+ * nominal design by identity, a compensated one is named so it cannot be
+ * mistaken for it, and the optional reference in a `.openchip` file changes
+ * nothing for files that do not carry it.
+ */
+
+import assert from 'node:assert/strict';
+import { readFileSync, readdirSync } from 'node:fs';
+import { join } from 'node:path';
+import { describe, it } from 'vitest';
+import { exportStl } from '../cad/stlExport';
+import { createProject } from '../defaults';
+import { parseProject, serializeProject } from '../projectFile';
+import { compensateDesign } from './compensate';
+import { planExport } from './exportPlan';
+import { hashDfmProfile } from './profile';
+import { design, makeProfile, parallelChannels } from './testFixtures';
+
+const nominal = design(parallelChannels(3), { splitType: 'monolithic' });
+
+describe('an export with no profile', () => {
+ it('is the nominal design, by identity', () => {
+ const plan = planExport(nominal, 'My chip', null);
+ assert.equal(plan.graph, nominal.graph);
+ assert.equal(plan.chipParams, nominal.chipParams);
+ assert.equal(plan.drainageVents, nominal.drainageVents);
+ assert.equal(plan.ceilingRaiseMm, 0);
+ assert.equal(plan.compensated, null);
+ });
+
+ it('keeps the file name and header the app has always written', () => {
+ const plan = planExport(nominal, 'My chip', null);
+ assert.equal(plan.fileSuffix, '');
+ assert.equal(plan.stlHeader, 'OpenChip My chip');
+ assert.deepEqual(plan.scadNotes, []);
+ });
+});
+
+describe('an export with a profile', () => {
+ const profile = makeProfile();
+
+ it('carries exactly what compensateDesign returns', async () => {
+ const entry = { profile, sha256: await hashDfmProfile(profile) };
+ const plan = planExport(nominal, 'My chip', entry);
+ const direct = compensateDesign(nominal, profile);
+ assert.deepEqual(plan.graph, direct.graph);
+ assert.equal(plan.ceilingRaiseMm, direct.ceilingRaiseMm);
+ assert.deepEqual(plan.compensated, direct);
+ });
+
+ it('gets a file suffix naming the profile', async () => {
+ const entry = { profile, sha256: await hashDfmProfile(profile) };
+ assert.equal(planExport(nominal, 'My chip', entry).fileSuffix, '-dfm-bench-printer-clear-resin');
+ });
+
+ it('records the profile name and hash in the STL header, inside 80 bytes', async () => {
+ const sha256 = await hashDfmProfile(profile);
+ const plan = planExport(nominal, 'A project with a very long name that would overflow the header', {
+ profile,
+ sha256,
+ });
+ assert.ok(plan.stlHeader.startsWith(`OpenChip DFM ${sha256.slice(0, 12)} Bench printer, clear resin`));
+
+ const mesh = { positions: new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0]), indices: new Uint32Array([0, 1, 2]) };
+ const written = new TextDecoder().decode(new Uint8Array(exportStl([mesh], plan.stlHeader), 0, 80));
+ assert.ok(written.includes(sha256.slice(0, 12)), 'the hash survives truncation');
+ });
+
+ it('records the full hash and the offsets in the OpenSCAD notes', async () => {
+ const sha256 = await hashDfmProfile(profile);
+ const notes = planExport(nominal, 'My chip', { profile, sha256 }).scadNotes.join('\n');
+ assert.ok(notes.includes(`Profile SHA-256: ${sha256}`));
+ assert.match(notes, /Print-correction profile: Bench printer, clear resin/);
+ assert.match(notes, /Lateral offset per side: 0\.05 mm/);
+ assert.match(notes, /Ceiling raise: 0\.1 mm/);
+ assert.match(notes, /not the nominal design/);
+ });
+});
+
+describe('the profile reference in a project file', () => {
+ it('is absent from a new project and from its saved file', () => {
+ const project = createProject();
+ assert.equal('dfmProfileRef' in project, false);
+ assert.doesNotMatch(serializeProject(project), /dfmProfileRef/);
+ });
+
+ it('round-trips when present', () => {
+ const project = { ...createProject(), dfmProfileRef: { name: 'Bench', sha256: 'ab'.repeat(32) } };
+ const parsed = parseProject(serializeProject(project));
+ assert.equal(parsed.ok, true);
+ if (!parsed.ok) return;
+ assert.deepEqual(parsed.project.dfmProfileRef, project.dfmProfileRef);
+ });
+
+ it('leaves every shipped project file byte-identical through a load and save', () => {
+ for (const dir of ['examples', 'skills/openchip-design/examples']) {
+ const abs = join(process.cwd(), dir);
+ for (const file of readdirSync(abs).filter((f) => f.endsWith('.openchip'))) {
+ const parsed = parseProject(readFileSync(join(abs, file), 'utf8'));
+ assert.equal(parsed.ok, true);
+ if (!parsed.ok) continue;
+ assert.equal('dfmProfileRef' in parsed.project, false, file);
+ const again = parseProject(serializeProject(parsed.project));
+ assert.ok(again.ok && serializeProject(again.project) === serializeProject(parsed.project), file);
+ }
+ }
+ });
+
+ it('opens a project whose profile is nowhere to be found', () => {
+ const project = { ...createProject(), dfmProfileRef: { name: 'Gone', sha256: 'cd'.repeat(32) } };
+ const parsed = parseProject(serializeProject(project));
+ assert.equal(parsed.ok, true);
+ if (!parsed.ok) return;
+ // Exporting it without that profile is simply the nominal export.
+ const plan = planExport(
+ {
+ graph: parsed.project.channelGraph,
+ chipParams: parsed.project.chipParams,
+ drainageVents: parsed.project.drainageVents,
+ printerProfile: parsed.project.printerProfile,
+ },
+ parsed.project.meta.name,
+ null,
+ );
+ assert.equal(plan.compensated, null);
+ });
+
+ it('rejects a malformed reference with a named section', () => {
+ const raw = JSON.parse(serializeProject(createProject()));
+ raw.dfmProfileRef = { name: 5 };
+ const parsed = parseProject(JSON.stringify(raw));
+ assert.equal(parsed.ok, false);
+ if (parsed.ok) return;
+ assert.ok(parsed.details.some((d) => /Print-correction reference/.test(d)), parsed.details.join(' | '));
+ });
+
+ it('never stores compensated geometry: saving after planning leaves the graph nominal', async () => {
+ const project = createProject({ channelGraph: parallelChannels(3) });
+ const before = serializeProject(project);
+ const profile = makeProfile();
+ planExport(
+ {
+ graph: project.channelGraph,
+ chipParams: project.chipParams,
+ drainageVents: project.drainageVents,
+ printerProfile: project.printerProfile,
+ },
+ project.meta.name,
+ { profile, sha256: await hashDfmProfile(profile) },
+ );
+ assert.equal(serializeProject(project), before);
+ });
+});
diff --git a/src/lib/dfm/exportPlan.ts b/src/lib/dfm/exportPlan.ts
new file mode 100644
index 0000000..aff24bd
--- /dev/null
+++ b/src/lib/dfm/exportPlan.ts
@@ -0,0 +1,86 @@
+/**
+ * What an export is built from, and what it is called.
+ *
+ * Every STL and OpenSCAD export goes through `planExport`. With no profile it
+ * hands back the nominal design untouched — the same objects, an empty suffix,
+ * the same header the app has always written — so "None (uncompensated)" is not
+ * a special mode of this feature but its absence. With a profile it runs
+ * `compensateDesign` and names the result so it cannot be mistaken for the
+ * nominal file.
+ */
+
+import { slugify } from '../slug';
+import { compensateDesign, type CompensatedDesign, type NominalDesign } from './compensate';
+import { shortHash, type DfmProfile } from './profile';
+import type { ChannelGraph, ChipParams, DrainageVent } from '../../types/project';
+
+/** A loaded profile with the hash of its contents. */
+export interface DfmEntry {
+ profile: DfmProfile;
+ sha256: string;
+}
+
+export interface ExportPlan {
+ graph: ChannelGraph;
+ chipParams: ChipParams;
+ drainageVents: DrainageVent[];
+ ceilingRaiseMm: number;
+ /** Appended to the file stem: empty for a nominal export. */
+ fileSuffix: string;
+ /** The 80-byte STL header. */
+ stlHeader: string;
+ /** Comment lines for the top of the OpenSCAD source. */
+ scadNotes: string[];
+ /** The full result of compensation, or null for a nominal export. */
+ compensated: CompensatedDesign | null;
+}
+
+const mm = (value: number): string => String(Number(value.toFixed(4)));
+
+export function planExport(
+ nominal: NominalDesign,
+ projectName: string,
+ entry: DfmEntry | null,
+ compensated?: CompensatedDesign,
+): ExportPlan {
+ if (!entry) {
+ return {
+ graph: nominal.graph,
+ chipParams: nominal.chipParams,
+ drainageVents: nominal.drainageVents,
+ ceilingRaiseMm: 0,
+ fileSuffix: '',
+ stlHeader: `OpenChip ${projectName}`,
+ scadNotes: [],
+ compensated: null,
+ };
+ }
+
+ const { profile, sha256 } = entry;
+ const result = compensated ?? compensateDesign(nominal, profile);
+ const { applied } = result;
+
+ return {
+ graph: result.graph,
+ chipParams: result.chipParams,
+ drainageVents: result.drainageVents,
+ ceilingRaiseMm: result.ceilingRaiseMm,
+ fileSuffix: `-dfm-${slugify(profile.meta.name)}`,
+ // An STL header is 80 bytes and nothing else in the format carries
+ // metadata, so the hash goes first where truncation cannot reach it.
+ stlHeader: `OpenChip DFM ${shortHash(sha256)} ${profile.meta.name} | ${projectName}`,
+ scadNotes: [
+ '',
+ 'PRINT-CORRECTED GEOMETRY — not the nominal design.',
+ `Print-correction profile: ${profile.meta.name}`,
+ `Profile SHA-256: ${sha256}`,
+ `Lateral offset per side: ${mm(applied.deltaXyMm)} mm` +
+ (applied.lateralDecayMm > 0 ? `, decay length ${mm(applied.lateralDecayMm)} mm` : ''),
+ applied.deltaZMm > 0
+ ? `Ceiling raise: ${mm(applied.deltaZMm)} mm`
+ : 'Ceiling raise: none (no printed ceilings on this split type)',
+ 'Channel sizes below already include the correction. Ports are nominal.',
+ ],
+ compensated: result,
+ };
+}
diff --git a/src/lib/dfm/fit.test.ts b/src/lib/dfm/fit.test.ts
new file mode 100644
index 0000000..76f41df
--- /dev/null
+++ b/src/lib/dfm/fit.test.ts
@@ -0,0 +1,181 @@
+/**
+ * Fit tests. Each synthesises coupon results from known offsets and checks the
+ * fit recovers them — or, for open/closed data, brackets them and says how
+ * loosely.
+ */
+
+import assert from 'node:assert/strict';
+import { describe, it } from 'vitest';
+import { FALLBACK_PRINTER_PROFILE } from '../defaults';
+import { blankMeasurements, couponLayout, defaultCouponSpec } from './coupon';
+import { fitCompensation } from './fit';
+import { printedWidthMm } from './model';
+import type { CouponMeasurement } from './profile';
+
+const blank = (): CouponMeasurement[] =>
+ blankMeasurements(couponLayout(defaultCouponSpec(FALLBACK_PRINTER_PROFILE)));
+
+/** Marks each channel the way a printer with these true offsets would leave it. */
+const simulate = (closureWidthMm: number, deltaZMm: number): CouponMeasurement[] =>
+ blank().map((m) => ({
+ ...m,
+ result:
+ m.nominalWidthMm <= closureWidthMm || m.nominalHeightMm <= deltaZMm ? 'closed' : 'open',
+ }));
+
+const near = (actual: number, expected: number, tolerance: number, label = '') =>
+ assert.ok(Math.abs(actual - expected) <= tolerance, `${label} expected ${expected}, got ${actual}`);
+
+describe('fitting from open / closed results', () => {
+ it('brackets both thresholds from the matrix', () => {
+ // Coupon widths: 0.1 0.15 0.2 0.25 0.3 0.4 0.6; heights: 0.1 0.2 0.3 0.5.
+ // Truth: closes at or below 0.22 mm wide (Δxy 0.11) or 0.15 mm tall.
+ const fit = fitCompensation(simulate(0.22, 0.15));
+
+ // 0.2 closed and 0.25 open → closure width in [0.2, 0.25), per side [0.1, 0.125).
+ assert.deepEqual(fit.lateral.bracketMm, [0.1, 0.125]);
+ near(fit.deltaXyMm, 0.1125, 1e-9);
+ // 0.1 closed and 0.2 open → Δz in [0.1, 0.2).
+ assert.deepEqual(fit.vertical.bracketMm, [0.1, 0.2]);
+ near(fit.deltaZMm, 0.15, 1e-9);
+
+ assert.equal(fit.lateral.method, 'open-closed');
+ assert.equal(fit.vertical.method, 'open-closed');
+ assert.equal(fit.lateral.inconsistent, 0);
+ assert.equal(fit.lateral.dataPoints, 28);
+ });
+
+ it('contains the true offset in its bracket', () => {
+ for (const [closure, dz] of [[0.12, 0.25], [0.31, 0.1], [0.45, 0.31]] as const) {
+ const fit = fitCompensation(simulate(closure, dz));
+ const [lo, hi] = fit.lateral.bracketMm ?? [0, 0];
+ assert.ok(lo <= closure / 2 && closure / 2 < (hi ?? Infinity), `lateral ${closure}`);
+ const [zlo, zhi] = fit.vertical.bracketMm ?? [0, 0];
+ assert.ok(zlo <= dz && dz < (zhi ?? Infinity), `vertical ${dz}`);
+ }
+ });
+
+ it('never fits a decay length, and says the result is coarse', () => {
+ const fit = fitCompensation(simulate(0.22, 0.15));
+ assert.equal(fit.lateralDecayMm, 0);
+ assert.ok(fit.notes.some((n) => /lateral offset comes from open\/closed results only.*coarse/.test(n)));
+ assert.ok(fit.notes.some((n) => /vertical offset comes from open\/closed results only.*coarse/.test(n)));
+ });
+
+ it('applies no correction when nothing closed', () => {
+ const fit = fitCompensation(blank().map((m) => ({ ...m, result: 'open' as const })));
+ assert.equal(fit.deltaXyMm, 0);
+ assert.equal(fit.deltaZMm, 0);
+ // The upper end is still reported: overcure is below the smallest size.
+ assert.deepEqual(fit.lateral.bracketMm, [0, 0.05]);
+ assert.ok(fit.notes.some((n) => /No channel closed across its width/.test(n)));
+ });
+
+ it('reports a lower bound when everything closed', () => {
+ const fit = fitCompensation(blank().map((m) => ({ ...m, result: 'closed' as const })));
+ assert.ok(
+ fit.lateral.bracketMm?.[1] === null || fit.vertical.bracketMm?.[1] === null,
+ 'at least one axis has no upper bound',
+ );
+ assert.ok(fit.notes.some((n) => /lower bound/.test(n)));
+ });
+
+ it('uses a partially open channel to tighten the bracket', () => {
+ const results = simulate(0.22, 0.05).map((m) =>
+ m.nominalWidthMm === 0.25 ? { ...m, result: 'partial' as const } : m,
+ );
+ const fit = fitCompensation(results);
+ // The threshold is taken to sit just under the partial channel's 0.25 mm:
+ // the top quarter of [0.2, 0.25], halved per side.
+ near(fit.lateral.bracketMm?.[0] ?? 0, 0.11875, 1e-4);
+ assert.equal(fit.lateral.bracketMm?.[1], 0.125);
+ });
+
+ it('counts results no threshold can explain', () => {
+ const results = simulate(0.22, 0.05).map((m) =>
+ m.id === '4.1' ? { ...m, result: 'closed' as const } : m,
+ );
+ const fit = fitCompensation(results);
+ assert.equal(fit.lateral.inconsistent, 1);
+ assert.match(fit.notes[0], /1 channel does not fit any single threshold/);
+ // One stray entry does not move the answer.
+ assert.deepEqual(fit.lateral.bracketMm, [0.1, 0.125]);
+ });
+
+ it('ignores channels that were not checked', () => {
+ const results = simulate(0.22, 0.15).map((m, i) => (i % 2 ? { ...m, result: null } : m));
+ assert.equal(fitCompensation(results).lateral.dataPoints, 14);
+ });
+
+ it('says so when there is nothing to fit', () => {
+ const fit = fitCompensation(blank());
+ assert.equal(fit.lateral.method, 'none');
+ assert.equal(fit.vertical.method, 'none');
+ assert.deepEqual(fit.notes, ['No results have been entered yet.']);
+ });
+});
+
+describe('fitting from measured dimensions', () => {
+ it('recovers a constant lateral offset exactly', () => {
+ const results = blank().map((m) => ({
+ ...m,
+ measuredWidthMm: Math.max(0, m.nominalWidthMm - 0.08),
+ }));
+ const fit = fitCompensation(results);
+ assert.equal(fit.lateral.method, 'measured');
+ near(fit.deltaXyMm, 0.04, 1e-4);
+ assert.equal(fit.lateralDecayMm, 0);
+ near(fit.lateral.rmsMm ?? 1, 0, 1e-4);
+ });
+
+ it('recovers the offset and the decay length when narrow channels lose more', () => {
+ const truth = { deltaXyMm: 0.03, lateralDecayMm: 0.06 };
+ const results = blank().map((m) => ({
+ ...m,
+ measuredWidthMm: Number(printedWidthMm(m.nominalWidthMm, truth).toFixed(4)),
+ }));
+ const fit = fitCompensation(results);
+ near(fit.deltaXyMm, 0.03, 2e-3);
+ near(fit.lateralDecayMm, 0.06, 5e-3);
+ assert.ok((fit.lateral.rmsMm ?? 1) < 1e-3);
+ });
+
+ it('keeps the constant model when too few widths were measured', () => {
+ const results = blank().map((m) =>
+ m.nominalWidthMm >= 0.4 ? { ...m, measuredWidthMm: m.nominalWidthMm - 0.06 } : m,
+ );
+ const fit = fitCompensation(results);
+ assert.equal(fit.lateralDecayMm, 0);
+ near(fit.deltaXyMm, 0.03, 1e-4);
+ assert.ok(fit.notes.some((n) => /Measure at least 3 different widths/.test(n)));
+ });
+
+ it('averages the measured ceiling loss, with its scatter', () => {
+ const results = blank().map((m, i) => ({
+ ...m,
+ measuredHeightMm: m.nominalHeightMm > 0.1 ? m.nominalHeightMm - (i % 2 ? 0.07 : 0.09) : undefined,
+ }));
+ const fit = fitCompensation(results);
+ assert.equal(fit.vertical.method, 'measured');
+ near(fit.deltaZMm, 0.08, 2e-3);
+ near(fit.vertical.rmsMm ?? 0, 0.01, 2e-3);
+ });
+
+ it('fits each axis from the best evidence it has', () => {
+ const results = simulate(0.22, 0.15).map((m) => ({
+ ...m,
+ measuredWidthMm: Math.max(0, m.nominalWidthMm - 0.2),
+ }));
+ const fit = fitCompensation(results);
+ assert.equal(fit.lateral.method, 'measured');
+ assert.equal(fit.vertical.method, 'open-closed');
+ });
+
+ it('reports a clear misfit as a residual rather than hiding it', () => {
+ const results = blank().map((m, i) => ({
+ ...m,
+ measuredWidthMm: m.nominalWidthMm - (i % 2 ? 0.02 : 0.1),
+ }));
+ assert.ok((fitCompensation(results).lateral.rmsMm ?? 0) > 0.02);
+ });
+});
diff --git a/src/lib/dfm/fit.ts b/src/lib/dfm/fit.ts
new file mode 100644
index 0000000..0392543
--- /dev/null
+++ b/src/lib/dfm/fit.ts
@@ -0,0 +1,320 @@
+/**
+ * Fitting compensation parameters to coupon results.
+ *
+ * Two kinds of evidence, and they are worth very different amounts.
+ *
+ * **Measured dimensions** give the printed size of a channel directly, so the
+ * offsets are a least-squares fit with a residual that says how well the model
+ * describes the printer.
+ *
+ * **Open / partial / closed** only says on which side of a threshold each
+ * channel fell. The most that can be recovered is the interval between the
+ * largest size that closed and the smallest that stayed open. The fit reports
+ * that interval and takes a point inside it, and the UI calls the result
+ * coarse — because it is: with a coupon stepping in 0.05 mm, the lateral
+ * offset per side is known to about ±0.0125 mm at best, and a closure width
+ * alone cannot tell a large constant offset from a small one that grows in
+ * narrow channels. So an open/closed fit always uses the constant model
+ * (`lateralDecayMm` = 0).
+ *
+ * The two axes are fitted separately and may use different evidence: measured
+ * widths with open/closed heights is a normal thing to have, since widths can
+ * be read from above and heights need a section.
+ *
+ * Everything here is pure and deterministic.
+ */
+
+import { closureWidthMm, printedWidthMm, type LateralModel } from './model';
+import type { AxisFit, CouponMeasurement } from './profile';
+
+export interface FitResult {
+ deltaXyMm: number;
+ lateralDecayMm: number;
+ deltaZMm: number;
+ lateral: AxisFit;
+ vertical: AxisFit;
+ /** Plain-language caveats for the UI, most important first. */
+ notes: string[];
+}
+
+/** Distinct measured widths needed before the decay length is fitted too. */
+const MIN_WIDTHS_FOR_DECAY = 3;
+const MAX_DECAY_MM = 0.5;
+
+const round = (value: number, places = 4): number => Number(value.toFixed(places));
+const distinct = (values: number[]): number[] =>
+ [...new Set(values.map((v) => round(v)))].sort((a, b) => a - b);
+
+// ---------------------------------------------------------------------------
+// open / closed
+// ---------------------------------------------------------------------------
+
+interface Bracket {
+ lo: number;
+ hi: number | null;
+ inconsistent: number;
+ dataPoints: number;
+}
+
+/**
+ * Closure thresholds in width and in height that best explain the results.
+ *
+ * A channel is taken to close when its width is at or below a width threshold
+ * *or* its height is at or below a height threshold. Both are searched
+ * together, because a channel that closed says only that one of the two was
+ * crossed — the matrix of widths against heights is what separates them. Every
+ * pair of candidate thresholds is scored by how many open and closed channels
+ * it gets wrong; partial channels fit either side and score nothing.
+ *
+ * Several pairs usually tie. The answer for each axis is the full range of its
+ * threshold over the tied pairs, which is the honest statement of what the
+ * data pins down.
+ */
+function closureBrackets(measurements: CouponMeasurement[]): { width: Bracket; height: Bracket } {
+ const marked = measurements.filter((m) => m.result !== null);
+ const widths = distinct(marked.map((m) => m.nominalWidthMm));
+ const heights = distinct(marked.map((m) => m.nominalHeightMm));
+
+ // Candidate k means "the k smallest sizes close": the threshold sits between
+ // size k and size k+1, with 0 below everything.
+ const edges = (sizes: number[]) => [0, ...sizes];
+ const widthEdges = edges(widths);
+ const heightEdges = edges(heights);
+
+ let best = Infinity;
+ let tied: { wi: number; hi: number }[] = [];
+
+ for (let wi = 0; wi < widthEdges.length; wi += 1) {
+ for (let hi = 0; hi < heightEdges.length; hi += 1) {
+ let wrong = 0;
+ for (const m of marked) {
+ const closes =
+ round(m.nominalWidthMm) <= widthEdges[wi] || round(m.nominalHeightMm) <= heightEdges[hi];
+ if (m.result === 'open' && closes) wrong += 1;
+ if (m.result === 'closed' && !closes) wrong += 1;
+ }
+ if (wrong < best) {
+ best = wrong;
+ tied = [];
+ }
+ if (wrong === best) tied.push({ wi, hi });
+ }
+ }
+
+ const bracket = (indices: number[], sizeEdges: number[], axis: 'w' | 'h'): Bracket => {
+ const lowest = Math.min(...indices);
+ const highest = Math.max(...indices);
+ const upper = sizeEdges[highest + 1];
+ let hi: number | null = upper ?? null;
+ let lo = sizeEdges[lowest];
+
+ // A partially open channel is sitting on the threshold, so it narrows the
+ // interval to the top quarter below its own size.
+ const partial = marked
+ .filter((m) => m.result === 'partial')
+ .map((m) => round(axis === 'w' ? m.nominalWidthMm : m.nominalHeightMm))
+ .filter((size) => size > lo && (hi === null || size <= hi));
+ if (partial.length > 0) {
+ hi = Math.min(...partial);
+ lo = hi - (hi - lo) / 4;
+ }
+
+ return { lo, hi, inconsistent: best === Infinity ? 0 : best, dataPoints: marked.length };
+ };
+
+ return {
+ width: bracket(tied.map((t) => t.wi), widthEdges, 'w'),
+ height: bracket(tied.map((t) => t.hi), heightEdges, 'h'),
+ };
+}
+
+/**
+ * A point estimate from a bracket.
+ *
+ * The midpoint when both ends are known. When nothing closed, the lower end —
+ * zero — because enlarging channels on no evidence of overcure is the one
+ * choice that can only make a good print worse. When nothing stayed open, the
+ * lower end again: it is a floor, and the UI says so.
+ */
+const pointIn = (bracket: Bracket): number =>
+ bracket.hi === null || bracket.lo === 0 ? bracket.lo : (bracket.lo + bracket.hi) / 2;
+
+// ---------------------------------------------------------------------------
+// measured
+// ---------------------------------------------------------------------------
+
+function sumSquares(points: { drawn: number; printed: number }[], model: LateralModel): number {
+ let total = 0;
+ for (const p of points) {
+ const residual = printedWidthMm(p.drawn, model) - p.printed;
+ total += residual * residual;
+ }
+ return total;
+}
+
+/** Best `deltaXyMm` for a fixed decay length, by golden-section search. */
+function bestDelta(
+ points: { drawn: number; printed: number }[],
+ lateralDecayMm: number,
+): { deltaXyMm: number; sse: number } {
+ const widest = Math.max(...points.map((p) => p.drawn));
+ let lo = 0;
+ let hi = widest / 2;
+ const ratio = (Math.sqrt(5) - 1) / 2;
+ const cost = (deltaXyMm: number) => sumSquares(points, { deltaXyMm, lateralDecayMm });
+
+ for (let i = 0; i < 60; i += 1) {
+ const a = hi - (hi - lo) * ratio;
+ const b = lo + (hi - lo) * ratio;
+ if (cost(a) < cost(b)) hi = b;
+ else lo = a;
+ }
+ const deltaXyMm = (lo + hi) / 2;
+ return { deltaXyMm, sse: cost(deltaXyMm) };
+}
+
+function fitLateralMeasured(
+ points: { drawn: number; printed: number }[],
+): { model: LateralModel; rmsMm: number } {
+ const widths = distinct(points.map((p) => p.drawn));
+ let best = { lateralDecayMm: 0, ...bestDelta(points, 0) };
+
+ if (widths.length >= MIN_WIDTHS_FOR_DECAY) {
+ // A scan rather than a second golden-section: the cost is not guaranteed
+ // to have one minimum in the decay length, and 100 evaluations of a
+ // closed-form model are free.
+ for (let step = 1; step <= 100; step += 1) {
+ const lateralDecayMm = (MAX_DECAY_MM * step) / 100;
+ const candidate = bestDelta(points, lateralDecayMm);
+ // The extra parameter has to earn its place: a decay length is kept only
+ // if it cuts the squared error by more than a tenth.
+ if (candidate.sse < best.sse * 0.9) best = { lateralDecayMm, ...candidate };
+ }
+ }
+
+ return {
+ model: { deltaXyMm: best.deltaXyMm, lateralDecayMm: best.lateralDecayMm },
+ rmsMm: Math.sqrt(best.sse / points.length),
+ };
+}
+
+// ---------------------------------------------------------------------------
+// the fit
+// ---------------------------------------------------------------------------
+
+export function fitCompensation(measurements: CouponMeasurement[]): FitResult {
+ const notes: string[] = [];
+ const brackets = closureBrackets(measurements);
+ const anyMarked = brackets.width.dataPoints > 0;
+
+ // --- lateral --------------------------------------------------------------
+ const widthPoints = measurements
+ .filter((m) => m.measuredWidthMm !== undefined && m.measuredWidthMm > 0)
+ .map((m) => ({ drawn: m.nominalWidthMm, printed: m.measuredWidthMm as number }));
+
+ let deltaXyMm = 0;
+ let lateralDecayMm = 0;
+ let lateral: AxisFit = { method: 'none', dataPoints: 0 };
+
+ if (widthPoints.length > 0) {
+ const fitted = fitLateralMeasured(widthPoints);
+ deltaXyMm = fitted.model.deltaXyMm;
+ lateralDecayMm = fitted.model.lateralDecayMm;
+ lateral = { method: 'measured', dataPoints: widthPoints.length, rmsMm: round(fitted.rmsMm, 5) };
+
+ const widths = distinct(widthPoints.map((p) => p.drawn)).length;
+ if (widths < MIN_WIDTHS_FOR_DECAY) {
+ notes.push(
+ `Widths were measured at ${widths} size${widths === 1 ? '' : 's'}, so the lateral offset is fitted as a constant. ` +
+ `Measure at least ${MIN_WIDTHS_FOR_DECAY} different widths to fit how it grows in narrow channels.`,
+ );
+ }
+ } else if (anyMarked) {
+ const b = brackets.width;
+ // A channel closes when its width is at or below 2·Δxy in the constant
+ // model, so the closure width is halved to get the per-side offset.
+ deltaXyMm = pointIn(b) / 2;
+ lateral = {
+ method: 'open-closed',
+ dataPoints: b.dataPoints,
+ bracketMm: [round(b.lo / 2), b.hi === null ? null : round(b.hi / 2)],
+ inconsistent: b.inconsistent,
+ };
+ notes.push(
+ 'The lateral offset comes from open/closed results only, so it is coarse: it is known no better than the ' +
+ 'range shown, and it is applied equally at every width. Measured widths give a real fit.',
+ );
+ if (b.hi === null) {
+ notes.push(
+ 'No channel stayed open across its width, so the lateral offset is a lower bound. Reprint the coupon with wider channels.',
+ );
+ } else if (b.lo === 0) {
+ notes.push(
+ 'No channel closed across its width, so lateral overcure is below what this coupon resolves and no lateral correction is applied.',
+ );
+ }
+ }
+
+ // --- vertical -------------------------------------------------------------
+ const heightPoints = measurements.filter(
+ (m) => m.measuredHeightMm !== undefined && m.measuredHeightMm > 0,
+ );
+
+ let deltaZMm = 0;
+ let vertical: AxisFit = { method: 'none', dataPoints: 0 };
+
+ if (heightPoints.length > 0) {
+ const losses = heightPoints.map((m) => m.nominalHeightMm - (m.measuredHeightMm as number));
+ const mean = losses.reduce((sum, v) => sum + v, 0) / losses.length;
+ deltaZMm = Math.max(0, mean);
+ const rms = Math.sqrt(losses.reduce((sum, v) => sum + (v - mean) ** 2, 0) / losses.length);
+ vertical = { method: 'measured', dataPoints: heightPoints.length, rmsMm: round(rms, 5) };
+ } else if (anyMarked) {
+ const b = brackets.height;
+ deltaZMm = pointIn(b);
+ vertical = {
+ method: 'open-closed',
+ dataPoints: b.dataPoints,
+ bracketMm: [round(b.lo), b.hi === null ? null : round(b.hi)],
+ inconsistent: b.inconsistent,
+ };
+ notes.push(
+ 'The vertical offset comes from open/closed results only, so it is coarse: it is known no better than the range shown.',
+ );
+ if (b.hi === null) {
+ notes.push(
+ 'No channel stayed open at any height, so the vertical offset is a lower bound. Reprint the coupon with taller channels.',
+ );
+ } else if (b.lo === 0) {
+ notes.push(
+ 'No channel closed because of its height, so vertical overcure is below what this coupon resolves and no ceiling correction is applied.',
+ );
+ }
+ }
+
+ if (!anyMarked && widthPoints.length === 0 && heightPoints.length === 0) {
+ notes.push('No results have been entered yet.');
+ }
+
+ const inconsistent = Math.max(lateral.inconsistent ?? 0, vertical.inconsistent ?? 0);
+ if (inconsistent > 0) {
+ notes.unshift(
+ `${inconsistent} channel${inconsistent === 1 ? ' does' : 's do'} not fit any single threshold — for example a narrow ` +
+ 'channel open while a wider one at the same height is closed. Check those entries, or flush the coupon again: ' +
+ 'trapped resin reads as a closed channel.',
+ );
+ }
+
+ return {
+ deltaXyMm: round(deltaXyMm),
+ lateralDecayMm: round(lateralDecayMm),
+ deltaZMm: round(deltaZMm),
+ lateral,
+ vertical,
+ notes,
+ };
+}
+
+/** Drawn width at or below which a fitted profile predicts closure, mm. */
+export const predictedClosureWidthMm = (fit: Pick): number =>
+ closureWidthMm(fit);
diff --git a/src/lib/dfm/model.ts b/src/lib/dfm/model.ts
new file mode 100644
index 0000000..fa6c149
--- /dev/null
+++ b/src/lib/dfm/model.ts
@@ -0,0 +1,110 @@
+/**
+ * The compensation model: how far a printed edge lands from where it was drawn.
+ *
+ * ## Where the shape comes from
+ *
+ * Resin cures where the absorbed dose exceeds a critical exposure. Jacobs'
+ * working curve gives the depth that reaches it,
+ *
+ * C_d = D_p · ln(E / E_c)
+ *
+ * which is Beer–Lambert attenuation solved for the depth at which the dose has
+ * fallen to E_c. Two consequences shape everything here.
+ *
+ * **Vertically**, light meant for the layers above a channel carries on into
+ * the uncured resin inside it and cures the ceiling downwards. The depth
+ * depends on dose and penetration depth, not on how wide the channel is, so it
+ * is modelled as one number: `deltaZMm`.
+ *
+ * **Laterally**, stray light past a mask edge is taken to fall off the same
+ * way, exponentially with distance, with a decay length λ. One isolated edge
+ * then cures a fixed distance Δ past where it was drawn. A channel is two
+ * edges facing each other, and the stray doses from both add in the gap:
+ *
+ * dose(x) ∝ e^(−x/λ) + e^(−(W−x)/λ) 0 ≤ x ≤ W
+ *
+ * The wall advances to wherever that sum equals the threshold e^(−Δ/λ). For a
+ * wide channel the far wall contributes nothing and each side moves in by Δ.
+ * As the channel narrows the tails overlap, each wall moves further, and at
+ * W = 2Δ + 2λ·ln 2 the two meet and the channel is closed — which is the
+ * observed behaviour that narrow channels close disproportionately.
+ *
+ * ## What is and is not claimed
+ *
+ * - This is an **empirical** two-parameter curve with a physically motivated
+ * shape. Δ and λ are fitted to coupon measurements directly. D_p and E_c are
+ * not recovered: a coupon printed at one exposure cannot separate them, since
+ * only the product in the logarithm is observable.
+ * - Real stray light is not purely exponential (pixel blur, scattering in the
+ * vat film, resin bleed all contribute). λ absorbs whatever makes narrow
+ * channels worse, whatever its cause.
+ * - λ = 0 reduces the model to a constant offset per side. That is what a fit
+ * from open/closed observations alone uses, because one closure width cannot
+ * separate Δ from λ.
+ * - Offsets are assumed isotropic in XY and uniform across the build plate.
+ */
+
+export interface LateralModel {
+ /** Bleed per side on an isolated edge, mm. */
+ deltaXyMm: number;
+ /** Decay length of the stray dose, mm. Zero for a constant offset. */
+ lateralDecayMm: number;
+}
+
+/** Drawn width at or below which the model predicts a channel cures shut, mm. */
+export function closureWidthMm(model: LateralModel): number {
+ return 2 * model.deltaXyMm + 2 * Math.max(0, model.lateralDecayMm) * Math.LN2;
+}
+
+/**
+ * How far each wall of a channel drawn `drawnWidthMm` wide moves inward, mm.
+ *
+ * Returns half the drawn width when the channel closes, so that
+ * `drawn − 2·bleed` is zero rather than negative.
+ */
+export function bleedPerSideMm(drawnWidthMm: number, model: LateralModel): number {
+ const delta = model.deltaXyMm;
+ const lambda = model.lateralDecayMm;
+ if (drawnWidthMm <= 0) return 0;
+ if (!(lambda > 0)) return Math.min(delta, drawnWidthMm / 2);
+
+ // With y = e^(x/λ), c = e^(−Δ/λ) and q = e^(−W/λ), the threshold condition
+ // 1/y + q·y = c is the quadratic q·y² − c·y + 1 = 0. The smaller root is the
+ // wall nearer x = 0. Written as 2/(c + √disc) rather than (c − √disc)/2q:
+ // for a wide channel q underflows towards zero and the second form divides
+ // one vanishing number by another.
+ const c = Math.exp(-delta / lambda);
+ const q = Math.exp(-drawnWidthMm / lambda);
+ const disc = c * c - 4 * q;
+ if (disc <= 0) return drawnWidthMm / 2;
+
+ const y = 2 / (c + Math.sqrt(disc));
+ return Math.min(lambda * Math.log(y), drawnWidthMm / 2);
+}
+
+/** Width a channel drawn `drawnWidthMm` wide is predicted to print at, mm. */
+export function printedWidthMm(drawnWidthMm: number, model: LateralModel): number {
+ return Math.max(0, drawnWidthMm - 2 * bleedPerSideMm(drawnWidthMm, model));
+}
+
+/**
+ * Width to draw so the channel prints `targetWidthMm` wide — the inverse of
+ * `printedWidthMm`.
+ *
+ * Printed width rises monotonically with drawn width, and the answer lies
+ * between `target + 2Δ` (no overlap of the tails) and `target + closure width`
+ * (the most either wall can ever move), so bisection always converges.
+ */
+export function drawnWidthForMm(targetWidthMm: number, model: LateralModel): number {
+ if (targetWidthMm <= 0) return targetWidthMm;
+ if (!(model.lateralDecayMm > 0)) return targetWidthMm + 2 * model.deltaXyMm;
+
+ let lo = targetWidthMm + 2 * model.deltaXyMm;
+ let hi = targetWidthMm + closureWidthMm(model);
+ for (let i = 0; i < 60; i += 1) {
+ const mid = (lo + hi) / 2;
+ if (printedWidthMm(mid, model) < targetWidthMm) lo = mid;
+ else hi = mid;
+ }
+ return (lo + hi) / 2;
+}
diff --git a/src/lib/dfm/preview.test.ts b/src/lib/dfm/preview.test.ts
new file mode 100644
index 0000000..cb126a5
--- /dev/null
+++ b/src/lib/dfm/preview.test.ts
@@ -0,0 +1,205 @@
+/**
+ * The preview must show the geometry the export writes. These tests build the
+ * compensated chip through the export path and compare the actual mesh with
+ * what the preview draws for the same design and profile.
+ */
+
+import assert from 'node:assert/strict';
+import { beforeAll, describe, it } from 'vitest';
+import Module from 'manifold-3d';
+import { buildChip, type ManifoldApi } from '../cad/buildChip';
+import { CHIP_PRESETS, presetBuild } from '../presets';
+import { DEFAULT_CHIP_PARAMS, FALLBACK_PRINTER_PROFILE } from '../defaults';
+import type { ChannelGraph } from '../../types/project';
+import { compensateDesign, type NominalDesign } from './compensate';
+import { planExport } from './exportPlan';
+import { buildDfmPreview, sliceSections } from './preview';
+import { hashDfmProfile } from './profile';
+import { design, makeProfile, parallelChannels } from './testFixtures';
+
+let api: ManifoldApi;
+
+beforeAll(async () => {
+ const raw = await Module();
+ raw.setup();
+ api = { Manifold: raw.Manifold, Mesh: raw.Mesh } as unknown as ManifoldApi;
+}, 60_000);
+
+const near = (actual: number, expected: number, tolerance: number, label = '') =>
+ assert.ok(Math.abs(actual - expected) <= tolerance, `${label} expected ${expected}, got ${actual}`);
+
+/** Extent of a mesh's vertices near the plane x = `at`, in y and z. */
+function meshSlice(positions: Float32Array, at: number, yLo: number, yHi: number) {
+ let yMin = Infinity, yMax = -Infinity, zMin = Infinity, zMax = -Infinity;
+ for (let i = 0; i < positions.length; i += 3) {
+ if (Math.abs(positions[i] - at) > 0.6) continue;
+ const y = positions[i + 1];
+ if (y < yLo || y > yHi) continue;
+ yMin = Math.min(yMin, y);
+ yMax = Math.max(yMax, y);
+ zMin = Math.min(zMin, positions[i + 2]);
+ zMax = Math.max(zMax, positions[i + 2]);
+ }
+ return { yMin, yMax, zMin, zMax };
+}
+
+describe('preview geometry equals compensated export geometry', () => {
+ const profile = makeProfile({ deltaXyMm: 0.06, lateralDecayMm: 0.05, deltaZMm: 0.12 });
+
+ for (const crossSection of ['rect', 'trapezoid', 'round'] as const) {
+ it(`matches the built mesh for a ${crossSection} channel`, async () => {
+ const graph: ChannelGraph = parallelChannels(4);
+ graph.edges = graph.edges.map((e) => ({ ...e, crossSection }));
+ graph.edges[1].dimensionPoints = [{ t: 0, widthMm: 0.4, heightMm: 0.3 }];
+ const nominal = design(graph, { splitType: 'monolithic', wallThickness: 0.4 });
+
+ // The export path…
+ const plan = planExport(nominal, 'chip', { profile, sha256: await hashDfmProfile(profile) });
+ const built = buildChip(api, plan.graph, plan.chipParams, {
+ quality: 2,
+ drainageVents: plan.drainageVents,
+ ceilingRaiseMm: plan.ceilingRaiseMm,
+ includeChannelSolid: true,
+ });
+ const cavity = built.channelSolid?.positions;
+ assert.ok(cavity);
+
+ // …and the preview path, from the same function's result.
+ const compensated = compensateDesign(nominal, profile);
+ assert.deepEqual(compensated, plan.compensated);
+ const sections = sliceSections(nominal, compensated, 'x', 20);
+ assert.equal(sections.length, 2);
+
+ for (const section of sections) {
+ const s = section.compensated.points.map((p) => p.s);
+ const z = section.compensated.points.map((p) => p.z);
+ const mesh = meshSlice(cavity, 20, section.alongMm - 2, section.alongMm + 2);
+
+ // The round profile is a 32-gon in both; rect and trapezoid are exact.
+ near(Math.min(...s), mesh.yMin, 1e-4, `${section.edgeId} left wall`);
+ near(Math.max(...s), mesh.yMax, 1e-4, `${section.edgeId} right wall`);
+ near(Math.min(...z), mesh.zMin, 1e-4, `${section.edgeId} floor`);
+ near(Math.max(...z), mesh.zMax, 1e-4, `${section.edgeId} ceiling`);
+
+ if (crossSection === 'round') {
+ // A round channel is corrected as a larger circle, so its lowest
+ // point drops by the lateral offset. A documented limit of the model.
+ const grown = (section.compensated.widthMm - section.nominal.widthMm) / 2;
+ near(section.nominal.floorZ - section.compensated.floorZ, grown, 1e-9, 'round floor');
+ near(section.compensated.ceilingZ - section.nominal.ceilingZ, 0.12 + grown, 1e-9, 'round roof');
+ } else {
+ near(section.compensated.floorZ, section.nominal.floorZ, 1e-9, 'the floor does not move');
+ near(section.compensated.ceilingZ - section.nominal.ceilingZ, 0.12, 1e-9, 'ceiling raise');
+ }
+ assert.ok(section.compensated.widthMm > section.nominal.widthMm);
+ }
+ });
+ }
+
+ it('draws the nominal outline at the nominal mesh, too', () => {
+ const nominal = design(parallelChannels(4), { splitType: 'monolithic' });
+ const compensated = compensateDesign(nominal, profile);
+ const built = buildChip(api, nominal.graph, nominal.chipParams, { quality: 2, includeChannelSolid: true });
+ const [section] = sliceSections(nominal, compensated, 'x', 20);
+ const mesh = meshSlice(built.channelSolid!.positions, 20, section.alongMm - 2, section.alongMm + 2);
+ near(Math.min(...section.nominal.points.map((p) => p.s)), mesh.yMin, 1e-4);
+ near(Math.max(...section.nominal.points.map((p) => p.z)), mesh.zMax, 1e-4);
+ });
+
+ it('outlines each channel in the top view at its compensated width', () => {
+ const nominal = design(parallelChannels(4), { splitType: 'two-piece' });
+ const compensated = compensateDesign(nominal, makeProfile({ deltaXyMm: 0.05 }));
+ const model = buildDfmPreview(nominal, compensated);
+
+ const ys = (points: { y: number }[]) => [Math.min(...points.map((p) => p.y)), Math.max(...points.map((p) => p.y))];
+ // Channel at y = 20, 0.8 mm wide as drawn, 0.9 mm compensated.
+ assert.deepEqual(ys(model.edges[0].nominal).map((v) => Number(v.toFixed(6))), [19.6, 20.4]);
+ assert.deepEqual(ys(model.edges[0].compensated).map((v) => Number(v.toFixed(6))), [19.55, 20.45]);
+ assert.equal(model.edges[0].changed, true);
+ });
+});
+
+describe('the preview model', () => {
+ it('marks nothing changed when the profile changes nothing', () => {
+ const nominal = design(parallelChannels(4));
+ const model = buildDfmPreview(nominal, compensateDesign(nominal, makeProfile({ deltaXyMm: 0, deltaZMm: 0 })));
+ assert.ok(model.edges.every((e) => !e.changed && !e.conflict));
+ assert.deepEqual(model.conflictMarks, []);
+ });
+
+ it('flags the segments a conflict names, and marks where it is', () => {
+ const nominal = design(parallelChannels(1.3), { wallThickness: 0.3 });
+ const compensated = compensateDesign(nominal, makeProfile({ deltaXyMm: 0.1 }));
+ const model = buildDfmPreview(nominal, compensated);
+ assert.deepEqual(model.edges.map((e) => e.conflict), [true, true]);
+ assert.equal(model.conflictMarks.length, 1);
+ assert.equal(model.conflictMarks[0].kind, 'wall-too-thin');
+ assert.ok(sliceSections(nominal, compensated, 'x', 20).every((s) => s.conflict));
+ });
+
+ it('shows ports unchanged and chambers and vents changed', () => {
+ const preset = CHIP_PRESETS.find((p) => p.id === 'serpentine-mixer')!;
+ const graph = presetBuild(preset).graph;
+ const nominal: NominalDesign = {
+ graph,
+ chipParams: { ...DEFAULT_CHIP_PARAMS, ...preset.chipParams },
+ drainageVents: [{ id: 'v', nodeId: graph.nodes[3].id, diameterMm: 0.8, autoPlaced: false }],
+ printerProfile: FALLBACK_PRINTER_PROFILE,
+ };
+ const model = buildDfmPreview(nominal, compensateDesign(nominal, makeProfile()));
+ assert.ok(model.circles.filter((c) => c.kind === 'port').every((c) => !c.changed));
+ assert.ok(model.circles.filter((c) => c.kind === 'vent').every((c) => c.changed));
+ assert.ok(model.circles.some((c) => c.kind === 'joint' && c.changed));
+ });
+
+ it('finds every channel a slice crosses, in order, and none it misses', () => {
+ const nominal = design(parallelChannels(4));
+ const compensated = compensateDesign(nominal, makeProfile());
+ assert.deepEqual(sliceSections(nominal, compensated, 'x', 20).map((s) => s.edgeId), ['ea', 'eb']);
+ assert.deepEqual(sliceSections(nominal, compensated, 'x', 35), []);
+ // A slice along the channels' own direction crosses neither.
+ assert.deepEqual(sliceSections(nominal, compensated, 'y', 22), []);
+ });
+
+ it('stretches an oblique crossing and keeps the true width', () => {
+ const graph: ChannelGraph = {
+ nodes: [
+ { id: 'a', x: 10, y: 10, type: 'waypoint' },
+ { id: 'b', x: 30, y: 30, type: 'waypoint' },
+ ],
+ edges: [{ id: 'e', fromNodeId: 'a', toNodeId: 'b', curveType: 'straight', crossSection: 'rect', dimensionPoints: [] }],
+ };
+ const nominal = design(graph);
+ const [section] = sliceSections(nominal, compensateDesign(nominal, makeProfile()), 'x', 20);
+ near(section.obliqueStretch, Math.SQRT2, 1e-6);
+ near(section.nominal.widthMm, 0.8, 1e-9);
+ const s = section.nominal.points.map((p) => p.s);
+ near(Math.max(...s) - Math.min(...s), 0.8 * Math.SQRT2, 1e-6);
+ });
+
+ it('is fast enough to recompute while editing', () => {
+ // The largest template. Compensation, conflict detection, the preview model
+ // and a slice together are what one debounced recompute costs.
+ const preset = CHIP_PRESETS.find((p) => p.id === 'gradient-generator')!;
+ const nominal: NominalDesign = {
+ graph: presetBuild(preset).graph,
+ chipParams: { ...DEFAULT_CHIP_PARAMS, ...preset.chipParams },
+ drainageVents: [],
+ printerProfile: FALLBACK_PRINTER_PROFILE,
+ };
+ const profile = makeProfile({ lateralDecayMm: 0.05 });
+ const run = () => {
+ // A fresh graph object each time, so the loft cache cannot flatter it.
+ const fresh = { ...nominal, graph: { ...nominal.graph } };
+ const compensated = compensateDesign(fresh, profile);
+ buildDfmPreview(fresh, compensated);
+ sliceSections(fresh, compensated, 'x', fresh.chipParams.width / 2);
+ };
+ run();
+ const started = performance.now();
+ for (let i = 0; i < 5; i += 1) run();
+ const each = (performance.now() - started) / 5;
+ assert.ok(each < 250, `one recompute took ${each.toFixed(1)} ms`);
+ console.log(`dfm preview recompute, gradient generator: ${each.toFixed(1)} ms`);
+ });
+});
diff --git a/src/lib/dfm/preview.ts b/src/lib/dfm/preview.ts
new file mode 100644
index 0000000..f356c87
--- /dev/null
+++ b/src/lib/dfm/preview.ts
@@ -0,0 +1,325 @@
+/**
+ * Geometry for the compensated-design preview.
+ *
+ * The preview draws what `compensateDesign` returned and nothing else: this
+ * module takes the nominal design and that result, and turns both into
+ * outlines and cross-sections with the same loft solver, placement and profile
+ * functions the STL is built from. There is no second idea here of what a
+ * compensated channel looks like, so the picture and the exported file cannot
+ * drift apart — and `preview.test.ts` slices the built mesh to hold it to that.
+ *
+ * Pure, and read-only by construction: it has no access to a store.
+ */
+
+import { ceilingZ, placeChannel, profilePoints } from '../cad/placement';
+import { withChannelPlane } from '../cad/slide';
+import { buildAdjacency, edgesFrom } from '../geometry';
+import { getLoft, sampleAtNode, type LoftSample, type LoftSolution } from '../loft';
+import type { ChannelGraph, ChipParams, CrossSection, Point2 } from '../../types/project';
+import type { CompensatedDesign, DfmConflictKind, NominalDesign } from './compensate';
+
+// ---------------------------------------------------------------------------
+// top view
+// ---------------------------------------------------------------------------
+
+export interface PreviewEdge {
+ id: string;
+ /** Channel outline as drawn, a closed polygon in chip mm. */
+ nominal: Point2[];
+ /** Channel outline after compensation. */
+ compensated: Point2[];
+ /** True when compensation moved this channel's walls. */
+ changed: boolean;
+ /** True when a conflict names this segment. */
+ conflict: boolean;
+}
+
+export interface PreviewCircle {
+ id: string;
+ kind: 'joint' | 'chamber' | 'vent' | 'port';
+ x: number;
+ y: number;
+ nominalRadiusMm: number;
+ compensatedRadiusMm: number;
+ changed: boolean;
+ conflict: boolean;
+}
+
+export interface DfmPreviewModel {
+ chip: { width: number; length: number; baseThickness: number };
+ edges: PreviewEdge[];
+ circles: PreviewCircle[];
+ /** Where each conflict is, for a marker. */
+ conflictMarks: { id: string; kind: DfmConflictKind; x: number; y: number }[];
+}
+
+const EPS = 1e-9;
+
+function outline(samples: LoftSample[]): Point2[] {
+ const left: Point2[] = [];
+ const right: Point2[] = [];
+ for (const sample of samples) {
+ const half = sample.widthMm / 2;
+ // The channel's width is laid off along the normal to its path.
+ const nx = -sample.tangent.y;
+ const ny = sample.tangent.x;
+ left.push({ x: sample.point.x + nx * half, y: sample.point.y + ny * half });
+ right.push({ x: sample.point.x - nx * half, y: sample.point.y - ny * half });
+ }
+ return [...left, ...right.reverse()];
+}
+
+function jointRadii(graph: ChannelGraph, loft: LoftSolution): Map {
+ const adjacency = buildAdjacency(graph.edges);
+ const radii = new Map();
+ for (const node of graph.nodes) {
+ const touching = edgesFrom(adjacency, node.id);
+ if (touching.length < 2 || node.type === 'chamber') continue;
+ const sample = sampleAtNode(loft, touching[0], node.id);
+ if (sample) radii.set(node.id, sample.widthMm / 2);
+ }
+ return radii;
+}
+
+export function buildDfmPreview(
+ nominal: NominalDesign,
+ compensated: CompensatedDesign,
+): DfmPreviewModel {
+ const before = getLoft(nominal.graph, withChannelPlane(nominal.chipParams));
+ const after = getLoft(compensated.graph, withChannelPlane(compensated.chipParams));
+
+ const conflictEdges = new Set(compensated.conflicts.flatMap((c) => c.edgeIds));
+ const conflictNodes = new Set(compensated.conflicts.flatMap((c) => c.nodeIds));
+ // A ceiling raise changes every channel even where no wall moved.
+ const raised = compensated.ceilingRaiseMm > 0;
+
+ const edges: PreviewEdge[] = [];
+ for (const edge of nominal.graph.edges) {
+ const a = before.edges.get(edge.id)?.samples;
+ const b = after.edges.get(edge.id)?.samples;
+ if (!a || !b || a.length < 2) continue;
+ const widened = a.some((sample, i) => Math.abs((b[i]?.widthMm ?? sample.widthMm) - sample.widthMm) > EPS);
+ edges.push({
+ id: edge.id,
+ nominal: outline(a),
+ compensated: outline(b),
+ changed: widened || raised,
+ conflict: conflictEdges.has(edge.id),
+ });
+ }
+
+ const circles: PreviewCircle[] = [];
+ const jointsBefore = jointRadii(nominal.graph, before);
+ const jointsAfter = jointRadii(compensated.graph, after);
+ const nodesAfter = new Map(compensated.graph.nodes.map((n) => [n.id, n]));
+
+ for (const node of nominal.graph.nodes) {
+ const joint = jointsBefore.get(node.id);
+ if (joint !== undefined) {
+ const next = jointsAfter.get(node.id) ?? joint;
+ circles.push({
+ id: `joint:${node.id}`,
+ kind: 'joint',
+ x: node.x,
+ y: node.y,
+ nominalRadiusMm: joint,
+ compensatedRadiusMm: next,
+ changed: Math.abs(next - joint) > EPS || raised,
+ conflict: false,
+ });
+ }
+
+ if (node.type === 'chamber') {
+ const next = nodesAfter.get(node.id);
+ const size = next?.type === 'chamber' ? next.sizeMm : node.sizeMm;
+ circles.push({
+ id: `chamber:${node.id}`,
+ kind: 'chamber',
+ x: node.x,
+ y: node.y,
+ nominalRadiusMm: node.sizeMm / 2,
+ compensatedRadiusMm: size / 2,
+ changed: Math.abs(size - node.sizeMm) > EPS || raised,
+ conflict: conflictNodes.has(node.id),
+ });
+ } else if (node.type === 'port') {
+ // Ports are not compensated; they are drawn so the picture is the chip.
+ circles.push({
+ id: `port:${node.id}`,
+ kind: 'port',
+ x: node.x,
+ y: node.y,
+ nominalRadiusMm: node.diameterMm / 2,
+ compensatedRadiusMm: node.diameterMm / 2,
+ changed: false,
+ conflict: false,
+ });
+ }
+ }
+
+ const ventsAfter = new Map(compensated.drainageVents.map((v) => [v.id, v]));
+ const nodesBefore = new Map(nominal.graph.nodes.map((n) => [n.id, n]));
+ for (const vent of nominal.drainageVents) {
+ const node = nodesBefore.get(vent.nodeId);
+ if (!node) continue;
+ const next = ventsAfter.get(vent.id)?.diameterMm ?? vent.diameterMm;
+ circles.push({
+ id: `vent:${vent.id}`,
+ kind: 'vent',
+ x: node.x,
+ y: node.y,
+ nominalRadiusMm: vent.diameterMm / 2,
+ compensatedRadiusMm: next / 2,
+ changed: Math.abs(next - vent.diameterMm) > EPS,
+ conflict: false,
+ });
+ }
+
+ return {
+ chip: {
+ width: nominal.chipParams.width,
+ length: nominal.chipParams.length,
+ baseThickness: nominal.chipParams.baseThickness,
+ },
+ edges,
+ circles,
+ conflictMarks: compensated.conflicts
+ .filter((c) => c.focus)
+ .map((c) => ({ id: c.id, kind: c.kind, x: c.focus!.x, y: c.focus!.y })),
+ };
+}
+
+// ---------------------------------------------------------------------------
+// cross-sections
+// ---------------------------------------------------------------------------
+
+/** One channel profile in the slice plane: `s` along the slice line, `z` up. */
+export interface SectionShape {
+ widthMm: number;
+ heightMm: number;
+ floorZ: number;
+ ceilingZ: number;
+ /** Closed polygon. */
+ points: { s: number; z: number }[];
+}
+
+export interface DfmSection {
+ edgeId: string;
+ crossSection: CrossSection;
+ /** Where the slice line meets this channel's centreline, mm along the line. */
+ alongMm: number;
+ /**
+ * How much the channel's width is stretched in this view because the slice
+ * crosses it at an angle. 1 for a square cut. The `widthMm` of each shape is
+ * the true width; only `points` carry the stretch.
+ */
+ obliqueStretch: number;
+ nominal: SectionShape;
+ compensated: SectionShape;
+ conflict: boolean;
+}
+
+/** `x` slices along the plane x = position; `y` along y = position. */
+export type SliceAxis = 'x' | 'y';
+
+const SECTION_SEGMENTS = 32;
+/** A slice nearly parallel to a channel would stretch it without limit. */
+const MAX_OBLIQUE_STRETCH = 5;
+
+function shape(
+ crossSection: CrossSection,
+ widthMm: number,
+ heightMm: number,
+ chipParams: ChipParams,
+ ceilingRaiseMm: number,
+ alongMm: number,
+ stretch: number,
+): SectionShape {
+ const place = placeChannel(crossSection, widthMm, heightMm, chipParams.splitHeight, ceilingRaiseMm);
+ const profile = profilePoints(crossSection, widthMm, heightMm, SECTION_SEGMENTS, ceilingRaiseMm);
+ return {
+ widthMm,
+ heightMm: place.halfHeight * 2 + place.ceilingRaiseMm,
+ floorZ: place.centerZ - place.halfHeight,
+ ceilingZ: ceilingZ(place),
+ points: profile.map((p) => ({ s: alongMm + p.u * stretch, z: place.centerZ + p.v })),
+ };
+}
+
+/**
+ * Every channel the slice line crosses, as drawn and as compensated.
+ *
+ * Crossings are found on the nominal centreline — compensation never moves a
+ * centreline — and the compensated size is read from the same station of the
+ * compensated loft.
+ */
+export function sliceSections(
+ nominal: NominalDesign,
+ compensated: CompensatedDesign,
+ axis: SliceAxis,
+ positionMm: number,
+): DfmSection[] {
+ const chipBefore = withChannelPlane(nominal.chipParams);
+ const chipAfter = withChannelPlane(compensated.chipParams);
+ const before = getLoft(nominal.graph, chipBefore);
+ const after = getLoft(compensated.graph, chipAfter);
+ const conflictEdges = new Set(compensated.conflicts.flatMap((c) => c.edgeIds));
+
+ const across = (p: Point2) => (axis === 'x' ? p.x : p.y);
+ const along = (p: Point2) => (axis === 'x' ? p.y : p.x);
+ const lerp = (a: number, b: number, t: number) => a + (b - a) * t;
+
+ const sections: DfmSection[] = [];
+
+ for (const edge of nominal.graph.edges) {
+ const a = before.edges.get(edge.id)?.samples;
+ const b = after.edges.get(edge.id)?.samples;
+ if (!a || !b || a.length !== b.length) continue;
+
+ for (let i = 0; i < a.length - 1; i += 1) {
+ const d0 = across(a[i].point) - positionMm;
+ const d1 = across(a[i + 1].point) - positionMm;
+ // Half-open, so a crossing exactly on a station is counted once.
+ if (!((d0 <= 0 && d1 > 0) || (d0 >= 0 && d1 < 0))) continue;
+
+ const t = d0 / (d0 - d1);
+ const alongMm = lerp(along(a[i].point), along(a[i + 1].point), t);
+ const tangent = {
+ x: lerp(a[i].tangent.x, a[i + 1].tangent.x, t),
+ y: lerp(a[i].tangent.y, a[i + 1].tangent.y, t),
+ };
+ const length = Math.hypot(tangent.x, tangent.y) || 1;
+ // Component of the path direction through the slice plane.
+ const through = Math.abs(axis === 'x' ? tangent.x : tangent.y) / length;
+ const obliqueStretch = Math.min(MAX_OBLIQUE_STRETCH, 1 / Math.max(through, 1e-6));
+
+ sections.push({
+ edgeId: edge.id,
+ crossSection: edge.crossSection,
+ alongMm,
+ obliqueStretch,
+ nominal: shape(
+ edge.crossSection,
+ lerp(a[i].widthMm, a[i + 1].widthMm, t),
+ lerp(a[i].heightMm, a[i + 1].heightMm, t),
+ chipBefore,
+ 0,
+ alongMm,
+ obliqueStretch,
+ ),
+ compensated: shape(
+ edge.crossSection,
+ lerp(b[i].widthMm, b[i + 1].widthMm, t),
+ lerp(b[i].heightMm, b[i + 1].heightMm, t),
+ chipAfter,
+ compensated.ceilingRaiseMm,
+ alongMm,
+ obliqueStretch,
+ ),
+ conflict: conflictEdges.has(edge.id),
+ });
+ }
+ }
+
+ return sections.sort((p, q) => p.alongMm - q.alongMm);
+}
diff --git a/src/lib/dfm/profile.test.ts b/src/lib/dfm/profile.test.ts
new file mode 100644
index 0000000..712fa2d
--- /dev/null
+++ b/src/lib/dfm/profile.test.ts
@@ -0,0 +1,189 @@
+/**
+ * Print-correction profile file tests: parse, validation messages, version
+ * handling, round-trip and the content hash.
+ */
+
+import assert from 'node:assert/strict';
+import { describe, it } from 'vitest';
+import {
+ DFM_SCHEMA_VERSION,
+ canonicalJson,
+ dfmProfileFileName,
+ hashDfmProfile,
+ parseDfmProfile,
+ serializeDfmProfile,
+} from './profile';
+import { makeProfile } from './testFixtures';
+
+const text = (mutate: (raw: Record) => void = () => {}): string => {
+ const raw = JSON.parse(serializeDfmProfile(makeProfile()));
+ mutate(raw);
+ return JSON.stringify(raw);
+};
+
+describe('profile round-trip', () => {
+ it('restores an identical profile', () => {
+ const profile = makeProfile();
+ const parsed = parseDfmProfile(serializeDfmProfile(profile));
+ assert.equal(parsed.ok, true);
+ if (!parsed.ok) return;
+ assert.deepEqual(parsed.profile, profile);
+ });
+
+ it('survives repeated save/load cycles without drift', () => {
+ let current = serializeDfmProfile(makeProfile());
+ for (let i = 0; i < 3; i += 1) {
+ const parsed = parseDfmProfile(current);
+ assert.equal(parsed.ok, true);
+ if (!parsed.ok) return;
+ const next = serializeDfmProfile(parsed.profile);
+ assert.equal(next, current);
+ current = next;
+ }
+ });
+
+ it('keeps the raw coupon measurements, so the profile can be re-fitted', () => {
+ const parsed = parseDfmProfile(serializeDfmProfile(makeProfile()));
+ assert.equal(parsed.ok, true);
+ if (!parsed.ok) return;
+ assert.equal(parsed.profile.measurements.length, 2);
+ assert.equal(parsed.profile.measurements[1].measuredWidthMm, 0);
+ assert.equal(parsed.profile.coupon.version, 1);
+ });
+
+ it('preserves fields it does not know about', () => {
+ const parsed = parseDfmProfile(text((raw) => Object.assign(raw.meta, { operator: 'JC' })));
+ assert.equal(parsed.ok, true);
+ if (!parsed.ok) return;
+ assert.match(serializeDfmProfile(parsed.profile), /"operator": "JC"/);
+ });
+
+ it('defaults what an older or hand-written file leaves out', () => {
+ const parsed = parseDfmProfile(
+ text((raw) => {
+ delete (raw.compensation as Record).lateralDecayMm;
+ delete (raw.compensation as Record).snapToPixelGrid;
+ delete (raw as Record).fit;
+ delete (raw.meta as Record).exposure;
+ }),
+ );
+ assert.equal(parsed.ok, true);
+ if (!parsed.ok) return;
+ assert.equal(parsed.profile.compensation.lateralDecayMm, 0);
+ assert.equal(parsed.profile.compensation.snapToPixelGrid, false);
+ assert.equal(parsed.profile.fit.lateral.method, 'manual');
+ assert.equal(parsed.profile.meta.exposure.normalExposureS, null);
+ });
+
+ it('derives a filesystem-safe filename', () => {
+ assert.equal(dfmProfileFileName('Mars 4 / clear @ 2.5 s'), 'Mars-4-clear-25-s.ocdfm');
+ assert.equal(dfmProfileFileName(' '), 'print-correction.ocdfm');
+ });
+});
+
+describe('malformed profiles produce clear errors', () => {
+ it('rejects an empty file', () => {
+ const result = parseDfmProfile(' ');
+ assert.equal(result.ok, false);
+ if (result.ok) return;
+ assert.match(result.message, /empty/);
+ });
+
+ it('rejects invalid JSON and says so', () => {
+ const result = parseDfmProfile('{ "kind": ');
+ assert.equal(result.ok, false);
+ if (result.ok) return;
+ assert.match(result.message, /valid JSON/);
+ });
+
+ it('recognises a project file dropped in by mistake', () => {
+ const result = parseDfmProfile(JSON.stringify({ formatVersion: 1, channelGraph: {} }));
+ assert.equal(result.ok, false);
+ if (result.ok) return;
+ assert.match(result.message, /project, not a print-correction profile/);
+ });
+
+ it('names a missing section in plain language', () => {
+ const result = parseDfmProfile(text((raw) => delete (raw as Record).compensation));
+ assert.equal(result.ok, false);
+ if (result.ok) return;
+ assert.deepEqual(result.details, ['Compensation parameters is missing.']);
+ });
+
+ it('names the specific bad field', () => {
+ const result = parseDfmProfile(
+ text((raw) => Object.assign(raw.compensation, { deltaXyMm: -0.1, deltaZMm: 'lots' })),
+ );
+ assert.equal(result.ok, false);
+ if (result.ok) return;
+ assert.ok(
+ result.details.some((d) => /deltaXyMm.*cannot be negative/.test(d)),
+ result.details.join(' | '),
+ );
+ assert.ok(result.details.some((d) => /deltaZMm.*must be a number/.test(d)));
+ });
+
+ it('rejects a measurement with an unknown result', () => {
+ const result = parseDfmProfile(
+ text((raw) => Object.assign((raw.measurements as Record[])[0], { result: 'maybe' })),
+ );
+ assert.equal(result.ok, false);
+ if (result.ok) return;
+ assert.ok(result.details.some((d) => /open.*partial.*closed/.test(d)), result.details.join(' | '));
+ });
+
+ it('rejects a model it does not implement', () => {
+ const result = parseDfmProfile(text((raw) => Object.assign(raw.compensation, { model: 'voxel-v9' })));
+ assert.equal(result.ok, false);
+ if (result.ok) return;
+ assert.ok(result.details.some((d) => /edge-bleed-v1/.test(d)));
+ });
+});
+
+describe('profile version handling', () => {
+ it('refuses a newer schema with a readable message, not a crash', () => {
+ const result = parseDfmProfile(
+ text((raw) => Object.assign(raw, { schemaVersion: DFM_SCHEMA_VERSION + 1, compensation: 'reshaped' })),
+ );
+ assert.equal(result.ok, false);
+ if (result.ok) return;
+ assert.match(result.message, /newer version of OpenChip/);
+ assert.ok(result.details.some((d) => d.includes(`format ${DFM_SCHEMA_VERSION + 1}`)));
+ });
+
+ it('reads the current schema version', () => {
+ assert.equal(parseDfmProfile(text()).ok, true);
+ });
+
+ it('rejects a file with no version at all', () => {
+ const result = parseDfmProfile(text((raw) => delete (raw as Record).schemaVersion));
+ assert.equal(result.ok, false);
+ if (result.ok) return;
+ assert.ok(result.details.some((d) => /File header/.test(d)));
+ });
+});
+
+describe('content hash', () => {
+ it('is a 64-character hex SHA-256', async () => {
+ assert.match(await hashDfmProfile(makeProfile()), /^[0-9a-f]{64}$/);
+ });
+
+ it('ignores formatting and key order', async () => {
+ const profile = makeProfile();
+ const reversed = Object.fromEntries(Object.entries(profile).reverse());
+ const reordered = JSON.parse(JSON.stringify(reversed, null, 8));
+ assert.notDeepEqual(Object.keys(reordered), Object.keys(profile));
+ assert.equal(await hashDfmProfile(reordered), await hashDfmProfile(profile));
+ });
+
+ it('changes when any parameter changes', async () => {
+ assert.notEqual(
+ await hashDfmProfile(makeProfile({ deltaXyMm: 0.051 })),
+ await hashDfmProfile(makeProfile()),
+ );
+ });
+
+ it('writes canonical JSON with sorted keys', () => {
+ assert.equal(canonicalJson({ b: 1, a: [{ d: null, c: 'x' }] }), '{"a":[{"c":"x","d":null}],"b":1}');
+ });
+});
diff --git a/src/lib/dfm/profile.ts b/src/lib/dfm/profile.ts
new file mode 100644
index 0000000..a94afc7
--- /dev/null
+++ b/src/lib/dfm/profile.ts
@@ -0,0 +1,398 @@
+/**
+ * The print-correction profile: a `.ocdfm` file.
+ *
+ * A profile describes how one printer, with one resin at one set of exposure
+ * settings, departs from the geometry it is asked to print — and carries the
+ * coupon measurements that description was fitted from. It is deliberately a
+ * file of its own rather than a section of `.openchip`:
+ *
+ * - it belongs to a machine and a bottle of resin, not to a chip, so one
+ * profile serves every design printed on that setup;
+ * - it can be shared with a colleague running the same printer without
+ * sharing a design;
+ * - a design file that never mentions it stays a description of the *nominal*
+ * chip, which is what a paper cites and what a different printer needs.
+ *
+ * Units are in the field names, as in the project file: `Mm` is millimetres,
+ * `Microns` is micrometres, `S` is seconds.
+ *
+ * Like `projectFile.ts`, this module is free of React and of storage: it turns
+ * text into a validated profile and back.
+ */
+
+import * as z from 'zod';
+
+export const DFM_PROFILE_EXTENSION = '.ocdfm';
+export const DFM_PROFILE_MIME = 'application/json';
+/** Marks the file as a profile, so a renamed project file is not mistaken for one. */
+export const DFM_PROFILE_KIND = 'openchip-dfm-profile';
+/** Bumped when the on-disk shape changes in a way an older build cannot read. */
+export const DFM_SCHEMA_VERSION = 1;
+/** The compensation model this build fits and applies. See `model.ts`. */
+export const DFM_MODEL_ID = 'edge-bleed-v1';
+
+// ---------------------------------------------------------------------------
+// types
+// ---------------------------------------------------------------------------
+
+export type ChannelResult = 'open' | 'partial' | 'closed';
+
+/** One coupon channel as the user found it. */
+export interface CouponMeasurement {
+ /** `group.index`, as printed on the measurement sheet, e.g. `2.3`. */
+ id: string;
+ /** Width the channel was drawn at, mm. */
+ nominalWidthMm: number;
+ /** Height the channel was drawn at, mm. */
+ nominalHeightMm: number;
+ /** Null when the channel was not checked. */
+ result: ChannelResult | null;
+ /** Width actually measured, mm. Optional — a microscope is not assumed. */
+ measuredWidthMm?: number;
+ /** Height actually measured, mm. */
+ measuredHeightMm?: number;
+}
+
+export type FitMethod = 'measured' | 'open-closed' | 'manual' | 'none';
+
+/** How one axis of the fit was arrived at, and what it rests on. */
+export interface AxisFit {
+ method: FitMethod;
+ /** Channels that informed this axis. */
+ dataPoints: number;
+ /** RMS residual of a `measured` fit, mm. */
+ rmsMm?: number;
+ /**
+ * The interval an `open-closed` fit can place the offset in, mm. The upper
+ * end is null when nothing in the coupon stayed open to bound it.
+ */
+ bracketMm?: [number, number | null];
+ /** Channels an `open-closed` fit could not reconcile with any threshold. */
+ inconsistent?: number;
+}
+
+export interface DfmCompensation {
+ model: typeof DFM_MODEL_ID;
+ /** Lateral bleed per side on an isolated edge, mm. */
+ deltaXyMm: number;
+ /**
+ * Decay length of the stray dose across a channel, mm. Zero makes the lateral
+ * offset the same at every width; above zero, narrow channels lose more.
+ */
+ lateralDecayMm: number;
+ /** Vertical cure-through into a channel ceiling, mm. */
+ deltaZMm: number;
+ /** Round compensated widths to whole pixels, when the pixel size is known. */
+ snapToPixelGrid: boolean;
+}
+
+export interface DfmProfileMeta {
+ name: string;
+ printerModel: string;
+ resin: string;
+ layerHeightMicrons: number;
+ /** As entered. Nothing here is used by the model; it identifies the setup. */
+ exposure: {
+ normalExposureS: number | null;
+ bottomExposureS: number | null;
+ bottomLayers: number | null;
+ /** Anything else worth recording: lift speed, rest time, light-off delay. */
+ other: string;
+ };
+ /** XY pixel pitch, microns. Null when unknown. */
+ xyPixelMicrons: number | null;
+ /** ISO-8601 timestamp. */
+ createdAt: string;
+ notes: string;
+}
+
+export interface DfmCouponInfo {
+ /** Version of the coupon layout the measurements came from. */
+ version: number;
+ widthsMm: number[];
+ heightsMm: number[];
+}
+
+export interface DfmProfile {
+ kind: typeof DFM_PROFILE_KIND;
+ schemaVersion: number;
+ meta: DfmProfileMeta;
+ compensation: DfmCompensation;
+ fit: { lateral: AxisFit; vertical: AxisFit };
+ coupon: DfmCouponInfo;
+ /** Kept in full so the profile can be re-fitted when the model improves. */
+ measurements: CouponMeasurement[];
+}
+
+/** What a `.openchip` file may remember about the profile it was last exported with. */
+export interface DfmProfileRef {
+ name: string;
+ sha256: string;
+}
+
+// ---------------------------------------------------------------------------
+// schema
+// ---------------------------------------------------------------------------
+
+const finite = (label: string) =>
+ z.number({ error: `${label} must be a number` }).finite(`${label} must be a real number`);
+const positive = (label: string) => finite(label).positive(`${label} must be greater than zero`);
+const nonNegative = (label: string) => finite(label).nonnegative(`${label} cannot be negative`);
+
+const resultSchema = z
+ .enum(['open', 'partial', 'closed'], { error: "result must be 'open', 'partial' or 'closed'" })
+ .nullable()
+ .default(null);
+
+const measurementSchema = z.looseObject({
+ id: z.string({ error: 'channel id must be text' }).min(1, 'channel id cannot be empty'),
+ nominalWidthMm: positive('nominal width'),
+ nominalHeightMm: positive('nominal height'),
+ result: resultSchema,
+ measuredWidthMm: nonNegative('measured width').optional(),
+ measuredHeightMm: nonNegative('measured height').optional(),
+});
+
+const axisFitSchema = z.looseObject({
+ method: z
+ .enum(['measured', 'open-closed', 'manual', 'none'], {
+ error: "fit method must be 'measured', 'open-closed', 'manual' or 'none'",
+ })
+ .default('manual'),
+ dataPoints: nonNegative('fit data points').default(0),
+ rmsMm: nonNegative('fit residual').optional(),
+ bracketMm: z.tuple([finite('bracket'), finite('bracket').nullable()]).optional(),
+ inconsistent: nonNegative('inconsistent channels').optional(),
+});
+
+const freshAxisFit = (): AxisFit & Record => ({ method: 'manual', dataPoints: 0 });
+
+const profileSchema = z.looseObject({
+ kind: z.literal(DFM_PROFILE_KIND, {
+ error: 'this is not an OpenChip print-correction profile',
+ }),
+ schemaVersion: z.number().int('schema version must be a whole number').positive(),
+ meta: z.looseObject({
+ name: z.string({ error: 'profile name must be text' }).min(1, 'profile name cannot be empty'),
+ printerModel: z.string({ error: 'printer model must be text' }).default(''),
+ resin: z.string({ error: 'resin must be text' }).default(''),
+ layerHeightMicrons: positive('layer height'),
+ exposure: z
+ .looseObject({
+ normalExposureS: nonNegative('normal exposure').nullable().default(null),
+ bottomExposureS: nonNegative('bottom exposure').nullable().default(null),
+ bottomLayers: nonNegative('bottom layer count').nullable().default(null),
+ other: z.string().default(''),
+ })
+ .default({ normalExposureS: null, bottomExposureS: null, bottomLayers: null, other: '' }),
+ xyPixelMicrons: positive('XY pixel size').nullable().default(null),
+ createdAt: z
+ .string({ error: 'creation date must be a date string' })
+ .refine((v) => !Number.isNaN(Date.parse(v)), {
+ error: 'creation date must be an ISO-8601 date string',
+ }),
+ notes: z.string().default(''),
+ }),
+ compensation: z.looseObject({
+ model: z.literal(DFM_MODEL_ID, {
+ error: `compensation model must be '${DFM_MODEL_ID}'`,
+ }),
+ deltaXyMm: nonNegative('lateral offset (deltaXyMm)'),
+ lateralDecayMm: nonNegative('lateral decay length (lateralDecayMm)').default(0),
+ deltaZMm: nonNegative('vertical offset (deltaZMm)'),
+ snapToPixelGrid: z.boolean({ error: 'snapToPixelGrid must be true or false' }).default(false),
+ }),
+ fit: z
+ .looseObject({
+ lateral: axisFitSchema.default(freshAxisFit),
+ vertical: axisFitSchema.default(freshAxisFit),
+ })
+ .default(() => ({ lateral: freshAxisFit(), vertical: freshAxisFit() })),
+ coupon: z.looseObject({
+ version: z.number().int('coupon version must be a whole number').positive(),
+ widthsMm: z.array(positive('coupon width')).default([]),
+ heightsMm: z.array(positive('coupon height')).default([]),
+ }),
+ measurements: z.array(measurementSchema, { error: 'measurements must be a list' }).default([]),
+});
+
+// ---------------------------------------------------------------------------
+// parse
+// ---------------------------------------------------------------------------
+
+export interface DfmParseSuccess {
+ ok: true;
+ profile: DfmProfile;
+}
+
+export interface DfmParseFailure {
+ ok: false;
+ /** One-line summary for a toast. */
+ message: string;
+ /** Specific, actionable problems. May be empty. */
+ details: string[];
+}
+
+export type DfmParseResult = DfmParseSuccess | DfmParseFailure;
+
+const SECTION_LABELS: Record = {
+ kind: 'File header',
+ schemaVersion: 'File header',
+ meta: 'Profile info',
+ compensation: 'Compensation parameters',
+ fit: 'Fit summary',
+ coupon: 'Coupon',
+ measurements: 'Coupon measurements',
+};
+
+/** The value a zod issue path points at in the raw file, or undefined. */
+function valueAt(raw: unknown, path: PropertyKey[]): unknown {
+ let current = raw;
+ for (const key of path) {
+ if (current === null || typeof current !== 'object') return undefined;
+ current = (current as Record)[key];
+ }
+ return current;
+}
+
+function describe(error: z.ZodError, raw: unknown, limit = 6): string[] {
+ const lines: string[] = [];
+ for (const issue of error.issues) {
+ const [head, ...rest] = issue.path;
+ const section = typeof head === 'string' ? (SECTION_LABELS[head] ?? head) : 'File';
+ const field = rest.join('.');
+ // Zod reports a missing key as a type error against `undefined`, and does
+ // not include the offending value in the issue. Looking the path up in the
+ // file is what tells "absent" from "present but the wrong type".
+ const absent = issue.code === 'invalid_type' && valueAt(raw, issue.path) === undefined;
+ const line = absent
+ ? field
+ ? `${section}: "${field}" is missing.`
+ : `${section} is missing.`
+ : field
+ ? `${section} → ${field}: ${issue.message}`
+ : `${section}: ${issue.message}`;
+ if (!lines.includes(line)) lines.push(line);
+ if (lines.length >= limit) break;
+ }
+ const remaining = error.issues.length - lines.length;
+ if (remaining > 0) lines.push(`…and ${remaining} more problem${remaining === 1 ? '' : 's'}.`);
+ return lines;
+}
+
+export function parseDfmProfile(text: string): DfmParseResult {
+ if (text.trim().length === 0) {
+ return { ok: false, message: 'That file is empty.', details: [] };
+ }
+
+ let raw: unknown;
+ try {
+ raw = JSON.parse(text);
+ } catch (error) {
+ return {
+ ok: false,
+ message: "That file isn't valid JSON, so it can't be read as a print-correction profile.",
+ details: [error instanceof Error ? error.message : String(error)],
+ };
+ }
+
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) {
+ return {
+ ok: false,
+ message: "That file isn't a print-correction profile.",
+ details: ['The file parsed as JSON, but it is not a profile object.'],
+ };
+ }
+
+ const record = raw as Record;
+
+ // A project file dropped here is the likeliest mistake, and "kind is missing"
+ // would not tell anyone what they did.
+ if (record.kind !== DFM_PROFILE_KIND && 'channelGraph' in record) {
+ return {
+ ok: false,
+ message: 'That is an OpenChip project, not a print-correction profile.',
+ details: [`Profiles end in ${DFM_PROFILE_EXTENSION}. Open a project from Project → Open Project.`],
+ };
+ }
+
+ // Unlike a project file, a newer profile is refused rather than opened with
+ // its unknown parts ignored. A project's unknown fields are things this build
+ // does not draw; a profile's would be terms of a model this build does not
+ // apply, and exporting with half a correction is worse than exporting none.
+ const version = record.schemaVersion;
+ if (typeof version === 'number' && version > DFM_SCHEMA_VERSION) {
+ return {
+ ok: false,
+ message: 'That profile was saved by a newer version of OpenChip.',
+ details: [
+ `It uses profile format ${version}; this build reads up to format ${DFM_SCHEMA_VERSION}.`,
+ 'Update OpenChip to use it. Nothing was changed.',
+ ],
+ };
+ }
+
+ const result = profileSchema.safeParse(raw);
+ if (!result.success) {
+ return {
+ ok: false,
+ message: "That profile is missing or has invalid data, so it wasn't loaded.",
+ details: describe(result.error as z.ZodError, raw),
+ };
+ }
+
+ return { ok: true, profile: result.data as unknown as DfmProfile };
+}
+
+// ---------------------------------------------------------------------------
+// serialise
+// ---------------------------------------------------------------------------
+
+/** Pretty-printed JSON, like a project file. */
+export function serializeDfmProfile(profile: DfmProfile): string {
+ return `${JSON.stringify(profile, null, 2)}\n`;
+}
+
+/** Filesystem-safe filename derived from the profile name. */
+export function dfmProfileFileName(name: string): string {
+ const base = name
+ .trim()
+ .replace(/[^a-zA-Z0-9-_ ]+/g, '')
+ .replace(/\s+/g, '-')
+ .replace(/-+/g, '-')
+ .replace(/^-|-$/g, '')
+ .slice(0, 60);
+ return `${base || 'print-correction'}${DFM_PROFILE_EXTENSION}`;
+}
+
+// ---------------------------------------------------------------------------
+// content hash
+// ---------------------------------------------------------------------------
+
+/**
+ * The profile as text with object keys in a fixed order and no whitespace.
+ *
+ * Hashing this rather than the file's bytes means re-indenting a profile, or
+ * passing it through a tool that reorders keys, does not make it a "different"
+ * profile — only a change to its contents does.
+ */
+export function canonicalJson(value: unknown): string {
+ if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`;
+ if (value !== null && typeof value === 'object') {
+ const entries = Object.entries(value as Record)
+ .filter(([, v]) => v !== undefined)
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
+ return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonicalJson(v)}`).join(',')}}`;
+ }
+ return JSON.stringify(value);
+}
+
+/** SHA-256 of the profile's canonical form, as lowercase hex. */
+export async function hashDfmProfile(profile: DfmProfile): Promise {
+ const bytes = new TextEncoder().encode(canonicalJson(profile));
+ const digest = await crypto.subtle.digest('SHA-256', bytes);
+ return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, '0')).join('');
+}
+
+/** The first characters of a hash, for filenames and the 80-byte STL header. */
+export const shortHash = (sha256: string): string => sha256.slice(0, 12);
diff --git a/src/lib/dfm/testFixtures.ts b/src/lib/dfm/testFixtures.ts
new file mode 100644
index 0000000..ff6b8b9
--- /dev/null
+++ b/src/lib/dfm/testFixtures.ts
@@ -0,0 +1,85 @@
+/**
+ * Shared fixtures for the print-correction tests. Not imported by the app.
+ */
+
+import { DEFAULT_CHIP_PARAMS, FALLBACK_PRINTER_PROFILE } from '../defaults';
+import type { ChannelGraph, ChipParams } from '../../types/project';
+import type { NominalDesign } from './compensate';
+import { DFM_MODEL_ID, DFM_PROFILE_KIND, DFM_SCHEMA_VERSION, type DfmProfile } from './profile';
+
+export function makeProfile(
+ compensation: Partial = {},
+ meta: Partial = {},
+): DfmProfile {
+ return {
+ kind: DFM_PROFILE_KIND,
+ schemaVersion: DFM_SCHEMA_VERSION,
+ meta: {
+ name: 'Bench printer, clear resin',
+ printerModel: 'Standard 4K',
+ resin: 'Clear',
+ layerHeightMicrons: 50,
+ exposure: { normalExposureS: 2.5, bottomExposureS: 30, bottomLayers: 5, other: '' },
+ xyPixelMicrons: 35,
+ createdAt: '2026-01-15T10:00:00.000Z',
+ notes: '',
+ ...meta,
+ },
+ compensation: {
+ model: DFM_MODEL_ID,
+ deltaXyMm: 0.05,
+ lateralDecayMm: 0,
+ deltaZMm: 0.1,
+ snapToPixelGrid: false,
+ ...compensation,
+ },
+ fit: {
+ lateral: { method: 'manual', dataPoints: 0 },
+ vertical: { method: 'manual', dataPoints: 0 },
+ },
+ coupon: { version: 1, widthsMm: [0.2, 0.4], heightsMm: [0.2, 0.4] },
+ measurements: [
+ { id: '1.1', nominalWidthMm: 0.4, nominalHeightMm: 0.2, result: 'open' },
+ { id: '1.2', nominalWidthMm: 0.2, nominalHeightMm: 0.2, result: 'closed', measuredWidthMm: 0 },
+ ],
+ };
+}
+
+/** Two straight parallel channels along X, `pitchMm` apart centre to centre. */
+export function parallelChannels(pitchMm: number): ChannelGraph {
+ return {
+ nodes: [
+ { id: 'a1', x: 10, y: 20, type: 'waypoint' },
+ { id: 'a2', x: 30, y: 20, type: 'waypoint' },
+ { id: 'b1', x: 10, y: 20 + pitchMm, type: 'waypoint' },
+ { id: 'b2', x: 30, y: 20 + pitchMm, type: 'waypoint' },
+ ],
+ edges: [
+ {
+ id: 'ea',
+ fromNodeId: 'a1',
+ toNodeId: 'a2',
+ curveType: 'straight',
+ crossSection: 'rect',
+ dimensionPoints: [],
+ },
+ {
+ id: 'eb',
+ fromNodeId: 'b1',
+ toNodeId: 'b2',
+ curveType: 'straight',
+ crossSection: 'rect',
+ dimensionPoints: [],
+ },
+ ],
+ };
+}
+
+export function design(graph: ChannelGraph, chipParams: Partial = {}): NominalDesign {
+ return {
+ graph,
+ chipParams: { ...DEFAULT_CHIP_PARAMS, ...chipParams },
+ drainageVents: [],
+ printerProfile: FALLBACK_PRINTER_PROFILE,
+ };
+}
diff --git a/src/lib/persistence.ts b/src/lib/persistence.ts
index d6ffab3..de620e8 100644
--- a/src/lib/persistence.ts
+++ b/src/lib/persistence.ts
@@ -26,6 +26,7 @@ import type { PersistStorage, StateStorage, StorageValue } from 'zustand/middlew
export const SETTINGS_STORAGE_KEY = 'openchip.settings.v1';
export const DRAFT_STORAGE_KEY = 'openchip.draft.v1';
export const CHECK_SETTINGS_STORAGE_KEY = 'openchip.check-settings.v1';
+export const DFM_STORAGE_KEY = 'openchip.dfm.v1';
// ---------------------------------------------------------------------------
// safe localStorage
diff --git a/src/lib/schema.ts b/src/lib/schema.ts
index 964ea20..41a1f5c 100644
--- a/src/lib/schema.ts
+++ b/src/lib/schema.ts
@@ -219,6 +219,15 @@ export const projectSchema = z.looseObject({
// Added later; files written before it must still open.
drainageVents: z.array(drainageVentSchema).default([]),
presetLibraryRef: z.string().nullable().default(null),
+ // Optional and never defaulted: a file that has not been exported with a
+ // print-correction profile carries no trace of the feature, so it saves back
+ // exactly as it was.
+ dfmProfileRef: z
+ .looseObject({
+ name: z.string({ error: 'profile name must be text' }),
+ sha256: z.string({ error: 'profile hash must be text' }),
+ })
+ .optional(),
});
// ---------------------------------------------------------------------------
@@ -269,6 +278,7 @@ const SECTION_LABELS: Record = {
channelGraph: 'Channel network',
fluidProfiles: 'Fluid profiles',
savedImages: 'Saved images',
+ dfmProfileRef: 'Print-correction reference',
formatVersion: 'File header',
};
diff --git a/src/lib/wikiLinks.ts b/src/lib/wikiLinks.ts
index 815b43d..b67a943 100644
--- a/src/lib/wikiLinks.ts
+++ b/src/lib/wikiLinks.ts
@@ -78,6 +78,8 @@ export const CONTEXT_LINKS = {
fileFormat: '/reference/file-format/',
/** The dimension tool. */
dimensionMarkers: '/guide/dimension-markers/',
+ /** The print-correction selector, the preview panel and the calibration dialog. */
+ printCorrection: '/printing/print-correction/',
} as const;
export type ContextLink = keyof typeof CONTEXT_LINKS;
diff --git a/src/store/cadStore.ts b/src/store/cadStore.ts
index 07b30bc..39a262a 100644
--- a/src/store/cadStore.ts
+++ b/src/store/cadStore.ts
@@ -87,6 +87,8 @@ interface CadState {
graph: ChannelGraph,
chipParams: ChipParams,
drainageVents?: DrainageVent[],
+ /** Print-correction ceiling raise, mm. Zero for a nominal export. */
+ ceilingRaiseMm?: number,
) => Promise;
dispose: () => void;
}
@@ -200,7 +202,7 @@ export const useCadStore = create()((set) => ({
w.postMessage(request);
},
- buildForExport: (graph, chipParams, drainageVents = []) =>
+ buildForExport: (graph, chipParams, drainageVents = [], ceilingRaiseMm = 0) =>
new Promise((resolve, reject) => {
const w = ensureWorker(set);
seq += 1;
@@ -218,6 +220,7 @@ export const useCadStore = create()((set) => ({
quality: 2,
drainageVents,
includeChannelSolid: false,
+ ceilingRaiseMm,
};
w.postMessage(request);
diff --git a/src/store/dfmStore.ts b/src/store/dfmStore.ts
new file mode 100644
index 0000000..02b04e2
--- /dev/null
+++ b/src/store/dfmStore.ts
@@ -0,0 +1,93 @@
+/**
+ * Print correction: the profiles loaded into this browser, and which one — if
+ * any — the next export uses.
+ *
+ * Like `settingsStore`, nothing here is written into a `.openchip` file. A
+ * profile belongs to a printer and a resin, so it is kept with the browser's
+ * own setup and reused across every project opened in it.
+ *
+ * Only the library persists. The selection deliberately does not: every
+ * session starts on "None (uncompensated)", so a compensated export is always
+ * something the user chose this time rather than something left switched on
+ * last week.
+ */
+
+import { create } from 'zustand';
+import { createJSONStorage, persist } from 'zustand/middleware';
+import type { DfmEntry } from '../lib/dfm/exportPlan';
+import { hashDfmProfile, parseDfmProfile, type DfmProfile } from '../lib/dfm/profile';
+import { DFM_STORAGE_KEY, safeStorage } from '../lib/persistence';
+
+interface DfmState {
+ profiles: DfmEntry[];
+ /** Hash of the profile exports use. Null is "None (uncompensated)". */
+ selectedSha: string | null;
+ /** The compensated-geometry preview panel in the CAD sidebar. */
+ previewOpen: boolean;
+ /** The calibration dialog: coupon, results, fit. */
+ calibrationOpen: boolean;
+
+ /** Adds a profile to the library, or returns the entry already holding it. */
+ addProfile: (profile: DfmProfile) => Promise;
+ removeProfile: (sha256: string) => void;
+ select: (sha256: string | null) => void;
+ setPreviewOpen: (open: boolean) => void;
+ setCalibrationOpen: (open: boolean) => void;
+}
+
+export const useDfmStore = create()(
+ persist(
+ (set, get) => ({
+ profiles: [],
+ selectedSha: null,
+ previewOpen: false,
+ calibrationOpen: false,
+
+ addProfile: async (profile) => {
+ const sha256 = await hashDfmProfile(profile);
+ const existing = get().profiles.find((entry) => entry.sha256 === sha256);
+ if (existing) return existing;
+ const entry: DfmEntry = { profile, sha256 };
+ set((state) => ({ profiles: [...state.profiles, entry] }));
+ return entry;
+ },
+
+ removeProfile: (sha256) =>
+ set((state) => ({
+ profiles: state.profiles.filter((entry) => entry.sha256 !== sha256),
+ ...(state.selectedSha === sha256 ? { selectedSha: null, previewOpen: false } : {}),
+ })),
+
+ // Deselecting closes the preview with it: with no profile there is
+ // nothing compensated to look at.
+ select: (selectedSha) =>
+ set((state) => ({ selectedSha, previewOpen: selectedSha ? state.previewOpen : false })),
+
+ setPreviewOpen: (previewOpen) => set({ previewOpen }),
+ setCalibrationOpen: (calibrationOpen) => set({ calibrationOpen }),
+ }),
+ {
+ name: DFM_STORAGE_KEY,
+ storage: createJSONStorage(() => safeStorage),
+ partialize: (state) => ({ profiles: state.profiles }) as DfmState,
+ // Stored profiles go back through the file parser. One written by a
+ // newer build, or damaged, is dropped here rather than handed to an
+ // export that would apply half of it.
+ merge: (persisted, current) => {
+ const stored = (persisted as { profiles?: unknown } | undefined)?.profiles;
+ const profiles: DfmEntry[] = [];
+ for (const item of Array.isArray(stored) ? stored : []) {
+ const entry = item as { profile?: unknown; sha256?: unknown };
+ if (typeof entry?.sha256 !== 'string') continue;
+ const parsed = parseDfmProfile(JSON.stringify(entry.profile ?? null));
+ if (parsed.ok) profiles.push({ profile: parsed.profile, sha256: entry.sha256 });
+ }
+ return { ...current, profiles };
+ },
+ },
+ ),
+);
+
+/** The entry exports will use, or null for "None (uncompensated)". */
+export const selectedDfmEntry = (state: Pick): DfmEntry | null =>
+ state.profiles.find((entry) => entry.sha256 === state.selectedSha) ?? null;
diff --git a/src/store/projectStore.ts b/src/store/projectStore.ts
index ede546c..0fe0bd6 100644
--- a/src/store/projectStore.ts
+++ b/src/store/projectStore.ts
@@ -172,6 +172,12 @@ interface ProjectState extends ProjectStateData {
removeSavedImage: (id: string) => void;
/** Drainage holes. Replaces the whole list — it is small and edited wholesale. */
setDrainageVents: (vents: DrainageVent[]) => void;
+ /**
+ * Records which print-correction profile the project was last exported with.
+ * A note in the file, nothing more: it changes no geometry and is not an
+ * undo step. A no-op when the reference is already the same.
+ */
+ setDfmProfileRef: (ref: { name: string; sha256: string }) => void;
// --- fluids --------------------------------------------------------------
setFluidProfiles: (profiles: FluidProfile[]) => void;
@@ -508,6 +514,12 @@ export const useProjectStore = create()(
setDrainageVents: (vents) =>
edit((project) => ({ ...project, drainageVents: vents })),
+ setDfmProfileRef: (ref) => {
+ const current = get().project.dfmProfileRef;
+ if (current?.sha256 === ref.sha256 && current.name === ref.name) return;
+ edit((project) => ({ ...project, dfmProfileRef: { ...ref } }));
+ },
+
setFluidProfiles: (profiles) =>
edit((project) => ({ ...project, fluidProfiles: profiles })),
diff --git a/src/types/project.ts b/src/types/project.ts
index 4d86db9..29045c0 100644
--- a/src/types/project.ts
+++ b/src/types/project.ts
@@ -330,6 +330,14 @@ export interface OpenChipProject {
drainageVents: DrainageVent[];
/** Id of the starter template this project began from, if any. */
presetLibraryRef: string | null;
+ /**
+ * The print-correction profile this project was last exported with: its name
+ * and the SHA-256 of its contents. A convenience only — the profile itself
+ * lives in its own `.ocdfm` file and is never embedded here, the channel
+ * graph above is always the nominal design, and a project opens and exports
+ * normally when the profile it names is nowhere to be found.
+ */
+ dfmProfileRef?: { name: string; sha256: string };
}
// ---------------------------------------------------------------------------
diff --git a/src/workers/cadWorker.ts b/src/workers/cadWorker.ts
index d683584..7088c0f 100644
--- a/src/workers/cadWorker.ts
+++ b/src/workers/cadWorker.ts
@@ -28,6 +28,8 @@ export interface CadRequest {
drainageVents?: DrainageVent[];
/** Also return the cavity as a solid, for the viewport's isolate mode. */
includeChannelSolid?: boolean;
+ /** Print-correction ceiling raise, mm. Absent or zero for a nominal build. */
+ ceilingRaiseMm?: number;
}
export interface CadPiecePayload {
@@ -78,6 +80,7 @@ async function build(request: CadRequest): Promise {
quality: request.quality,
drainageVents: request.drainageVents,
includeChannelSolid: request.includeChannelSolid,
+ ceilingRaiseMm: request.ceilingRaiseMm,
});
// Sent even if a newer preview has arrived meanwhile: that one is next in