Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 79 additions & 0 deletions ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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/
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
29 changes: 29 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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
Expand All @@ -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-<profile>.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.
Expand Down
12 changes: 12 additions & 0 deletions skills/openchip-design/references/SCHEMA.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
105 changes: 89 additions & 16 deletions src/components/cad/CadPanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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<CadViewportHandle | null> }) {
Expand All @@ -25,6 +33,7 @@ export function CadPanel({ viewport }: { viewport: RefObject<CadViewportHandle |
<ChipParameters />
<SlideParameters />
<ExportSection viewport={viewport} />
<DfmCalibrationDialog />
</aside>
);
}
Expand Down Expand Up @@ -422,19 +431,64 @@ function ExportSection({ viewport }: { viewport: RefObject<CadViewportHandle | n
const addSavedImage = useProjectStore((s) => 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<string | null>(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<typeof plan>): 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);

Expand All @@ -443,13 +497,13 @@ function ExportSection({ viewport }: { viewport: RefObject<CadViewportHandle | n
return;
}

const suffix = which === 'all' ? '' : `-${which}`;
const buffer = exportStl(pieces, `OpenChip ${projectName}`);
const suffix = `${which === 'all' ? '' : `-${which}`}${planned.fileSuffix}`;
const buffer = exportStl(pieces, planned.stlHeader);
downloadBlob(buffer, `${slug}${suffix}.stl`, 'model/stl');

const tris = pieces.reduce((sum, p) => 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", {
Expand All @@ -463,10 +517,16 @@ function ExportSection({ viewport }: { viewport: RefObject<CadViewportHandle | n
const exportScadFile = () => {
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);
Expand Down Expand Up @@ -521,14 +581,25 @@ function ExportSection({ viewport }: { viewport: RefObject<CadViewportHandle | n
STL to print, OpenSCAD to keep editing.{' '}
<WikiLink to="exporting">Which format when</WikiLink>
</p>
<Button
size="sm"
icon={<Download size={14} />}
disabled={busy !== null || !model}
onClick={() => void exportStlFor('all')}
>
{busy === 'stl-all' ? 'Building…' : twoPiece ? 'STL — both pieces' : 'STL'}
</Button>

<DfmProfileSelect />
{dfm ? <DfmSummary dfm={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. */}
<div className={dfm ? 'grid grid-cols-[minmax(0,1fr)_auto] gap-1.5' : 'contents'}>
<Button
size="sm"
icon={<Download size={14} />}
disabled={busy !== null || !model}
className={dfm ? 'whitespace-nowrap px-2' : undefined}
onClick={() => void exportStlFor('all')}
>
{busy === 'stl-all' ? 'Building…' : twoPiece ? 'STL — both pieces' : 'STL'}
</Button>
{dfm ? <DfmPreviewToggle /> : null}
</div>

{twoPiece ? (
<div className="grid grid-cols-2 gap-2">
Expand Down Expand Up @@ -565,6 +636,8 @@ function ExportSection({ viewport }: { viewport: RefObject<CadViewportHandle | n
</p>
</Section>

{dfm && dfmPreviewOpen ? <DfmPreviewPanel dfm={dfm} /> : null}

<Section title="Snapshot">
<label className="flex items-center gap-2 text-[12px] text-ink">
<input
Expand Down
Loading
Loading