diff --git a/CHANGELOG.md b/CHANGELOG.md index 6905584..d8f5575 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,44 @@ # Changelog +## 0.13.2 (2026-12-03) + +New: + +- `$view = "assembled"` or `$view = "apart"` at the top level of a + program says how a flat picture of the design shows it: put together, + as a layered ornament looks best, or as its parts laid apart, as a box + does. `render()` gives it as `view`; without it the field is not + there and the viewer chooses. Like `$print` it is never a setting. + The files to cut and the 3D files are the same either way. + +Changes: + +- In the print layout (`--print`, `layout: "print"`) an object of several + parts that would need supports whichever way it lies, a print group or + a part with what is glued on it, prints as a few objects that do not. + A cabinet closed by its front used to be one object with a panel over + air: now its carcass and shelves are one object, lying on the back, + and the front another. The object is laid the way that keeps the most + of it whole, the parts that hang over air then are taken off with what + they hold, and those print together where they touch. The objects are + named after the group and their biggest part, as "cabinet - Back". An + object with less than 100 mm² over air, as the lintel of a small + window, stays whole, and so does every object that already printed + without supports and parts with `print = "each"`. `meshBodies()` and + `toModel()` take `split`: `false` keeps every object whole, a number + sets how much may hang over air, in mm². +- In the print layout an object no longer stands off the bed on its + engraving. A mark on a face turned down and nearer the bed than the + mark is high, as under a panel a hundredth of a millimetre above the + lowest edge, used to be made under the bed, which lifted the whole + object by the mark's height (0.6 mm with `--print`) and left all of it + over air. Such marks are left out, as marks on the bed face are. +- In the print layout a part that bends on a living hinge, in a print + group, is tried standing on its edge too, where it used to be tried + only on the faces of the group's parts. +- The print layout finds how an object lies faster, most of all for + models with much engraving, and `overhangs()` is faster. + ## 0.13.1 (2026-12-02) Changes: diff --git a/LANGUAGE.md b/LANGUAGE.md index ec27d88..ca903b9 100644 --- a/LANGUAGE.md +++ b/LANGUAGE.md @@ -212,6 +212,7 @@ module hang_hole(d = 5) { | `$join_lines` | `false` | join lines that meet end to end and order them nearest first, for less travel | | `$min_width` | `1.5` | warn where a part's material is narrower than this; `0` turns it off | | `$knob` | `12` | the size of the jigsaw knobs joining the pieces of a split part | +| `$view` | | at the top level: a flat picture shows the design `"assembled"` or `"apart"`; never a setting | | `$stands` | `false` | `true` for a model meant to stand: it warns if its weight's centre is not over what it stands on | | `$density` | `0.6` | the parts' density in g/cm³ for that check, plywood's by default | | `$knob_clearance` | `0.15` | the room between a knob and its socket | @@ -345,7 +346,9 @@ material(thickness = 4, kerf = 0.12, name = "birch") { the face away from the rest of it, so the cup stands on its bottom however the box is placed; if that would hang over air, it lies on a face of one of its biggest parts that needs clearly less support. A - part glued on another prints with it unless it has a print name of + group that needs support whichever way it lies prints as a few + objects that do not, each named after the group and its biggest + part. A part glued on another prints with it unless it has a print name of its own. `print = "each"` prints every copy of the part as an object of its own, joined only with the same copy of other parts with `print = "each"` that touch it: copy 3 of a chess piece's base with diff --git a/alias/package.json b/alias/package.json index 04f944d..ea5796f 100644 --- a/alias/package.json +++ b/alias/package.json @@ -1,6 +1,6 @@ { "name": "kerfscript", - "version": "0.13.1", + "version": "0.13.2", "description": "KerfScript: a programming language for laser cutting. Same package as @mylasertools/kerfscript.", "type": "module", "license": "AGPL-3.0-only", @@ -52,6 +52,6 @@ "node": ">=20" }, "dependencies": { - "@mylasertools/kerfscript": "0.13.1" + "@mylasertools/kerfscript": "0.13.2" } } diff --git a/desktop/src-tauri/Cargo.lock b/desktop/src-tauri/Cargo.lock index c514c79..73b49da 100644 --- a/desktop/src-tauri/Cargo.lock +++ b/desktop/src-tauri/Cargo.lock @@ -1958,7 +1958,7 @@ dependencies = [ [[package]] name = "kerfscript-desktop" -version = "0.13.1" +version = "0.13.2" dependencies = [ "hmac", "serde", diff --git a/desktop/src-tauri/Cargo.toml b/desktop/src-tauri/Cargo.toml index 20416bf..3311996 100644 --- a/desktop/src-tauri/Cargo.toml +++ b/desktop/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "kerfscript-desktop" -version = "0.13.1" +version = "0.13.2" description = "KerfScript: a programming language for laser cutting" authors = ["MyLaserTools"] license = "AGPL-3.0-only" diff --git a/docs/3d-files.md b/docs/3d-files.md index 1fe9b41..9b40b26 100644 --- a/docs/3d-files.md +++ b/docs/3d-files.md @@ -84,6 +84,25 @@ base. `print_on = "back"` or `"front"` names the face. A stack of parallel layers lies on its bigger end: a lid glued over a smaller insert prints on the lid. +An object of several parts that would need supports whichever way it +lies, a print group or a part with what is glued on it, prints as a few +objects that do not. A cabinet closed by its front has a panel over air +on every side, so its carcass and shelves print as one object, lying on +the back, and the front as another. The object is laid the way that +keeps the most of it whole, and the parts that hang over air then are +taken off it with what they hold; they print as an object of their own +where they touch, shared out again if they need it. Each object is named +after the group and its biggest part, as "cabinet - Back" and "cabinet - +Front", or after its biggest part alone where the parts were only glued. + +An object stays whole with less than 100 mm² over air, as the lintel of +a small window or the end of a finger, which print as short bridges. It +stays whole too where a little hangs under each of many parts, as round +a globe of layers, and where sharing it out would leave half as much +over air or more. Parts with `print = "each"` are not shared out. A +model of very many parts that cannot print joined, as a bowl of twisted +slats, prints as its parts laid flat. + Everything glued on a part of the group comes with it, unless it has a print name of its own. `print = "each"` prints every copy of a part as an object of its own, as coasters stacked in the assembly to show them. @@ -179,6 +198,9 @@ triangles in millimetres) for a viewer of your own, and `toGlb()`, `to3mf()` and `toStl()` write them. The options are `layout` (`"assembled"`, `"flat"` or `"print"`), `markHeight`, `lineWidth`, `slitWidth`, `hinges` (`false` leaves the cuts of living hinges out, as the print layout does), +`split` (`false` keeps an object that needs supports whole; a +number is how much of it may hang over air before it is shared out, in +mm², 100 unless given), `hardware` and `gap`. A part or mark body has `matrix`, the 4 x 4 matrix (row by row, as `result.assembly` has it) that takes its part's own coordinates, the outline in x and y and z from 0 at the back to the diff --git a/docs/customizer.md b/docs/customizer.md index e311424..ad557b7 100644 --- a/docs/customizer.md +++ b/docs/customizer.md @@ -62,7 +62,8 @@ part("figure") figure(figure, 80); ``` `/* [Size] */` starts a group named Size. `/* [Hidden] */` hides the -settings that follow it, until another group begins. +settings that follow it, until another group begins. `$print` and `$view` +are never settings, wherever they are. A `//` comment immediately above a variable supplies its caption. Keep the file's introductory comment separate with a blank line so it does not diff --git a/docs/javascript.md b/docs/javascript.md index 418d82a..c046a16 100644 --- a/docs/javascript.md +++ b/docs/javascript.md @@ -73,6 +73,7 @@ The URL should point to a font file provided by your application. | `assembly` | One entry per copy of a part with `name`, `copy`, `thickness`, `material`, `outline`, a 4 × 4 `matrix` and `placed`, for showing the design put together. Parts without `at` or `rotate` have `placed: false`. A bent part has `bends`; a part in a step has `step`; a part that moves when the model is opened has `moves`; `marks` holds what is engraved and scored on it, front and back; a mark that is the cuts of a living hinge has `hinge: true` | | `steps` | The text of each assembly step, in order; a part's `step` counts from 1 | | `stages` | The stages of opening the model, from `hinge()` and `slide()`, in order: a numbered stage as its number, a named one as its name | +| `view` | `"assembled"` or `"apart"` when the program sets `$view`: how a flat picture of the design shows it. Not there when the program leaves it to the viewer | | `hardware` | Each `hardware()`: `kind`, `from`, `to`, `size`, `up`, `sides`, `step`, `label` and `moves` | | `lights` | Each light, from a tealight, LED, bulb or `light()`: `from` and `to` (the same point unless it is a strip), `color`, `lumens`, `flicker`, `source`, `step`, `label` and `moves` | | `paths` | Layer paths with `name`, `mode`, `color`, `d`, `regions` and `lines` | diff --git a/docs/versions.md b/docs/versions.md index 5ec1e5e..8bb2855 100644 --- a/docs/versions.md +++ b/docs/versions.md @@ -1,6 +1,6 @@ # Versions -KerfScript 0.13.1 implements language version 0.3. The package version tracks +KerfScript 0.13.2 implements language version 0.3. The package version tracks the software release; the language version tracks the syntax and behavior of `.kerf` programs. @@ -30,4 +30,4 @@ files used with a design. Applications that store designs should retain that information and compare the output before upgrading the interpreter. Pin the npm package to an exact version when your application needs a fixed -renderer, for example `@mylasertools/kerfscript@0.13.1`. +renderer, for example `@mylasertools/kerfscript@0.13.2`. diff --git a/package-lock.json b/package-lock.json index 7a5af26..7f6cea9 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@mylasertools/kerfscript", - "version": "0.13.1", + "version": "0.13.2", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@mylasertools/kerfscript", - "version": "0.13.1", + "version": "0.13.2", "license": "AGPL-3.0-only", "bin": { "kerf": "dist/cli.js" diff --git a/package.json b/package.json index 057adf8..b014f85 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@mylasertools/kerfscript", - "version": "0.13.1", + "version": "0.13.2", "description": "KerfScript: a programming language and library for laser-cutting generators. Write parametric 2D parts with cut, score and engrave layers, kerf compensation and joinery, then turn settings into SVG or DXF cut files from Node.js, the browser, the command line or WebAssembly.", "type": "module", "license": "AGPL-3.0-only", diff --git a/packaging/flatpak/com.mylasertools.KerfScript.metainfo.xml b/packaging/flatpak/com.mylasertools.KerfScript.metainfo.xml index 7be03ee..f684b44 100644 --- a/packaging/flatpak/com.mylasertools.KerfScript.metainfo.xml +++ b/packaging/flatpak/com.mylasertools.KerfScript.metainfo.xml @@ -46,6 +46,7 @@ + diff --git a/src/customizer.ts b/src/customizer.ts index 2ec97d4..2d3f8ce 100644 --- a/src/customizer.ts +++ b/src/customizer.ts @@ -98,8 +98,9 @@ export function parameters(source: string): { parameters: Parameter[] } { // Settings whose `when` follows a [...], so it is surely a condition const afterControl = new Set(); for (const s of program.body) { - // $print names the program's print group, never a setting - if (s.kind !== 'assign' || /^\$(f[nas]|print)$/.test(s.name)) continue; + // $print names the program's print group and $view how it shows, + // never settings + if (s.kind !== 'assign' || /^\$(f[nas]|print|view)$/.test(s.name)) continue; const lit = literal(s.value); if (!lit.ok) continue; const group = diff --git a/src/export/mesh.ts b/src/export/mesh.ts index c033f02..b90f20a 100644 --- a/src/export/mesh.ts +++ b/src/export/mesh.ts @@ -9,6 +9,7 @@ import { bendPoint, foldPanels, + IDENTITY4, meshPieces, multiply, worldBox, @@ -30,7 +31,7 @@ import { import { HARDWARE_COLORS, HARDWARE_KINDS } from '../hardware.js'; import { rodFrame } from '../bores.js'; import { triangulate } from './triangulate.js'; -import { hangingArea } from './supports.js'; +import { hangingArea, weighingDone } from './supports.js'; export interface Body { /** "Lid", "Lid engrave", "dowel" */ @@ -85,6 +86,11 @@ export interface MeshOptions { /** Whether a living hinge's cuts are opened. Without them a bent part is * solid, as it is printed: true, but false in the "print" layout */ hinges?: boolean; + /** In the "print" layout, whether a print group that would need support + * is made as a few objects that each print without: true by default. + * A number is how much may hang over air before it is, in mm²: 100 + * for true, which a short bridge or the end of a finger stays under */ + split?: boolean | number; } export interface MeshSource { @@ -831,7 +837,7 @@ function printBodies(source: MeshSource, o: Required, cuts: Set { + ): { bodies: Body[]; box: number[]; frame: number[] } => { const back = inverse(frame); const local = new Map(members.map((i) => [i, multiply(back, all[i].matrix)] as const)); // The bed, under the lowest corner of the parts, bent as they are made @@ -854,7 +860,9 @@ function printBodies(source: MeshSource, o: Required, cuts: Set { const f = face(m, p.thickness, side); if (!f) return []; - if (!f.up && Math.abs(f.height - z0) < EPS) return null; + // On the bed, or nearer it than its marks stand off the face: + // they would be under the bed, and lift the object off it + if (!f.up && f.height - z0 < o.markHeight + EPS) return null; // The other parts with a face against this one, in its coordinates const into = inverse(m); const hidden: Poly[][] = []; @@ -905,13 +913,56 @@ function printBodies(source: MeshSource, o: Required, cuts: Set; + // Each part's solid in its own coordinates, made once, and the solids + // of a set of parts lying in a frame, on the bed, with the part each is + // of: for weighing ways of laying them without making the object + const solids = new Map(); + const solid = (i: number, bent: boolean) => { + const key = `${i}|${bent}`; + let made = solids.get(key); + if (!made) { + made = partBodies(all[i], IDENTITY4, { ...o, markHeight: 0 }, bent, cuts, 0); + solids.set(key, made); + } + return made; + }; + const pose = (set: number[], frame: number[], bent: boolean) => { + const back = inverse(frame); + const posed: Body[] = []; + const owner: number[] = []; + let low = Infinity; + for (const i of set) { + const m = multiply(back, all[i].matrix); + const mirrored = det3(m) < 0; + for (const b of solid(i, bent)) { + const positions = new Array(b.positions.length); + for (let k = 0; k < positions.length; k += 3) { + const q = apply(m, [b.positions[k], b.positions[k + 1], b.positions[k + 2]]); + positions[k] = q[0]; + positions[k + 1] = q[1]; + positions[k + 2] = q[2]; + low = Math.min(low, q[2]); + } + const indices = mirrored ? [...b.indices] : b.indices; + if (mirrored) + for (let k = 0; k < indices.length; k += 3) + [indices[k + 1], indices[k + 2]] = [indices[k + 2], indices[k + 1]]; + posed.push({ ...b, positions, indices }); + owner.push(i); + } + } + for (const b of posed) for (let k = 2; k < b.positions.length; k += 3) b.positions[k] -= low; + return { posed, owner }; }; // Without print_on, an object that would hang over air lies on whichever // face of its parts needs the least support, when that is clearly less // (5% and 5 mm²). // Each way down is tried once, the ways most of its parts face first. - const objects = groups.map((group, g) => { + const orient = (group: Group, g: number): Made => { const made = build(group, g); if (group.members.some((i) => all[i].printOn)) return made; if (hangingArea(made.bodies) < 20) return made; @@ -931,24 +982,249 @@ function printBodies(source: MeshSource, o: Required, cuts: Set b.area - a.area).slice(0, 32); // Weighed on a coarse grid first; the few best weighed again finely, // as the support check does, so two close ways are told apart - const tries: { made: typeof made; area: number }[] = []; + const tries: { bodies: Body[]; frame: number[]; area: number }[] = []; for (const { frame } of order) { - const other = build({ ...group, frame }, g); - const a = hangingArea(other.bodies); - tries.push({ made: other, area: a }); + const bodies = pose(group.members, frame, group.bent).posed; + const a = hangingArea(bodies); + tries.push({ bodies, frame, area: a }); if (a < 20) break; } if (!tries.length) return made; - const fine = (m: typeof made) => hangingArea(m.bodies, 120_000); - let best = { made, area: fine(made) }; + const fine = (bodies: Body[]) => hangingArea(bodies, 120_000); + let best: { frame?: number[]; area: number } = { area: fine(made.bodies) }; const start = best.area; tries.sort((x, y) => x.area - y.area); const near = tries.filter((t) => t.area <= tries[0].area * 1.3 + 5).slice(0, 3); for (const t of near) { - const a = fine(t.made); - if (a < start * 0.95 - 5 && a < best.area) best = { made: t.made, area: a }; + const a = fine(t.bodies); + if (a < start * 0.95 - 5 && a < best.area) best = { frame: t.frame, area: a }; + } + return best.frame ? build({ ...group, frame: best.frame }, g) : made; + }; + // As much over air as a print group is shared out for, in mm² + const HANGS = o.split === true ? 100 : o.split === false ? Infinity : Math.max(1, o.split); + const size = (i: number) => Math.abs(all[i].outline.reduce((s, r) => s + area(r), 0)); + // A print group that would need support whichever way it lies is made + // as a few objects that each print without. The part that hangs most + // is taken off, and the next, until what is left prints lying some way; + // the parts taken off are an object too where they touch, shared out + // the same way if they need it. So the fewest parts leave the group, + // and walls that hold each other's corners up stay together. + const shared = (group: Group, lay: number[]): Group[] => { + const { members, bent, name } = group; + const down = (f: number[]) => [f[2], f[6], f[10]].map((v) => v.toFixed(3)).join(','); + // How much of the parts hangs over air lying in a frame, and of each + // part: weighed once, as finely as overhangs() does, or roughly, which + // is quick and seldom finds less + const weighed = new Map }>(); + // The weighing done for this group so far + const begun = weighingDone(); + const work = () => weighingDone() - begun; + const weigh = (set: number[], frame: number[], rough = false) => { + const key = `${set.join(' ')}|${down(frame)}|${rough}`; + const known = weighed.get(key); + if (known) return known; + const { posed, owner } = pose(set, frame, bent); + const byBody: number[] = []; + const a = hangingArea(posed, rough ? 12_000 : 250_000, byBody); + const each = new Map(); + byBody.forEach((v, k) => each.set(owner[k], (each.get(owner[k]) ?? 0) + v)); + const found = { frame, area: a, each }; + weighed.set(key, found); + return found; + }; + // The ways a set of parts may lie: as print_on says, or on a face of + // one of its parts, the faces most of them have first; a bent part on + // either edge too + const ways = (set: number[]): number[][] => { + const told = set.find((i) => all[i].printOn); + if (told !== undefined) { + const inSet = new Set(set); + const base = + set.find((i) => all[i].glued === undefined || !inSet.has(all[i].glued!)) ?? set[0]; + const n0 = [all[set[0]].matrix[2], all[set[0]].matrix[6], all[set[0]].matrix[10]]; + const flat = set.every((i) => { + const m = all[i].matrix; + return ( + !all[i].bends?.length && + Math.abs(m[2] * n0[0] + m[6] * n0[1] + m[10] * n0[2]) > 1 - 1e-6 + ); + }); + return [lieOn(set, base, flat)]; + } + const found = new Map(); + for (const i of set) { + const m = all[i].matrix; + const frames = [m, multiply(m, FLIP)]; + if (bent && all[i].bends?.length) { + const edge = multiply(m, ON_EDGE); + frames.unshift(edge, multiply(edge, FLIP)); + } + for (const frame of frames) { + const k = down(frame); + const w = found.get(k); + if (w) w.area += size(i); + else found.set(k, { frame, area: size(i) }); + } + } + return [...found.values()] + .sort((x, y) => y.area - x.area) + .slice(0, 6) + .map((w) => w.frame); + }; + // A little less than needs support, so that an object weighed again + // once made, on a grid that falls a little otherwise, still does not + const FREE = HANGS * 0.9; + // The parts of a set that hang, lying one way: those with this much + // over air. A little over air under each of many parts is not helped + // by taking any of them off + const hung = (set: number[], each: Map) => + set.filter((i) => (each.get(i) ?? 0) >= HANGS / 2); + const sum = (set: number[]) => set.reduce((s, i) => s + size(i), 0); + // The way a set lies: as it lay if nothing hangs then. Else the way + // that takes the least of it off: of the two ways whose hanging + // parts are roughly the smallest, the one whose hanging parts, with + // those that hang once they are off, are the smallest + const lie = (set: number[], lay?: number[], look = true) => { + const told = set.some((i) => all[i].printOn); + // A flat part alone lies on its back, with nothing over air + if (set.length === 1 && !told && !(bent && all[set[0]].bends?.length)) + return { frame: all[set[0]].matrix, area: 0, each: new Map() }; + const frames = ways(set); + const first = weigh(set, told || !lay ? frames[0] : lay); + if (first.area < FREE || told || !look || work() >= MOST) return first; + const rough = [first.frame, ...frames.filter((w) => down(w) !== down(first.frame))] + .map((w) => { + const found = weigh(set, w, true); + return { w, a: found.area, cost: found.area < FREE ? 0 : sum(hung(set, found.each)) }; + }) + .sort((x, y) => x.cost - y.cost || x.a - y.a) + .slice(0, 2); + let best: { found: typeof first; cost: number } | undefined; + for (const { w } of rough) { + if (best && work() >= MOST) break; + const found = weigh(set, w); + if (found.area < FREE) return found; + const off = hung(set, found.each); + const rest = set.filter((i) => !off.includes(i)); + const after = rest.length ? weigh(rest, w) : undefined; + const cost = + sum(off) + + (after && after.area >= FREE ? sum(hung(rest, after.each)) : 0) + + (rest.length ? 0 : 1e12); + if ( + !best || + cost < best.cost - 1e-6 || + (cost < best.cost + 1e-6 && found.area < best.found.area) + ) + best = { found, cost }; + } + return best!.found; + }; + const joins = (i: number, j: number) => all[i].glued === j || all[j].glued === i || touch(i, j); + // The parts of a set that hold together, each lot apart + const lots = (set: number[]) => { + const out: number[][] = []; + const left = new Set(set); + for (const i of set) { + if (!left.delete(i)) continue; + const lot = [i]; + for (let k = 0; k < lot.length; k++) + for (const j of [...left]) + if (joins(lot[k], j)) { + left.delete(j); + lot.push(j); + } + out.push(lot.sort((x, y) => x - y)); + } + return out; + }; + // No more weighing than this for one group, a few seconds of it: the + // parts not yet shared out then each print alone, flat + const MOST = 250e6; + const alone = (i: number) => ({ set: [i], frame: ways([i])[0] }); + const pieces = (set: number[], lay?: number[]): { set: number[]; frame: number[] }[] => { + if (work() >= MOST) return set.map(alone); + const apart = lots(set); + if (apart.length > 1) return apart.flatMap((lot) => pieces(lot, lay)); + let rest = apart[0]; + const off: number[] = []; + let lying = lie(rest, lay); + while (lying.area >= FREE && rest.length > 1 && work() < MOST) { + let gone = hung(rest, lying.each); + if (!gone.length) break; + if (gone.length === rest.length) + gone = [ + gone.reduce((x, y) => ((lying.each.get(y) ?? 0) > (lying.each.get(x) ?? 0) ? y : x)), + ]; + const taken = gone; + off.push(...taken); + rest = rest.filter((i) => !taken.includes(i)); + // What they held to the rest goes with them: the biggest lot is + // left, and laid afresh + const now = lots(rest); + if (now.length > 1) { + const main = now.reduce((x, y) => (sum(y) > sum(x) ? y : x)); + off.push(...rest.filter((i) => !main.includes(i))); + rest = main; + lying = lie(rest, lying.frame); + continue; + } + // It lies as it did, less those parts + lying = lie(rest, lying.frame, false); + } + if (work() >= MOST && lying.area >= FREE && hung(rest, lying.each).length) + return [...rest.map(alone), ...pieces(off)]; + return [{ set: rest, frame: lying.frame }, ...(off.length ? pieces(off) : [])]; + }; + const out = pieces( + [...members].sort((x, y) => x - y), + lay, + ); + if (out.length < 2) return [{ ...group, frame: out[0].frame }]; + return out.map(({ set, frame }) => { + const biggest = set.reduce((x, y) => (size(y) > size(x) ? y : x)); + // Named after the group and its biggest part, or after that part alone + // where the group has no name + const part = all[biggest].name; + return { members: set, frame, bent, name: name === undefined ? part : `${name} - ${part}` }; + }); + }; + let made = 0; + const objects = groups.flatMap((group) => { + const whole = orient(group, made++); + // Not parts that print each apart, joined only copy by copy + if ( + o.split === false || + group.members.length < 2 || + group.members.some((i) => all[i].print === 'each') + ) + return [whole]; + const before = hangingArea(whole.bodies, 250_000); + if (before < HANGS) return [whole]; + const sets = shared(group, whole.frame); + // Whole, and lying as it did: nothing to gain + if ( + sets.length < 2 && + [2, 6, 10].every((k) => Math.abs(sets[0].frame[k] - whole.frame[k]) < 1e-3) + ) + return [whole]; + const pieces = sets.map((set) => build(set, made++)); + // Unless half of what hung still does: then it stays whole + const after = pieces.reduce( + (n, p, k) => n + (sets[k].members.length > 1 ? hangingArea(p.bodies, 250_000) : 0), + 0, + ); + if (after > before / 2) return [whole]; + // Objects of one name are numbered + const count = new Map(); + for (const p of pieces) { + const title = p.bodies[0]?.object ?? ''; + const n = (count.get(title) ?? 0) + 1; + count.set(title, n); + if (n > 1) for (const b of p.bodies) b.object = `${title} (${n})`; } - return best.made; + return pieces; }); const moves = packed( objects.map((g) => g.box), @@ -980,6 +1256,7 @@ export function meshBodies(source: MeshSource, options: MeshOptions = {}): Body[ gap: options.gap ?? 5, slitWidth: options.slitWidth ?? 0.2, hinges: options.hinges ?? options.layout !== 'print', + split: options.split ?? true, }; const cuts = new Set( (source.layers ?? [{ name: 'cut', mode: 'cut' }]) diff --git a/src/export/supports.ts b/src/export/supports.ts index 43cae63..b7994b1 100644 --- a/src/export/supports.ts +++ b/src/export/supports.ts @@ -36,12 +36,12 @@ const LEDGE = 1.5; // Most columns an object is cut into const MAX_COLUMNS = 250_000; -interface Run { - bottom: number; - top: number; - // The body whose face the run starts on - body: number; -} +// How much weighing has been done: the columns looked at, the faces tried +// against them and the columns looked to for a hold, all told +let weighed = 0; +/** The weighing done so far, in steps: the same for the same objects on any + * machine, to stop a search that takes too long */ +export const weighingDone = () => weighed; /** The objects of a model laid out to 3D print (meshBodies() with layout * "print") that hang over air: solid above the bed with nothing of the @@ -67,14 +67,20 @@ export function overhangs(bodies: Body[], options: OverhangOptions = {}): Overha /** How much of one object's bodies hangs over air, in mm², on a grid of * at most `columns` columns: for weighing one way of laying it against - * another */ -export function hangingArea(group: Body[], columns = 40_000): number { + * another. `each`, when given, is filled with how much of each body does, + * by its place among the object's parts */ +export function hangingArea(group: Body[], columns = 40_000, each?: number[]): number { // Its parts only, as overhangs() weighs them const parts = group.filter((b) => b.kind === 'part'); - return objectOverhang(parts, 1, columns)?.area ?? 0; + return objectOverhang(parts, 1, columns, each)?.area ?? 0; } -function objectOverhang(group: Body[], slope: number, columns = MAX_COLUMNS): Overhang | null { +function objectOverhang( + group: Body[], + slope: number, + columns = MAX_COLUMNS, + each?: number[], +): Overhang | null { let [x0, y0, x1, y1] = [Infinity, Infinity, -Infinity, -Infinity]; for (const b of group) for (let i = 0; i < b.positions.length; i += 3) { @@ -92,9 +98,13 @@ function objectOverhang(group: Body[], slope: number, columns = MAX_COLUMNS): Ov // faces drawn on round numbers const cx = (i: number) => x0 + (i + 0.5013) * r; const cy = (j: number) => y0 + (j + 0.4987) * r; + const near = Math.max(1, Math.ceil(LEDGE / r)); // Where each column's ray crosses a face: its height, +1 going into a // solid (a face turned down), -1 coming out, and the body - const hits: number[][] = Array.from({ length: nx * ny }, () => []); + const hitColumn: number[] = []; + const hitZ: number[] = []; + const hitDir: number[] = []; + const hitBody: number[] = []; group.forEach((b, bi) => { const p = b.positions; const ix = b.indices; @@ -117,6 +127,7 @@ function objectOverhang(group: Body[], slope: number, columns = MAX_COLUMNS): Ov const j0 = Math.max(0, Math.floor((Math.min(ay, ay + by, ay + dy) - y0) / r - 0.6)); const j1 = Math.min(ny - 1, Math.ceil((Math.max(ay, ay + by, ay + dy) - y0) / r)); const dir = nz < 0 ? 1 : -1; + if (i1 >= i0 && j1 >= j0) weighed += (i1 - i0 + 1) * (j1 - j0 + 1); for (let i = i0; i <= i1; i++) for (let j = j0; j <= j1; j++) { const px = cx(i) - ax; @@ -125,27 +136,60 @@ function objectOverhang(group: Body[], slope: number, columns = MAX_COLUMNS): Ov const u = (px * dy - py * dx) / nz; const v = (bx * py - by * px) / nz; if (u < 0 || v < 0 || u + v > 1) continue; - hits[i * ny + j].push(az + u * bz + v * dz, dir, bi); + hitColumn.push(i * ny + j); + hitZ.push(az + u * bz + v * dz); + hitDir.push(dir); + hitBody.push(bi); } } }); + // The hits column by column, in the order they were found: where each + // column's begin, and which they are + const count = nx * ny; + weighed += count; + const first = new Int32Array(count + 1); + for (const c of hitColumn) first[c + 1]++; + for (let c = 0; c < count; c++) first[c + 1] += first[c]; + const byColumn = new Int32Array(hitColumn.length); + const filled = first.slice(0, count); + for (let h = 0; h < hitColumn.length; h++) byColumn[filled[hitColumn[h]]++] = h; // Each column's runs of solid, the parts' runs joined where they overlap - // or nearly meet - const runs: Run[][] = hits.map((h) => { - if (!h.length) return []; - const order = Array.from({ length: h.length / 3 }, (_, k) => k).sort( - (m, n) => h[m * 3] - h[n * 3] || h[n * 3 + 1] - h[m * 3 + 1], - ); - const col: Run[] = []; + // or nearly meet: where each column's begin, and each run's bottom, top + // and the body whose face it starts on + const firstRun = new Int32Array(count + 1); + const bottoms: number[] = []; + const tops: number[] = []; + const bodies: number[] = []; + for (let c = 0; c < count; c++) { + firstRun[c] = bottoms.length; + if (first[c] === first[c + 1]) continue; + const [from, to] = [first[c], first[c + 1]]; + // Lowest first, and where two meet the one going in first + for (let m = from + 1; m < to; m++) { + const h = byColumn[m]; + let k = m - 1; + while ( + k >= from && + (hitZ[byColumn[k]] > hitZ[h] || + (hitZ[byColumn[k]] === hitZ[h] && hitDir[byColumn[k]] < hitDir[h])) + ) { + byColumn[k + 1] = byColumn[k]; + k--; + } + byColumn[k + 1] = h; + } let depth = 0; - for (const k of order) { - const [z, dir, body] = [h[k * 3], h[k * 3 + 1], h[k * 3 + 2]]; - if (dir > 0) { + for (let m = from; m < to; m++) { + const h = byColumn[m]; + const z = hitZ[h]; + if (hitDir[h] > 0) { if (depth === 0) { - const last = col[col.length - 1]; - if (last && z - last.top <= GAP) depth = 1; + const last = bottoms.length - 1; + if (last >= firstRun[c] && z - tops[last] <= GAP) depth = 1; else { - col.push({ bottom: z, top: z, body }); + bottoms.push(z); + tops.push(z); + bodies.push(hitBody[h]); depth = 1; } continue; @@ -153,24 +197,25 @@ function objectOverhang(group: Body[], slope: number, columns = MAX_COLUMNS): Ov depth++; } else if (depth > 0) { depth--; - if (depth === 0) col[col.length - 1].top = z; + if (depth === 0) tops[tops.length - 1] = z; } } - return col; - }); - const near = Math.max(1, Math.ceil(LEDGE / r)); + } + firstRun[count] = bottoms.length; + const widest = Math.max(r * Math.SQRT2, LEDGE) + 1e-9; const parts = new Set(); let cells = 0; let lowest = Infinity; for (let i = 0; i < nx; i++) for (let j = 0; j < ny; j++) - for (const run of runs[i * ny + j]) { - const z = run.bottom; + for (let run = firstRun[i * ny + j]; run < firstRun[i * ny + j + 1]; run++) { + const z = bottoms[run]; if (z <= GAP) continue; // Held up by a column near it, within a ledge's width, that reaches // lower and comes up to no further below than the steepest // printable slope drops over the distance let held = false; + weighed += (2 * near + 1) ** 2; for (let di = -near; di <= near && !held; di++) for (let dj = -near; dj <= near && !held; dj++) { if (!di && !dj) continue; @@ -178,14 +223,17 @@ function objectOverhang(group: Body[], slope: number, columns = MAX_COLUMNS): Ov const nj = j + dj; if (ni < 0 || nj < 0 || ni >= nx || nj >= ny) continue; const d = Math.hypot(di, dj) * r; - if (d > Math.max(r * Math.SQRT2, LEDGE) + 1e-9) continue; + if (d > widest) continue; const reach = d * slope + GAP; - held = runs[ni * ny + nj].some((o) => o.bottom < z - 1e-6 && o.top >= z - reach); + const end = firstRun[ni * ny + nj + 1]; + for (let o = firstRun[ni * ny + nj]; o < end && !held; o++) + held = bottoms[o] < z - 1e-6 && tops[o] >= z - reach; } if (held) continue; cells++; lowest = Math.min(lowest, z); - parts.add(group[run.body].name); + parts.add(group[bodies[run]].name); + if (each) each[bodies[run]] = (each[bodies[run]] ?? 0) + r * r; } if (!cells) return null; return { diff --git a/src/index.ts b/src/index.ts index 1727728..d33ebbb 100644 --- a/src/index.ts +++ b/src/index.ts @@ -42,7 +42,7 @@ export { HARDWARE_KINDS, HARDWARE_COLORS, type HardwareKind } from './hardware.j export { LIGHT_COLORS, lightPoints, type Light } from './lights.js'; export { PAINT_COLORS } from './colors.js'; -export const VERSION = '0.13.1'; +export const VERSION = '0.13.2'; export const LANGUAGE_VERSION = '0.3'; export { diffRenders, type DiffEntry } from './diff.js'; export { instructionsHtml } from './instructions.js'; diff --git a/src/language.ts b/src/language.ts index 4271cc4..cada18c 100644 --- a/src/language.ts +++ b/src/language.ts @@ -130,6 +130,9 @@ const SPECIAL: Record = { $print: { doc: 'Print group for the parts made inside, or at the top level for every part in the program: in the print layout (3MF, STL) the touching parts with one print name are one object; `""` for none. Never a setting', }, + $view: { + doc: 'At the top level, how a flat picture of the design shows it: `"assembled"` put together, `"apart"` as its parts laid out. Not set, the viewer chooses. Never a setting', + }, $sheet: { value: '[600, 400]', doc: 'Sheet size for packing' }, $gap: { value: '3', doc: 'Space between packed parts and around the sheet edge' }, $layout: { diff --git a/src/render.ts b/src/render.ts index 25b778a..c88072c 100644 --- a/src/render.ts +++ b/src/render.ts @@ -156,6 +156,9 @@ export interface RenderResult { // The stages of opening the model, from hinge() and slide(), in order: // a numbered stage by its number, a named one by its name stages: string[]; + // $view at the top level: how a flat picture of the design shows it, + // put together or as its parts laid apart. Not set, the viewer chooses + view?: 'assembled' | 'apart'; } const perimeter = (p: [number, number][], closed: boolean) => { @@ -1063,6 +1066,10 @@ export function render(source: string, options: RenderOptions = {}): RenderResul ); const svg = single ? single.svg : toSvg(stacked, width, height, layerList); const paths = single ? single.paths : layerPaths(stacked, layerList); + const fileView = g('$view'); + const view = fileView === 'assembled' || fileView === 'apart' ? fileView : undefined; + if (fileView !== undefined && !view) + warnings.push('$view must be "assembled" or "apart"; it is left for the viewer to choose.'); return { sheets, @@ -1081,6 +1088,7 @@ export function render(source: string, options: RenderOptions = {}): RenderResul lights: res.lights, steps: res.steps, stages: res.stages, + ...(view && { view }), }; } diff --git a/test/controls.test.mjs b/test/controls.test.mjs index 4703d78..41452b0 100644 --- a/test/controls.test.mjs +++ b/test/controls.test.mjs @@ -123,3 +123,23 @@ test('a comment that only begins with "when" stays a comment', async () => { assert.match(size.whenProblem, /not an expression/); assert.equal(render(src).warnings.length, 1); }); + +test('$view says how a flat picture shows the design and is never a setting', async () => { + const { parameters, render } = await import('../dist/index.js'); + const src = (v) => `width = 40;\n${v}\npart("a") rect([width, 20]);`; + assert.equal(render(src('')).view, undefined); + assert.equal('view' in render(src('')), false); + assert.equal(render(src('$view = "assembled";')).view, 'assembled'); + assert.equal(render(src('$view = "apart";')).view, 'apart'); + assert.equal(render(src('$view = width > 30 ? "apart" : "assembled";')).view, 'apart'); + assert.equal(render(src('module m() { $view = "apart"; rect(1); }')).view, undefined); + const bad = render(src('$view = "exploded";')); + assert.equal(bad.view, undefined); + assert.ok(bad.warnings.some((w) => w.includes('$view must be "assembled" or "apart"'))); + assert.equal(render(src('$view = "apart";')).warnings.length, render(src('')).warnings.length); + assert.equal(render(src('$view = "apart";')).svg, render(src('')).svg); + assert.deepEqual( + parameters(src('$view = "apart";')).parameters.map((p) => p.name), + ['width'], + ); +}); diff --git a/test/model3d.test.mjs b/test/model3d.test.mjs index fa6a6cc..882d1be 100644 --- a/test/model3d.test.mjs +++ b/test/model3d.test.mjs @@ -347,7 +347,7 @@ part("Post", stack = 3, at = [100, 0, 0]) { rect([10, 10]); engrave() translate( ['Post', 4], ], ); - const bodies = meshBodies(r, { layout: 'print', markHeight: 0.6 }); + const bodies = meshBodies(r, { layout: 'print', markHeight: 0.6, split: false }); for (const b of bodies) assert.equal(openEdges(b), 0, b.name); const z = (name, kind = 'part') => bodies.filter((b) => b.name === name && b.kind === kind).map((b) => box(b).map((v) => v[2])); @@ -403,9 +403,16 @@ part("Post", stack = 3, at = [100, 0, 0]) { rect([10, 10]); engrave() translate( // the hill's 36 x 16 less the house's 10 x 10 assert.equal(area(bodies.find((b) => b.name === 'Hill engrave')), 36 * 16 - 100); - const zip = Buffer.from(toModel(r, '3mf', { layout: 'print' })).toString('latin1'); - const model = zip.slice(zip.indexOf(' { + const zip = Buffer.from(toModel(r, '3mf', options)).toString('latin1'); + const model = zip.slice(zip.indexOf(' { @@ -666,7 +673,7 @@ test('kerf render --print lays glued stacks out as one object each', () => { }); test('overhangs() finds what hangs over air in the print layout, and not what a ledge or slope holds', () => { - const over = (src) => overhangs(meshBodies(render(src), { layout: 'print' })); + const over = (src) => overhangs(meshBodies(render(src), { layout: 'print', split: false })); // An upright cup and a stack of rings each a little wider: nothing assert.deepEqual(over('use \n$thickness = 3;\nbox([60, 40, 30], lid = true);'), []); assert.deepEqual( @@ -692,6 +699,80 @@ part("leg", qty = 2, at = [[0, 0, 0], [97, 0, 0]], rotate = [90, 0, 90]) rect([6 ); }); +test('a mark on a face next to the bed does not lift the object off it', () => { + // The wall reaches a hundredth of a millimetre lower than the bottom, so + // the bottom's back face is just off the bed: its engraving cannot print + const r = render(`$thickness = 3; +$print = "cup"; +part("bottom", print_on = "back", at = [0, 0, 0.01]) { rect([60, 40]); engrave(side = "back") translate([10, 10]) rect([20, 10]); } +part("wall", at = [0, 3, 0], rotate = [90, 0, 0]) rect([60, 30]);`); + const bodies = meshBodies(r, { layout: 'print', markHeight: 0.6 }); + const low = (b) => Math.min(...b.positions.filter((_, k) => k % 3 === 2)); + assert.ok(Math.abs(Math.min(...bodies.filter((b) => b.kind === 'part').map(low))) < 1e-6); + assert.ok(bodies.every((b) => low(b) > -1e-6)); + assert.deepEqual(overhangs(bodies), []); +}); + +test('a print group that would need support prints as a few objects that do not', () => { + const objects = (bodies) => + [...new Set(bodies.map((b) => b.instance))].map((i) => ({ + object: bodies.find((b) => b.instance === i).object, + parts: bodies.filter((b) => b.instance === i && b.kind === 'part').map((b) => b.name), + })); + // A cabinet: the front closes it, so whichever way it lies a panel is + // over air. The carcass with its shelf is one object, the front another + const cabinet = render(`$thickness = 3; +$print = "cabinet"; +part("Floor", at = [0, 0, 0]) rect([60, 40]); +part("Top", at = [0, 0, 97]) rect([60, 40]); +part("Side", qty = 2, at = [[0, 0, 0], [57, 0, 0]], rotate = [90, 0, 90]) rect([40, 100]); +part("Back", at = [0, 40, 0], rotate = [90, 0, 0]) rect([60, 100]); +part("Shelf", at = [3, 0, 50]) rect([54, 37]); +part("Front", at = [0, 3, 0], rotate = [90, 0, 0]) difference() { rect([60, 100]); translate([10, 20]) rect([40, 60]); }`); + const whole = meshBodies(cabinet, { layout: 'print', split: false }); + assert.equal(objects(whole).length, 1); + assert.equal(overhangs(whole).length, 1); + const shared = meshBodies(cabinet, { layout: 'print' }); + assert.deepEqual(overhangs(shared), []); + assert.deepEqual( + objects(shared).map((o) => [o.object, o.parts.sort().join(' ')]), + [ + ['cabinet - Back', 'Back Floor Shelf Side Side Top'], + ['cabinet - Front', 'Front'], + ], + ); + // The same solids either way, only laid out otherwise + assert.equal( + shared.reduce((n, b) => n + b.indices.length, 0), + whole.reduce((n, b) => n + b.indices.length, 0), + ); + // A table told to lie on its top's back: the top is over air, and + // prints apart from its legs + const table = render(`$thickness = 3; +$print = "table"; +part("top", print_on = "back", at = [0, 0, 40]) rect([100, 60]); +part("leg", qty = 2, at = [[0, 0, 0], [97, 0, 0]], rotate = [90, 0, 90]) rect([60, 40]);`); + const tabled = meshBodies(table, { layout: 'print' }); + assert.deepEqual(overhangs(tabled), []); + assert.deepEqual( + objects(tabled).map((o) => o.object), + ['table - leg', 'table - leg (2)', 'table - top'], + ); + // The lintel of a window is a short bridge: a cup with a window in two + // walls has one over air however it lies, and stays one object + const windowed = render(`$thickness = 3; +$print = "cup"; +part("bottom", at = [0, 0, 0]) rect([60, 40]); +part("wall", at = [0, 3, 3], rotate = [90, 0, 0]) difference() { rect([60, 30]); translate([20, 8]) rect([20, 10]); } +part("end", at = [0, 0, 3], rotate = [90, 0, 90]) difference() { rect([40, 30]); translate([10, 8]) rect([20, 10]); }`); + const cup = meshBodies(windowed, { layout: 'print' }); + assert.equal(objects(cup).length, 1); + assert.equal(overhangs(cup).length, 1); + assert.ok(overhangs(cup)[0].area < 100); + // ...unless less than that is asked to be shared out + assert.equal(objects(meshBodies(windowed, { layout: 'print', split: 20 })).length, 2); +}); + test('parts that move as the model opens print apart from the body they move against', () => { const r = render(`$thickness = 3; $print = "case";