scadify 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/plugin.json +17 -0
- package/BRIEF.md +111 -0
- package/LICENSE +21 -0
- package/README.md +79 -2
- package/docs/previews/domed-citadel.png +0 -0
- package/docs/previews/newton-cenotaph.png +0 -0
- package/docs/previews/temple-ruins.png +0 -0
- package/examples/domed-citadel.json +38 -0
- package/examples/newton-cenotaph.json +33 -0
- package/examples/temple-ruins.json +28 -0
- package/package.json +19 -6
- package/src/emitters/common.js +19 -0
- package/src/emitters/glb.js +55 -0
- package/src/emitters/scad.js +10 -0
- package/src/emitters/stl.js +24 -0
- package/src/emitters/threemf.js +22 -0
- package/src/emitters/usd.js +40 -0
- package/src/emitters/zip.js +52 -0
- package/src/engine.js +97 -0
- package/src/mcp.js +128 -0
- package/src/raster.js +136 -0
- package/src/recipe.js +186 -0
- package/src/scadify-cli.mjs +18 -0
- package/src/store.js +64 -0
- package/tests/lite.test.js +252 -0
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "scadify",
|
|
3
|
+
"displayName": "SCADify",
|
|
4
|
+
"description": "Make 3D models: tiny deterministic recipes (OpenSCAD inside) compiled to clean glb, stl, 3mf and usdz solids, with in-process previews.",
|
|
5
|
+
"version": "0.1.0",
|
|
6
|
+
"author": { "name": "SCADify contributors" },
|
|
7
|
+
"repository": "https://github.com/zvodd/scadify",
|
|
8
|
+
"homepage": "https://github.com/zvodd/scadify",
|
|
9
|
+
"license": "MIT",
|
|
10
|
+
"keywords": ["3d", "openscad", "cad", "glb", "stl", "usdz", "mcp"],
|
|
11
|
+
"mcpServers": {
|
|
12
|
+
"scadify": {
|
|
13
|
+
"command": "node",
|
|
14
|
+
"args": ["${CLAUDE_PLUGIN_ROOT}/src/scadify-cli.mjs"]
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
}
|
package/BRIEF.md
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
# SCADify — design brief
|
|
2
|
+
|
|
3
|
+
A tiny Node package that turns deterministic 3D-model recipes into clean meshes.
|
|
4
|
+
A recipe is a few hundred bytes of JSON (plain OpenSCAD inside, or a boolean
|
|
5
|
+
tree); the engine compiles it on demand and exports the result. Target install
|
|
6
|
+
footprint is ~7.5 MB (one heavy WASM dependency).
|
|
7
|
+
|
|
8
|
+
## Design principles (non-negotiable)
|
|
9
|
+
|
|
10
|
+
1. **Recipe is the source.** A recipe is a small JSON file (default store:
|
|
11
|
+
`store/`, one per ref). Deterministic: same recipe + params + seed ⇒ same
|
|
12
|
+
geometry, byte-for-byte on the same platform. Rendering is a disposable
|
|
13
|
+
derived output — never store the mesh.
|
|
14
|
+
2. **One heavy dependency:** `openscad-wasm-prebuilt` (in-process OpenSCAD with
|
|
15
|
+
the Manifold backend = exact booleans, deterministic mesh). Everything else
|
|
16
|
+
is Node stdlib. No SQLite, no sharp, no puppeteer, no Next.js, no audio, no
|
|
17
|
+
browser, no ffmpeg, no engines.
|
|
18
|
+
3. **Clean glTF / GLB.** The mesh only. No ground plane, no default camera
|
|
19
|
+
cluster, no light rig, no deep transform hierarchy. Flat tree: one node per
|
|
20
|
+
named part, mesh prim under it, PBR baseColor from the part's tint. Units are per recipe (mm|cm|dm|m, default dm); GLB/USD are exported in metres (scale 1),
|
|
21
|
+
z-up; glTF has no ratified units extension, so that is declared in
|
|
22
|
+
`asset.extras` (`units`, `metersPerUnit`, `upAxis`). Cameras/lights only
|
|
23
|
+
appear if a caller explicitly asks.
|
|
24
|
+
4. **USDZ / USDA output** — the editing/postprocess path (glTF is for engine
|
|
25
|
+
consumption). Also emit STL + 3MF (print) and SCAD (the program itself /
|
|
26
|
+
transpiled).
|
|
27
|
+
5. **The whole surface area**: a pattern for generating 3D models, a single
|
|
28
|
+
endpoint to add-and-compile, and an MCP to render from angles and export.
|
|
29
|
+
Nothing more.
|
|
30
|
+
|
|
31
|
+
## Recipe model
|
|
32
|
+
|
|
33
|
+
```jsonc
|
|
34
|
+
{
|
|
35
|
+
"kind": "scad", // "scad" (program is the source) | "csg"
|
|
36
|
+
"title": "demo-tray",
|
|
37
|
+
"units": "dm",
|
|
38
|
+
"seed": 7,
|
|
39
|
+
"program": "module tray(){ ... }", // for kind:"scad", stored verbatim
|
|
40
|
+
"parts": { "tray": "tray();", "standoffs": "standoffs();" },
|
|
41
|
+
"params": { "wall_h": 12 } // editable; compile is a function of these
|
|
42
|
+
}
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
For `kind:"csg"`, the recipe describes a boolean tree of primitives
|
|
46
|
+
(cube/cylinder/sphere/translate/rotate/union/difference/hull) which is compiled
|
|
47
|
+
via the Manifold backend and can also be transpiled to `.scad`. A part statement
|
|
48
|
+
may omit its trailing `;` — the engine terminates it (OpenSCAD's `-D` only
|
|
49
|
+
overrides variables the program declares; the engine pre-declares seed + params,
|
|
50
|
+
so `-D` stays the override).
|
|
51
|
+
|
|
52
|
+
## MCP surface (stdio, hand-rolled JSON-RPC — no SDK dep)
|
|
53
|
+
|
|
54
|
+
- `mint_solid` — store a recipe → `{ ref }`.
|
|
55
|
+
- `list_solids` / `get_solid` — list refs / return the recipe.
|
|
56
|
+
- `update_solid` — edit params/program/parts/tree/title/seed/tints in place.
|
|
57
|
+
- `export_solid` — the single add-and-compile endpoint: given `ref` and `format`
|
|
58
|
+
(`glb|gltf|stl|3mf|usdz|usda|scad|json`), compile deterministically and write
|
|
59
|
+
the file → `{ path, format, sizeBytes, sha256, ref }`.
|
|
60
|
+
- `render_turntable` — N PNG frames (3–36 angles) of the compiled solid, in-Node.
|
|
61
|
+
- `render_shot` — exactly one PNG at a chosen azimuth/elevation (`angle_deg` 0 =
|
|
62
|
+
the model front, `-y` face); `background` arg for a solid color or transparent.
|
|
63
|
+
- `render_standard` — one opaque composite: front-on + angled-high shots
|
|
64
|
+
side-by-side on a dark studio background.
|
|
65
|
+
- `measure_solid` — bounding box + volume + mesh checksum (determinism gate).
|
|
66
|
+
|
|
67
|
+
## Software rasterizer (in-Node, no canvas, no lib)
|
|
68
|
+
|
|
69
|
+
`src/raster.js` projects triangle soup from any camera angle, z-buffers, and
|
|
70
|
+
flat-shades by the triangle normal against a key light. Supports an opaque
|
|
71
|
+
studio background (default `#0C1019`) or a transparent alpha channel, and writes
|
|
72
|
+
PNGs with a hand-rolled encoder (node:zlib + packed chunks). Good enough for
|
|
73
|
+
previews; not a renderer.
|
|
74
|
+
|
|
75
|
+
## Layout
|
|
76
|
+
|
|
77
|
+
```
|
|
78
|
+
scadify/
|
|
79
|
+
package.json # name "scadify", bin "scadify"
|
|
80
|
+
.claude-plugin/plugin.json # Claude plugin manifest (mcpServers -> node ${CLAUDE_PLUGIN_ROOT}/src/scadify-cli.mjs)
|
|
81
|
+
src/
|
|
82
|
+
scadify-cli.mjs # stdio MCP server entry + one-shot CLI (package bin)
|
|
83
|
+
recipe.js # parse/validate/normalize recipes
|
|
84
|
+
store.js # plain JSON fs store (CRUD, no DB)
|
|
85
|
+
engine.js # openscad-wasm-prebuilt wrapper: compile recipe -> mesh
|
|
86
|
+
emitters/ # glb.js, stl.js, 3mf.js, usd.js, scad.js, zip.js
|
|
87
|
+
raster.js # software rasterizer + PNG encoder (turntable/shot/standard)
|
|
88
|
+
mcp.js # stdio JSON-RPC MCP server + tool defs
|
|
89
|
+
examples/ # canonical showcase recipes (JSON, no builder)
|
|
90
|
+
docs/previews/ # rendered side-by-side showcase images
|
|
91
|
+
tests/ # node:test suite
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
## Hard rules
|
|
95
|
+
|
|
96
|
+
- Self-contained: import no external code; the showcase examples are the
|
|
97
|
+
reference for every pattern.
|
|
98
|
+
- Every emitter produces a mesh-only, clean hierarchy (rule 3). USD/USDZ and
|
|
99
|
+
the zip stay dependency-free (no external USD lib).
|
|
100
|
+
- `export_solid` is byte-for-byte deterministic for a fixed recipe on one
|
|
101
|
+
platform (V8 Math caveats allowed).
|
|
102
|
+
- Tests: at least one round-trip per format and one determinism check (two
|
|
103
|
+
compiles → same checksum); `npm` lockfile committed; only runtime dependency
|
|
104
|
+
is `openscad-wasm-prebuilt`.
|
|
105
|
+
|
|
106
|
+
## Definition of done
|
|
107
|
+
|
|
108
|
+
`npm test` passes; `node src/scadify-cli.mjs` starts and answers `initialize`; README.md
|
|
109
|
+
documents the recipe pattern, the tools, and an end-to-end example (mint a
|
|
110
|
+
showcase recipe, export glb/stl/usdz, render a standard preview) with the actual
|
|
111
|
+
commands.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 SCADify contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,80 @@
|
|
|
1
|
-
#
|
|
1
|
+
# scadify
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Geometry as code: deterministic 3D solids generated from tiny JSON recipes with OpenSCAD inside, compiled on demand to clean meshes and exported as glb, gltf, stl, 3mf, usdz, usda or scad. The same recipe, seed and params give byte-for-byte identical output on the same platform. One runtime dependency (`openscad-wasm-prebuilt`, in-process OpenSCAD + Manifold); everything else is Node stdlib. Node ≥ 18.
|
|
4
|
+
|
|
5
|
+
## The pattern
|
|
6
|
+
|
|
7
|
+
A **recipe** is a small JSON file in `store/` (one per ref). It is the only thing stored; meshes are derived and disposable. Same recipe + params + seed ⇒ same bytes on the same platform.
|
|
8
|
+
|
|
9
|
+
```jsonc
|
|
10
|
+
{ "kind": "scad", // "scad": the program is the source | "csg": a boolean tree of primitives
|
|
11
|
+
"title": "demo-tray", "units": "dm", "seed": 7,
|
|
12
|
+
"program": "module tray(){ ... }",
|
|
13
|
+
"parts": { "tray": "tray();", "standoffs": "standoffs();" }, // one mesh/node per part
|
|
14
|
+
"params": { "wall_h": 12 }, // passed as -D, so they override program defaults
|
|
15
|
+
"tints": { "tray": "#3f6fb0" } } // optional #rrggbb per part
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
`kind:"csg"` uses `tree` (or `parts`) instead of `program`: nodes `{op, ...}` with ops `cube cylinder sphere translate rotate scale mirror union difference intersection hull`; transforms/booleans take `children`. A number may be `{"param":"name"}`. A csg recipe transpiles to `.scad` (`export_solid format=scad`). `seed` is injected as the OpenSCAD variable `seed`. Parts are emitted in sorted-name order.
|
|
19
|
+
|
|
20
|
+
**Units.** `units` is one of `mm`, `cm`, `dm`, `m` (metres per unit 0.001, 0.01, 0.1, 1) and defaults to `dm` when omitted, so architectural models land at true size (1 unit = 10 cm). Recipe coordinates are in that unit. Exports are normalized so imports land at true size with scale 1: GLB and USD are written in **metres** (`metersPerUnit` 1), STL and 3MF in **millimetres**. Previews render the raw recipe coordinates.
|
|
21
|
+
|
|
22
|
+
## Tools (stdio MCP, hand-rolled JSON-RPC; `node src/scadify-cli.mjs`)
|
|
23
|
+
|
|
24
|
+
| tool | does |
|
|
25
|
+
|---|---|
|
|
26
|
+
| `mint_solid {recipe}` | store a recipe → `{ref}` (`slug-<hash8>`; identical content is idempotent) |
|
|
27
|
+
| `list_solids` / `get_solid {ref}` | list refs / return the recipe |
|
|
28
|
+
| `update_solid {ref, params?, program?, parts?, tree?, title?, seed?, tints?}` | edit in place (params merge, rest replace; ref is stable) |
|
|
29
|
+
| `export_solid {ref, format}` | compile + write `out/<ref>.<format>`, `format` = `glb usdz gltf usda stl 3mf scad json` (prefer glb/usdz; stl/3mf only for printing) → `{path, format, sizeBytes, sha256, ref}` |
|
|
30
|
+
| `render_turntable {ref, frames=8 (3–36), size=256, elevation_deg=25}` | PNG frames from the in-Node software rasterizer (transparent background) |
|
|
31
|
+
| `render_shot {ref, angle_deg=0, elevation_deg=26, size=512, background='#0C1019'}` | exactly one PNG; angle 0 = model front (-y), camera orbits +z; `background` is `#rrggbb` or `transparent` → `{path, size}` |
|
|
32
|
+
| `render_standard {ref, size=1024, background='#0C1019'}` | standard preview: one square PNG, front-on shot (0°, 8° up) left and angled-high shot (30°, 32° up) right → `{path, size, panels}` |
|
|
33
|
+
| `measure_solid {ref}` | bbox, size, volume, area, triangle count, mesh checksum |
|
|
34
|
+
|
|
35
|
+
Env: `SCADIFY_STORE`, `SCADIFY_OUT` override the `store/` and `out/` dirs. The bin also has a one-shot CLI: `scadify tools`, `scadify call <tool> --json '{...}'`.
|
|
36
|
+
|
|
37
|
+
## Output notes
|
|
38
|
+
|
|
39
|
+
- **GLB/glTF**: mesh only. One flat node per part, one mesh/material (PBR baseColor from the tint). No cameras, lights, ground plane, transforms, or hierarchy. Node, mesh and material names are the part names (a numeric suffix only if a name repeats). Coordinates are in **metres**, converted to glTF's **y-up** convention ((x, y, z) → (x, z, −y); the model front −y faces +Z), so Godot, Blender, three.js etc. import it upright. glTF has no ratified units extension, so units are declared in `asset.extras` (`units: "m"`, `metersPerUnit: 1`, `sourceUnits` = the recipe's unit, `upAxis: "Y"`).
|
|
40
|
+
- **USDA/USDZ**: `upAxis="Z"`, coordinates in metres with `metersPerUnit = 1`, one Xform per part named after the part and holding a Mesh of the same name, UsdPreviewSurface materials; USDZ is a stored zip with 64-byte-aligned payload. The editing/postprocess path.
|
|
41
|
+
- **STL** (binary) and **3MF** (`unit="millimeter"`, one object per part) for print. Both are always written in millimetres: coordinates are converted from the recipe unit (×1, ×10, ×100, ×1000 for mm, cm, dm, m) so a slicer reads true size. **SCAD** is the assembled program.
|
|
42
|
+
- Not verified here: opening the files in third-party viewers (Blender, Quick Look, a slicer). Tests re-read each format structurally only.
|
|
43
|
+
|
|
44
|
+
## Examples
|
|
45
|
+
|
|
46
|
+
`examples/` ships three showcase solids. Each is a single JSON file: the `program` is plain OpenSCAD (loops, `rands(…, seed)`, list comprehensions, an in-language geodesic sphere), and `parts` are the unit of tinting. Any of them mints, compiles, exports and renders with the identical loop:
|
|
47
|
+
|
|
48
|
+
```bash
|
|
49
|
+
npm install
|
|
50
|
+
REF=$(node src/scadify-cli.mjs call mint_solid --json "{\"recipe\": $(cat examples/domed-citadel.json)}" | node -pe 'JSON.parse(require("fs").readFileSync(0)).ref')
|
|
51
|
+
for f in glb usdz; do node src/scadify-cli.mjs call export_solid --json "{\"ref\":\"$REF\",\"format\":\"$f\"}"; done
|
|
52
|
+
node src/scadify-cli.mjs call render_turntable --json "{\"ref\":\"$REF\",\"frames\":8,\"size\":256}"
|
|
53
|
+
node src/scadify-cli.mjs call measure_solid --json "{\"ref\":\"$REF\"}"
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
Files land in `out/`. `npm test` runs the suite (node:test).
|
|
57
|
+
|
|
58
|
+
### Temple ruins — `examples/temple-ruins.json`
|
|
59
|
+
|
|
60
|
+
A ruined stepped temple: hex peristyle with broken columns, crumbled cella, fallen drums and rubble. 8 parts, ~1.2k tris. `seed` drives the crumble and scatter.
|
|
61
|
+
|
|
62
|
+

|
|
63
|
+
|
|
64
|
+
### Newton Cenotaph — `examples/newton-cenotaph.json`
|
|
65
|
+
|
|
66
|
+
Boullée's cenotaph: a hollow **geodesic sphere** (generated in OpenSCAD) on stepped drums with cypress rings. `variant: 2` (default) opens a front cutaway to the navy-lined, gold-starred interior; set `variant: 1` for the closed shell with star openings. `freq` tunes the sphere (6 ≈ 9.3k tris).
|
|
67
|
+
|
|
68
|
+

|
|
69
|
+
|
|
70
|
+
### Domed citadel — `examples/domed-citadel.json`
|
|
71
|
+
|
|
72
|
+
A monumental domed building: fluted terrace, 32-bay two-storey drum with pointed-arch bays and slit windows, portico + grand stair, and a ribbed geodesic dome whose facets are three-colour raised panels. 12 parts, ~26.9k tris, `dome_freq` controls the dome.
|
|
73
|
+
|
|
74
|
+

|
|
75
|
+
|
|
76
|
+
Units are per recipe (`mm`/`cm`/`dm`/`m`, default `dm`; the three examples are `dm`), z-up, front faces −y. The preview renders are unit-independent. The same `seed` re-mints byte-identical geometry on the same platform.
|
|
77
|
+
|
|
78
|
+
## Claude plugin
|
|
79
|
+
|
|
80
|
+
`.claude-plugin/plugin.json` declares the stdio server as an `mcpServers` component (`node ${CLAUDE_PLUGIN_ROOT}/src/scadify-cli.mjs`); there is no top-level `bin/`. The plugin needs `openscad-wasm-prebuilt` installed alongside (`npm install`, or bundle `node_modules/`).
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
{
|
|
2
|
+
"kind": "scad",
|
|
3
|
+
"title": "domed-citadel",
|
|
4
|
+
"units": "dm",
|
|
5
|
+
"seed": 0,
|
|
6
|
+
"program": "\n// Domed citadel: fluted terrace, 32-bay two-storey drum with pointed arches, portico + grand stair,\n// ribbed geodesic dome with raised cell panels. Z-up, mm. Front/entrance faces -y.\ndome_freq = 6; // geodesic frequency of the dome (6 -> ~360 cells above the equator)\nN = 32; ENTRY = 24; STEP = 360 / N; // bay count; entry bay index (24 -> 270 deg = -y)\nDC = 80; DR = 86; // dome centre height, dome radius\n\n// ---------- helpers ----------\nmodule blk(c, z0, w, d, h, yaw = 0, top = 1) // block: w along x, d along y, then yaw (deg)\n translate([c[0], c[1], z0]) rotate(yaw) linear_extrude(height = h, scale = top) square([w, d], center = true);\nmodule cyl(r, z0, h, n = 64) translate([0,0,z0]) cylinder(r = r, h = h, $fn = n);\nmodule rad(th, x) rotate(th) translate([x, 0, 0]) children(); // place children at radius x, angle th\n// prism along the radial axis from r1 to r2; polygon u = tangent, v = up; tapers so adjacent bays meet\nmodule radial(th, r1, r2, z0, pts) rotate([0,0,th]) translate([r1,0,z0]) rotate([90,0,90])\n linear_extrude(height = r2 - r1, scale = [r2 / r1, 1]) polygon(pts);\n\n// pointed (equilateral) arch opening cut into a wall panel: width w, half-opening a, spring height s, panel height H\nfunction arch(w, a, s, H) = let(L = [for (k = [1:4]) let(g = 180 - k*15) [a + 2*a*cos(g), s + 2*a*sin(g)]])\n concat([[-w/2,0],[-a,0],[-a,s]], L, [for (i = [2:-1:0]) [-L[i][0], L[i][1]]], [[a,s],[a,0],[w/2,0],[w/2,H],[-w/2,H]]);\n// panel with slit windows [x, half-width, height] cut up from the bottom edge\nfunction slits(w, H, S) = concat([[-w/2,0]], [for (q = S) each [[q[0]-q[1],0],[q[0]-q[1],q[2]],[q[0],q[2]+2.2],[q[0]+q[1],q[2]],[q[0]+q[1],0]]], [[w/2,0],[w/2,H],[-w/2,H]]);\n\n// ---------- terrace + plinth ----------\nmodule terrace() {\n cyl(150, 0, 14); cyl(153, 14, 2.5); cyl(134, 16.5, 0.8);\n for (i = [0:63]) rad(i * 360 / 64, 151.2) blk([0,0], 0, 2.4, 3.4, 14); // wall ribs (fluting)\n}\nmodule terrace_trim() {\n for (i = [0:55]) { a = i * 360 / 56; if (abs(a - 270) > 7.5) rad(a, 146) { blk([0,0], 16.5, 1.8, 1.8, 7); blk([0,0], 23.5, 2.8, 2.8, 1.1); } } // rim posts, gap at the stair\n for (i = [0:7]) { a = 22.5 + i * 45; if (abs(a - 270) > 30) rad(a, 126) { blk([0,0], 16.5, 5, 5, 3); blk([0,0], 35.5, 3.6, 3.6, 6, 0, 0.01); } } // pylon base + pyramid tip\n cyl(96, 22, 3);\n}\nmodule pylons() { for (i = [0:7]) { a = 22.5 + i * 45; if (abs(a - 270) > 30) rad(a, 126) blk([0,0], 19.5, 3.6, 3.6, 16); } }\nmodule plaza() { cyl(114, 16.5, 1.6); cyl(100, 16.5, 5.5);\n for (i = [0:23]) blk([0, -202 + 4*i + 2], 0, 40, 4, (i + 1) * 25 / 24); } // grand stair treads\n\n// ---------- drum ----------\nw1 = 2 * 82 * tan(180 / N) + 0.3;\nmodule interior() cyl(79, 25, 45, 48); // dark wall seen through the arches\nmodule walls() {\n for (k = [0:N-1]) { th = k * STEP; e = (k == ENTRY);\n radial(th, 82, 90, 25, arch(w1, e ? 6.3 : 5.1, e ? 12 : 14, 27)); // lower storey: pointed-arch bays\n radial(th, 82, 90, 54.5, slits(w1, 13.5, e ? [[-4.5,1.1,9],[4.5,1.1,9]] : [[-3.6,1,9],[3.6,1,9]])); // upper storey: slit windows\n }\n cyl(90, 73, 7); cyl(89.6, 80, 11.4); // attic + dome tambour\n blk([0,-99], 52, 40, 11.5, 3.5); // portico entablature\n translate([0,-93,56.7]) rotate([90,0,0]) linear_extrude(height = 12) polygon([[-22,0],[22,0],[0,8.5]]); // pediment\n for (i = [0:23]) for (x = [-22.5, 22.5]) blk([x, -202 + 4*i + 2], 0, 5, 4, (i + 1) * 25 / 24 + 5); // stair cheek walls\n for (x = [-38, 38]) blk([x, -210], 0, 5, 5, 15); // gate posts\n}\nmodule pilasters() {\n for (k = [0:N-1]) rad(k * STEP + STEP / 2, 91.9) translate([0,0,27.2]) cylinder(r = 1.75, h = 38.8, $fn = 8);\n for (i = [0:15]) rad(i * 22.5, 92.4) blk([0,0], 73, 5, 6, 20); // buttress piers\n for (x = [-14, -5, 5, 14]) translate([x, -101.5, 27]) cylinder(r = 2.5, h = 23, $fn = 12); // portico columns\n for (x = [-22.5, 22.5]) { blk([x,-205], 0, 7, 7, 13); blk([x,-107], 25, 7, 7, 13); } // stair newels\n}\nmodule trim() {\n for (k = [0:N-1]) rad(k * STEP + STEP / 2, 91.9) { blk([0,0], 25, 4.4, 4.4, 2.2); blk([0,0], 66, 4.8, 4.8, 2.2); } // pilaster bases + capitals\n cyl(91.6, 52, 2.5); // string course\n for (i = [0:63]) rad((i + 0.5) * 360 / 64, 94.6) blk([0,0], 65.2, 1.8, 2.2, 3); // dentils\n cyl(93.5, 68.2, 1.6); cyl(96, 69.8, 1.6); cyl(97.5, 71.4, 1.6); // stepped cornice\n cyl(91.4, 91.4, 1.8); cyl(89.4, 93.2, 1.2); // tambour cap rings\n for (i = [0:15]) rad(i * 22.5, 92.4) blk([0,0], 93, 6, 7, 1.6); // pier caps\n blk([0,-99], 22, 44, 14, 3); blk([0,-99], 55.5, 42, 13, 1.2); // porch floor + roof slab\n for (x = [-14, -5, 5, 14]) { blk([x,-101.5], 25, 6.2, 6.2, 2); blk([x,-101.5], 50, 6.4, 6.4, 2); }\n for (x = [-22.5, 22.5]) { blk([x,-205], 13, 8, 8, 2); blk([x,-107], 38, 8, 8, 2); }\n for (x = [-38, 38]) blk([x,-210], 15, 6, 6, 1.5);\n}\nmodule glow() { rad(ENTRY * STEP, 80.5) blk([0,0], 25, 5, 1.2, 22); // portal glow slit\n for (x = [-38, 38]) blk([x,-210], 16.5, 3, 3, 3);\n translate([0,0,DC + DR - 1]) rotate_extrude($fn = 8) polygon([[0,0],[3.6,0],[2,5.6],[0.15,16],[0,16]]); } // gold finial\nmodule lights() { for (k = [0:N-1]) if (k != ENTRY && k % 3 == 0) rad(k * STEP, 80.6) blk([0,0], 27, 4, 1, 13); }\n\n// ---------- dome: geodesic cells, each an inset raised panel ----------\nphi = (1 + sqrt(5)) / 2;\nfunction nrm(v) = v / norm(v);\nIV = [for (p = [[-1,phi,0],[1,phi,0],[-1,-phi,0],[1,-phi,0],[0,-1,phi],[0,1,phi],[0,-1,-phi],[0,1,-phi],[phi,0,-1],[phi,0,1],[-phi,0,-1],[-phi,0,1]]) nrm(p)];\nIF = [[0,11,5],[0,5,1],[0,1,7],[0,7,10],[0,10,11],[1,5,9],[5,11,4],[11,10,2],[10,7,6],[7,1,8],[3,9,4],[3,4,2],[3,2,6],[3,6,8],[3,8,9],[4,9,5],[2,4,11],[6,2,10],[8,6,7],[9,8,1]];\nfunction gp(A,B,C,f,i,j) = nrm(A + (B-A)*i/f + (C-A)*j/f);\nfunction tris(f) = [for (fc = IF) let(A = IV[fc[0]], B = IV[fc[1]], C = IV[fc[2]])\n each [for (i = [0:f-1]) for (j = [0:f-1-i]) each concat(\n [[gp(A,B,C,f,i,j), gp(A,B,C,f,i+1,j), gp(A,B,C,f,i,j+1)]],\n (i + j <= f-2) ? [[gp(A,B,C,f,i+1,j), gp(A,B,C,f,i+1,j+1), gp(A,B,C,f,i,j+1)]] : [])]];\nTR = tris(dome_freq);\nmodule cell(t, ro, ri, s) {\n g = (t[0] + t[1] + t[2]) / 3 * ro; o = [for (k = [0:2]) g + (t[k]*ro - g) * s];\n polyhedron(points = concat(o, [for (k = [0:2]) t[k]*ri]), faces = [[0,2,1],[3,4,5],[0,1,4,3],[1,2,5,4],[2,0,3,5]]);\n}\nfunction above(i) = (TR[i][0][2] + TR[i][1][2] + TR[i][2][2]) / 3 >= -0.03; // keep the upper hemisphere\nfunction cls(i) = (i % 7 == 0) ? 2 : (i % 5 == 0) ? 1 : 0; // 0 peach, 1 coral, 2 lavender\nmodule dome(c) translate([0,0,DC]) for (i = [0:len(TR)-1]) if (above(i) && cls(i) == c) cell(TR[i], DR + 1.1, DR - 3, 0.72);\n\nfunction rp(a, j) = let(f = j / 12 * 86, Rr = DR + 2.2) [Rr*cos(f)*cos(a), Rr*cos(f)*sin(a), DC + Rr*sin(f)];\nmodule ribs() for (i = [0:15]) for (j = [0:11])\n hull() { translate(rp(i * 22.5, j)) sphere(r = 1.1, $fn = 6); translate(rp(i * 22.5, j + 1)) sphere(r = 1.1, $fn = 6); }\n",
|
|
7
|
+
"parts": {
|
|
8
|
+
"terrace": "terrace()",
|
|
9
|
+
"plaza": "plaza()",
|
|
10
|
+
"walls": "walls()",
|
|
11
|
+
"trim": "trim(); terrace_trim();",
|
|
12
|
+
"pilasters": "pilasters(); pylons();",
|
|
13
|
+
"interior": "interior()",
|
|
14
|
+
"glow": "glow()",
|
|
15
|
+
"lights": "lights()",
|
|
16
|
+
"dome": "dome(0)",
|
|
17
|
+
"dome_coral": "dome(1)",
|
|
18
|
+
"dome_lavender": "dome(2)",
|
|
19
|
+
"ribs": "ribs()"
|
|
20
|
+
},
|
|
21
|
+
"params": {
|
|
22
|
+
"dome_freq": 6
|
|
23
|
+
},
|
|
24
|
+
"tints": {
|
|
25
|
+
"terrace": "#3e4862",
|
|
26
|
+
"plaza": "#7c6258",
|
|
27
|
+
"walls": "#4a5675",
|
|
28
|
+
"trim": "#7b86a8",
|
|
29
|
+
"pilasters": "#5f6d92",
|
|
30
|
+
"interior": "#1f2740",
|
|
31
|
+
"glow": "#ffdca0",
|
|
32
|
+
"lights": "#b7c6ff",
|
|
33
|
+
"dome": "#f1d3c3",
|
|
34
|
+
"dome_coral": "#eba597",
|
|
35
|
+
"dome_lavender": "#cdb0d6",
|
|
36
|
+
"ribs": "#7e6670"
|
|
37
|
+
}
|
|
38
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
{
|
|
2
|
+
"kind": "scad",
|
|
3
|
+
"title": "newton-cenotaph",
|
|
4
|
+
"units": "dm",
|
|
5
|
+
"seed": 0,
|
|
6
|
+
"program": "\n// Newton Cenotaph (Boullee): hollow geodesic sphere on stepped drums with cypress rings. Z-up, mm.\n// variant 1 = closed shell with star openings, 2 = front cutaway (default). freq = geodesic frequency.\nvariant = 2;\nfreq = 6;\nR = 50; T = 2.5; // sphere outer radius, wall thickness\nDC = 60; // sphere centre height\n\n// ---- geodesic sphere: icosahedron subdivided `freq` times, as a list of unit-vector triangles ----\nphi = (1 + sqrt(5)) / 2;\nfunction nrm(v) = v / norm(v);\nIV = [for (p = [[-1,phi,0],[1,phi,0],[-1,-phi,0],[1,-phi,0],[0,-1,phi],[0,1,phi],[0,-1,-phi],[0,1,-phi],[phi,0,-1],[phi,0,1],[-phi,0,-1],[-phi,0,1]]) nrm(p)];\nIF = [[0,11,5],[0,5,1],[0,1,7],[0,7,10],[0,10,11],[1,5,9],[5,11,4],[11,10,2],[10,7,6],[7,1,8],[3,9,4],[3,4,2],[3,2,6],[3,6,8],[3,8,9],[4,9,5],[2,4,11],[6,2,10],[8,6,7],[9,8,1]];\nfunction gp(A,B,C,f,i,j) = nrm(A + (B-A)*i/f + (C-A)*j/f);\nfunction tris(f) = [for (fc = IF) let(A = IV[fc[0]], B = IV[fc[1]], C = IV[fc[2]])\n each [for (i = [0:f-1]) for (j = [0:f-1-i]) each concat(\n [[gp(A,B,C,f,i,j), gp(A,B,C,f,i+1,j), gp(A,B,C,f,i,j+1)]],\n (i + j <= f-2) ? [[gp(A,B,C,f,i+1,j), gp(A,B,C,f,i+1,j+1), gp(A,B,C,f,i,j+1)]] : [])]];\nTR = tris(freq);\n\n// triangular prism between radius ri and ro (top triangle inset toward its centre by factor s)\nmodule cell(t, ro, ri, s = 1) {\n g = (t[0] + t[1] + t[2]) / 3 * ro;\n o = [for (k = [0:2]) g + (t[k]*ro - g) * s];\n polyhedron(points = concat(o, [for (k = [0:2]) t[k]*ri]),\n faces = [[0,2,1],[3,4,5],[0,1,4,3],[1,2,5,4],[2,0,3,5]]);\n}\n\n// which cells exist: variant 2 cuts a cone out of the front (-y); variant 1 punches every 13th facet\nfunction cut(i) = (variant == 2) ? (nrm(TR[i][0]+TR[i][1]+TR[i][2]) * nrm([0,-1,0.1]) > 0.62) : (i % 13 == 0);\n\nmodule shell() { translate([0,0,DC]) for (i = [0:len(TR)-1]) if (!cut(i)) cell(TR[i], R, R - T); }\nmodule lining() { translate([0,0,DC]) for (i = [0:len(TR)-1]) if (!cut(i)) cell(TR[i], R - T, R - T - 0.4); }\nmodule stars() { translate([0,0,DC]) for (i = [0:len(TR)-1]) if (!cut(i) && i % 6 == 0) cell(TR[i], R - T - 0.4, R - T - 0.7); }\n\n// ---- base ----\nmodule disc(r, z, h, n = 40) translate([0,0,z]) cylinder(r = r, h = h, $fn = n);\nmodule base() { disc(92, 0, 9); disc(78, 9, 5); disc(66, 14, 4); }\n\nmodule cypress(x, y, z)\n translate([x, y, z]) rotate_extrude($fn = 5) polygon([[0,0],[0.3,0],[1.7,4.25],[1.3,10.2],[0.05,17],[0,17]]);\nmodule trees() {\n for (i = [0:55]) { a = i / 56 * 360; if (!(a > 260 && a < 280)) cypress(85*cos(a), 85*sin(a), 9); } // gap at the entrance (-y)\n for (i = [0:45]) { a = (i + 0.5) / 46 * 360; cypress(71*cos(a), 71*sin(a), 14); }\n}\n\nmodule bx(c, z, w, d, h) translate([c[0], c[1], z]) translate([-w/2, -d/2, 0]) cube([w, d, h]);\nmodule portal() { bx([-7.5,-91], 0, 4, 5, 9.5); bx([7.5,-91], 0, 4, 5, 9.5); bx([0,-91], 8.2, 19, 5, 2.2);\n bx([0,-97], 0, 22, 6, 1.5); bx([0,-94], 0, 20, 4, 3); }\nmodule door() { bx([0,-90.2], 0, 11, 4, 8.2); }\n\n// ---- interior: floor, brass armillary on a chain ----\nmodule floor_disc() disc(24, 18.35, 0.4, 24); // lifted a hair off the plinth top (z=18) to kill the coplanar z-fight\nmodule armillary() {\n translate([0,0,DC-15]) {\n for (o = [[0,0,0],[90,0,0],[90,90,0],[45,45,0]]) rotate(o) rotate_extrude($fn = 16) translate([13,0]) circle(r = 0.55, $fn = 4);\n sphere(r = 4, $fn = 8);\n }\n translate([0,0,DC-2]) cylinder(r = 0.35, h = R + 1, $fn = 4);\n}\n",
|
|
7
|
+
"parts": {
|
|
8
|
+
"shell": "shell()",
|
|
9
|
+
"lining": "lining()",
|
|
10
|
+
"stars": "stars()",
|
|
11
|
+
"base": "base()",
|
|
12
|
+
"trees": "trees()",
|
|
13
|
+
"portal": "portal()",
|
|
14
|
+
"door": "door()",
|
|
15
|
+
"floor": "floor_disc()",
|
|
16
|
+
"armillary": "armillary()"
|
|
17
|
+
},
|
|
18
|
+
"params": {
|
|
19
|
+
"variant": 2,
|
|
20
|
+
"freq": 6
|
|
21
|
+
},
|
|
22
|
+
"tints": {
|
|
23
|
+
"shell": "#d9d1bd",
|
|
24
|
+
"lining": "#1c2038",
|
|
25
|
+
"stars": "#f6e9a9",
|
|
26
|
+
"base": "#b8ad92",
|
|
27
|
+
"trees": "#34502f",
|
|
28
|
+
"portal": "#a99e84",
|
|
29
|
+
"door": "#1b1a1c",
|
|
30
|
+
"floor": "#2a2a33",
|
|
31
|
+
"armillary": "#b8923f"
|
|
32
|
+
}
|
|
33
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
{
|
|
2
|
+
"kind": "scad",
|
|
3
|
+
"title": "temple-ruins",
|
|
4
|
+
"units": "dm",
|
|
5
|
+
"seed": 7,
|
|
6
|
+
"program": "\n// Temple ruins: stepped stylobate, 10 hex columns (some broken), crumbled cella, rubble. Z-up, mm.\nR = rands(0, 1, 600, seed);\nTOP = 4.5; // top of the stylobate\nH = 14; // full column height\n\n// block centred on c=[x,y], base z0, w x d x h, yaw in degrees, top = taper factor (<1 narrows the top)\nmodule blk(c, z0, w, d, h, yaw = 0, top = 1)\n translate([c[0], c[1], z0]) rotate(yaw) linear_extrude(height = h, scale = top) square([w, d], center = true);\n\n// hexagonal column (lathe with 6 sides)\nmodule column(h, r)\n rotate_extrude($fn = 6) polygon([[0,0],[r*1.2,0],[r*1.2,h*0.07],[r,h*0.09],[r*0.78,h],[0,h]]);\n\n// fallen drum lying on its side, axis horizontal, yaw in degrees\nmodule drum(p, z, len, yaw, r = 2)\n translate([p[0], p[1], z]) rotate([0, 0, yaw]) rotate([0, 90, 0]) cylinder(h = len, r1 = r*0.95, r2 = r*0.9, $fn = 6);\n\n// [x, y, broken height]; 0 means intact\ncols = [[-18,-12,0],[-6,-12,0],[6,-12,9],[18,-12,4.5],[-18,12,0],[-6,12,11],[6,12,0],[18,12,0],[-18,0,7],[18,0,2.5]];\n\nmodule steps() { for (i = [0:2]) blk([0,0], i*1.5, [60,54,48][i], [44,38,32][i], 1.5); }\nmodule columns() { for (c = cols) translate([c[0], c[1], TOP]) column(c[2] > 0 ? c[2] : H, 2); }\nmodule capitals() { for (c = cols) if (c[2] == 0) blk([c[0], c[1]], TOP + H, 5.4, 5.4, 1.3); }\nmodule lintels() { blk([-12,-12], TOP + H + 1.3, 14.5, 3.4, 2.6); blk([12,12], TOP + H + 1.3, 14.5, 3.4, 2.6); }\n\n// wall of stacked courses; each segment keeps 0-4 courses (the crumble)\nmodule wall(p0, p1, t, off) {\n len = norm(p1 - p0); n = max(1, round(len / 5)); yaw = atan2(p1[1]-p0[1], p1[0]-p0[0]);\n for (i = [0:n-1]) {\n c = p0 + (p1 - p0) * ((i + 0.5) / n); k = floor(R[off + i] * 5);\n if (k > 0) for (j = [0:k-1]) blk(c, TOP + j*2.6, len/n - 0.15, t, 2.6, yaw);\n }\n}\nmodule cella() {\n wall([-10,8],[10,8],2.6,0); wall([-10,-4],[-10,8],2.6,10); wall([10,-4],[10,8],2.6,20);\n blk([-10,-5], TOP, 2.6, 2.6, 6); blk([10,-5], TOP, 2.6, 2.6, 3.2); // broken door jambs\n blk([0,3], TOP, 5, 5, 2.4); blk([0,3], TOP + 2.4, 3.4, 3.4, 1.2); // altar\n}\nmodule fallen() {\n drum([-26,-29], 2, 7, 6); drum([-18.5,-28.4], 2, 7, 0); drum([-10,-30.5], 2, 6, -20);\n drum([-3,-4], TOP + 1.9, 8.94, -26.6, 1.9); // drum lying on the top step\n blk([14,-29], 0, 5.4, 5.4, 1.3, 28.6); blk([32,-12], 0, 12, 3.4, 2.6, 51.6); // capital + lintel chunk\n}\nmodule rubble() {\n for (i = [0:33]) { // ground rubble outside the base footprint\n x = (R[100+i*7]*2-1)*40; y = (R[101+i*7]*2-1)*36;\n if (!(abs(x) < 33 && abs(y) < 25))\n blk([x,y], 0, 1.2+R[102+i*7]*2, 1.2+R[103+i*7]*2, 0.8+R[104+i*7]*1.4, R[105+i*7]*180, 0.6+R[106+i*7]*0.4);\n }\n for (i = [0:6]) // rubble on the platform\n blk([(R[400+i*6]*2-1)*22, -14+R[401+i*6]*8], TOP, 1+R[402+i*6]*1.4, 1+R[403+i*6]*1.4, 0.6+R[404+i*6]*0.8, R[405+i*6]*180, 0.7);\n}\nmodule moss() {\n for (p = [[-24,-18,3,2],[22,-19,4,2.2],[0,-17,5,2],[-27,10,3,2],[26,9,3,2.5]])\n blk([p[0],p[1]], 3.0, p[2], p[3], 0.25, p[0]*7, 0.8);\n}\n",
|
|
7
|
+
"parts": {
|
|
8
|
+
"steps": "steps()",
|
|
9
|
+
"columns": "columns()",
|
|
10
|
+
"capitals": "capitals()",
|
|
11
|
+
"lintels": "lintels()",
|
|
12
|
+
"cella": "cella()",
|
|
13
|
+
"fallen": "fallen()",
|
|
14
|
+
"rubble": "rubble()",
|
|
15
|
+
"moss": "moss()"
|
|
16
|
+
},
|
|
17
|
+
"params": {},
|
|
18
|
+
"tints": {
|
|
19
|
+
"steps": "#bfa97e",
|
|
20
|
+
"columns": "#c9b48a",
|
|
21
|
+
"capitals": "#b39d74",
|
|
22
|
+
"lintels": "#c9b48a",
|
|
23
|
+
"cella": "#b39d74",
|
|
24
|
+
"fallen": "#c9b48a",
|
|
25
|
+
"rubble": "#8f8268",
|
|
26
|
+
"moss": "#6b7f4a"
|
|
27
|
+
}
|
|
28
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,19 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "scadify",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
1
|
+
{
|
|
2
|
+
"name": "scadify",
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "Deterministic recipes -> clean 3D solids (OpenSCAD/Manifold WASM), exported to GLB/STL/3MF/USDZ.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"bin": {
|
|
7
|
+
"scadify": "src/scadify-cli.mjs"
|
|
8
|
+
},
|
|
9
|
+
"scripts": {
|
|
10
|
+
"test": "node --test tests/"
|
|
11
|
+
},
|
|
12
|
+
"engines": {
|
|
13
|
+
"node": ">=18"
|
|
14
|
+
},
|
|
15
|
+
"license": "MIT",
|
|
16
|
+
"dependencies": {
|
|
17
|
+
"openscad-wasm-prebuilt": "^1.2.0"
|
|
18
|
+
}
|
|
19
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
// Shared by the interchange emitters (glb, usd): meters normalization + part naming.
|
|
2
|
+
import { metersPerUnit } from '../recipe.js';
|
|
3
|
+
|
|
4
|
+
/** Recipe-unit positions -> metres (Float32Array). mm*0.001, cm*0.01, dm*0.1, m*1. Interchange formats are always 1 unit = 1 m. */
|
|
5
|
+
export function positionsInMeters(positions, recipe) {
|
|
6
|
+
const f = metersPerUnit(recipe);
|
|
7
|
+
return f === 1 ? positions : Float32Array.from(positions, (v) => v * f);
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
/** Names for exported nodes/prims: the part names themselves; a numeric suffix (_2, _3, ...) only when a name repeats
|
|
11
|
+
* or hits a reserved sibling name. */
|
|
12
|
+
export function uniqueNames(names, reserved = []) {
|
|
13
|
+
const used = new Set(reserved); const out = [];
|
|
14
|
+
for (const n of names) {
|
|
15
|
+
let u = n; for (let k = 2; used.has(u); k++) u = `${n}_${k}`;
|
|
16
|
+
used.add(u); out.push(u);
|
|
17
|
+
}
|
|
18
|
+
return out;
|
|
19
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
// Clean GLB: mesh only. Flat tree = one node per part (mesh under it). No cameras, lights, ground, hierarchy.
|
|
2
|
+
// Coordinates are written in METRES (recipe units scaled by the unit's metres-per-unit) and converted from the recipe's z-up to glTF's
|
|
3
|
+
// y-up (x, y, z) -> (x, z, -y): up stays up, the model front (-y) faces glTF +Z. A proper rotation, so triangle winding is unchanged.
|
|
4
|
+
// asset.extras records units 'm' / metersPerUnit 1
|
|
5
|
+
// since glTF has no ratified units extension. Node, mesh and material names are the part names.
|
|
6
|
+
import { positionsInMeters, uniqueNames } from './common.js';
|
|
7
|
+
|
|
8
|
+
function zUpToYUp(pos) {
|
|
9
|
+
const out = new Float32Array(pos.length);
|
|
10
|
+
for (let i = 0; i < pos.length; i += 3) { out[i] = pos[i]; out[i + 1] = pos[i + 2]; out[i + 2] = -pos[i + 1]; }
|
|
11
|
+
return out;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
const hex = (h) => [1, 3, 5].map((i) => parseInt(h.slice(i, i + 2), 16) / 255);
|
|
15
|
+
const pad4 = (b, fill = 0) => (b.length % 4 ? Buffer.concat([b, Buffer.alloc(4 - (b.length % 4), fill)]) : b);
|
|
16
|
+
|
|
17
|
+
function build(recipe, mesh) {
|
|
18
|
+
const bufs = []; const bufferViews = []; const accessors = []; const meshes = []; const nodes = []; const materials = [];
|
|
19
|
+
let len = 0;
|
|
20
|
+
const view = (b, target) => { const bb = pad4(b); bufferViews.push({ buffer: 0, byteOffset: len, byteLength: b.length, target }); bufs.push(bb); len += bb.length; return bufferViews.length - 1; };
|
|
21
|
+
const names = uniqueNames(mesh.parts.map((p) => p.name));
|
|
22
|
+
for (const [pi, part] of mesh.parts.entries()) {
|
|
23
|
+
const p = { ...part, positions: zUpToYUp(positionsInMeters(part.positions, recipe)) }; const name = names[pi];
|
|
24
|
+
const min = [Infinity, Infinity, Infinity], max = [-Infinity, -Infinity, -Infinity];
|
|
25
|
+
for (let i = 0; i < p.positions.length; i += 3) for (let a = 0; a < 3; a++) { min[a] = Math.min(min[a], p.positions[i + a]); max[a] = Math.max(max[a], p.positions[i + a]); }
|
|
26
|
+
const pv = view(Buffer.from(p.positions.buffer, p.positions.byteOffset, p.positions.byteLength), 34962);
|
|
27
|
+
accessors.push({ bufferView: pv, componentType: 5126, count: p.positions.length / 3, type: 'VEC3', min, max });
|
|
28
|
+
const iv = view(Buffer.from(p.indices.buffer, p.indices.byteOffset, p.indices.byteLength), 34963);
|
|
29
|
+
accessors.push({ bufferView: iv, componentType: 5125, count: p.indices.length, type: 'SCALAR' });
|
|
30
|
+
materials.push({ name, pbrMetallicRoughness: { baseColorFactor: [...hex(p.tint), 1], metallicFactor: 0, roughnessFactor: 0.6 } });
|
|
31
|
+
meshes.push({ name, primitives: [{ attributes: { POSITION: accessors.length - 2 }, indices: accessors.length - 1, material: materials.length - 1, mode: 4 }] });
|
|
32
|
+
nodes.push({ name, mesh: meshes.length - 1 });
|
|
33
|
+
}
|
|
34
|
+
const json = {
|
|
35
|
+
asset: { version: '2.0', generator: 'scadify', extras: { units: 'm', metersPerUnit: 1, sourceUnits: recipe.units, upAxis: 'Y', title: recipe.title } },
|
|
36
|
+
scene: 0, scenes: [{ name: recipe.title, nodes: nodes.map((_, i) => i) }],
|
|
37
|
+
nodes, meshes, materials, accessors, bufferViews, buffers: [{ byteLength: len }],
|
|
38
|
+
};
|
|
39
|
+
return { json, bin: Buffer.concat(bufs) };
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function emitGLTF(recipe, mesh) {
|
|
43
|
+
const { json, bin } = build(recipe, mesh);
|
|
44
|
+
json.buffers[0].uri = `data:application/octet-stream;base64,${bin.toString('base64')}`;
|
|
45
|
+
return JSON.stringify(json, null, 1) + '\n';
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function emitGLB(recipe, mesh) {
|
|
49
|
+
const { json, bin } = build(recipe, mesh);
|
|
50
|
+
const j = pad4(Buffer.from(JSON.stringify(json)), 0x20);
|
|
51
|
+
const total = 12 + 8 + j.length + 8 + bin.length;
|
|
52
|
+
const h = Buffer.alloc(12 + 8); h.writeUInt32LE(0x46546c67, 0); h.writeUInt32LE(2, 4); h.writeUInt32LE(total, 8); h.writeUInt32LE(j.length, 12); h.writeUInt32LE(0x4e4f534a, 16);
|
|
53
|
+
const bh = Buffer.alloc(8); bh.writeUInt32LE(bin.length, 0); bh.writeUInt32LE(0x004e4942, 4);
|
|
54
|
+
return Buffer.concat([h, j, bh, bin]);
|
|
55
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
// The program itself, assembled: params, program, each part as a tinted block. For csg recipes this is the transpile.
|
|
2
|
+
import { toScadParts, scadValue } from '../recipe.js';
|
|
3
|
+
import { partTint } from '../recipe.js';
|
|
4
|
+
|
|
5
|
+
export function emitSCAD(recipe) {
|
|
6
|
+
const { program, partCode } = toScadParts(recipe);
|
|
7
|
+
const params = Object.entries({ seed: recipe.seed, ...recipe.params }).map(([k, v]) => `${k} = ${scadValue(v)};`).join('\n');
|
|
8
|
+
const blocks = Object.keys(recipe.parts).map((n) => `// part: ${n}\ncolor("${partTint(recipe, n)}") {\n${partCode[n]}\n}`).join('\n\n');
|
|
9
|
+
return `// scadify: ${recipe.title} (units: ${recipe.units})\n${program}\n\n// recipe params (override program defaults)\n${params}\n\n${blocks}\n`;
|
|
10
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
// Binary STL, all parts merged, written in MILLIMETRES (print convention) whatever the recipe unit. Fixed header -> deterministic.
|
|
2
|
+
import { metersPerUnit } from '../recipe.js';
|
|
3
|
+
|
|
4
|
+
export function emitSTL(recipe, mesh) {
|
|
5
|
+
const k = metersPerUnit(recipe) * 1000; // recipe units -> mm (1 for mm recipes, so their bytes are unchanged)
|
|
6
|
+
const n = mesh.parts.reduce((a, p) => a + p.indices.length / 3, 0);
|
|
7
|
+
const buf = Buffer.alloc(84 + n * 50);
|
|
8
|
+
buf.write(`scadify ${recipe.title}`.slice(0, 80), 0, 'latin1');
|
|
9
|
+
buf.writeUInt32LE(n, 80);
|
|
10
|
+
let o = 84;
|
|
11
|
+
for (const { positions: P0, indices: I } of mesh.parts) {
|
|
12
|
+
const P = k === 1 ? P0 : Float64Array.from(P0, (v) => v * k);
|
|
13
|
+
for (let t = 0; t < I.length; t += 3) {
|
|
14
|
+
const a = I[t] * 3, b = I[t + 1] * 3, c = I[t + 2] * 3;
|
|
15
|
+
const ux = P[b] - P[a], uy = P[b + 1] - P[a + 1], uz = P[b + 2] - P[a + 2];
|
|
16
|
+
const vx = P[c] - P[a], vy = P[c + 1] - P[a + 1], vz = P[c + 2] - P[a + 2];
|
|
17
|
+
let nx = uy * vz - uz * vy, ny = uz * vx - ux * vz, nz = ux * vy - uy * vx;
|
|
18
|
+
const l = Math.hypot(nx, ny, nz) || 1; nx /= l; ny /= l; nz /= l;
|
|
19
|
+
for (const v of [nx, ny, nz, P[a], P[a + 1], P[a + 2], P[b], P[b + 1], P[b + 2], P[c], P[c + 1], P[c + 2]]) { buf.writeFloatLE(v, o); o += 4; }
|
|
20
|
+
o += 2;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
return buf;
|
|
24
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
// 3MF (print): one object per part, written in MILLIMETRES (unit="millimeter") whatever the recipe unit, zipped deterministically.
|
|
2
|
+
import { zip } from './zip.js';
|
|
3
|
+
import { metersPerUnit } from '../recipe.js';
|
|
4
|
+
const esc = (s) => String(s).replace(/[<>&"]/g, (c) => ({ '<': '<', '>': '>', '&': '&', '"': '"' }[c]));
|
|
5
|
+
const f = (x) => +x.toFixed(5);
|
|
6
|
+
export function emit3MF(recipe, mesh) {
|
|
7
|
+
const mm = metersPerUnit(recipe) * 1000; // recipe units -> mm
|
|
8
|
+
let objs = '', items = '';
|
|
9
|
+
mesh.parts.forEach((p, i) => {
|
|
10
|
+
const id = i + 1; let v = '', t = '';
|
|
11
|
+
for (let j = 0; j < p.positions.length; j += 3) v += `<vertex x="${f(p.positions[j] * mm)}" y="${f(p.positions[j + 1] * mm)}" z="${f(p.positions[j + 2] * mm)}"/>`;
|
|
12
|
+
for (let k = 0; k < p.indices.length; k += 3) t += `<triangle v1="${p.indices[k]}" v2="${p.indices[k + 1]}" v3="${p.indices[k + 2]}"/>`;
|
|
13
|
+
objs += `<object id="${id}" name="${esc(p.name)}" type="model"><mesh><vertices>${v}</vertices><triangles>${t}</triangles></mesh></object>`;
|
|
14
|
+
items += `<item objectid="${id}"/>`;
|
|
15
|
+
});
|
|
16
|
+
const model = `<?xml version="1.0" encoding="UTF-8"?>\n<model unit="millimeter" xml:lang="en-US" xmlns="http://schemas.microsoft.com/3dmanufacturing/core/2015/02"><metadata name="Title">${esc(recipe.title)}</metadata><metadata name="Application">scadify</metadata><resources>${objs}</resources><build>${items}</build></model>`;
|
|
17
|
+
return zip([
|
|
18
|
+
{ name: '[Content_Types].xml', data: '<?xml version="1.0" encoding="UTF-8"?>\n<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="model" ContentType="application/vnd.ms-package.3dmanufacturing-3dmodel+xml"/></Types>' },
|
|
19
|
+
{ name: '_rels/.rels', data: '<?xml version="1.0" encoding="UTF-8"?>\n<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Target="/3D/3dmodel.model" Id="rel0" Type="http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel"/></Relationships>' },
|
|
20
|
+
{ name: '3D/3dmodel.model', data: model },
|
|
21
|
+
]);
|
|
22
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
// USDA text + USDZ (uncompressed zip, 64-byte aligned). Z-up, coordinates in METRES (metersPerUnit = 1). One Xform per part, named after the part, holding a Mesh with the same name.
|
|
2
|
+
import { zip } from './zip.js';
|
|
3
|
+
import { slug } from '../recipe.js';
|
|
4
|
+
import { positionsInMeters, uniqueNames } from './common.js';
|
|
5
|
+
|
|
6
|
+
const hex = (h) => [1, 3, 5].map((i) => +(parseInt(h.slice(i, i + 2), 16) / 255).toFixed(4));
|
|
7
|
+
const g = (x) => String(+x.toPrecision(7));
|
|
8
|
+
const ident = (s) => { const t = String(s).replace(/[^A-Za-z0-9_]/g, '_'); return /^[A-Za-z_]/.test(t) ? t : `_${t}`; };
|
|
9
|
+
|
|
10
|
+
export function emitUSDA(recipe, mesh) {
|
|
11
|
+
const root = ident(slug(recipe.title).replace(/-/g, '_'));
|
|
12
|
+
let body = '';
|
|
13
|
+
let mats = '';
|
|
14
|
+
const names = uniqueNames(mesh.parts.map((p) => ident(p.name)), ['Materials']); // 'Materials' is the sibling Scope
|
|
15
|
+
for (const [pi, p] of mesh.parts.entries()) {
|
|
16
|
+
const n = names[pi]; const c = hex(p.tint);
|
|
17
|
+
const P = positionsInMeters(p.positions, recipe); const pts = []; for (let i = 0; i < P.length; i += 3) pts.push(`(${g(P[i])}, ${g(P[i + 1])}, ${g(P[i + 2])})`);
|
|
18
|
+
const ext = [[Infinity, Infinity, Infinity], [-Infinity, -Infinity, -Infinity]];
|
|
19
|
+
for (let i = 0; i < P.length; i += 3) for (let a = 0; a < 3; a++) { ext[0][a] = Math.min(ext[0][a], P[i + a]); ext[1][a] = Math.max(ext[1][a], P[i + a]); }
|
|
20
|
+
body += ` def Xform "${n}"\n {\n def Mesh "${n}"\n {\n` +
|
|
21
|
+
` int[] faceVertexCounts = [${new Array(p.indices.length / 3).fill(3).join(', ')}]\n` +
|
|
22
|
+
` int[] faceVertexIndices = [${Array.from(p.indices).join(', ')}]\n` +
|
|
23
|
+
` point3f[] points = [${pts.join(', ')}]\n` +
|
|
24
|
+
` float3[] extent = [(${ext[0].map(g).join(', ')}), (${ext[1].map(g).join(', ')})]\n` +
|
|
25
|
+
` uniform token subdivisionScheme = "none"\n uniform bool doubleSided = 0\n` +
|
|
26
|
+
` color3f[] primvars:displayColor = [(${c.join(', ')})]\n` +
|
|
27
|
+
` rel material:binding = </${root}/Materials/${n}>\n }\n }\n`;
|
|
28
|
+
mats += ` def Material "${n}"\n {\n token outputs:surface.connect = </${root}/Materials/${n}/pbr.outputs:surface>\n` +
|
|
29
|
+
` def Shader "pbr"\n {\n uniform token info:id = "UsdPreviewSurface"\n` +
|
|
30
|
+
` color3f inputs:diffuseColor = (${c.join(', ')})\n float inputs:metallic = 0\n float inputs:roughness = 0.6\n` +
|
|
31
|
+
` token outputs:surface\n }\n }\n`;
|
|
32
|
+
}
|
|
33
|
+
return `#usda 1.0\n(\n defaultPrim = "${root}"\n metersPerUnit = 1\n upAxis = "Z"\n doc = "scadify: ${recipe.title.replace(/["\\\n]/g, ' ')}"\n)\n\n` +
|
|
34
|
+
`def Xform "${root}"\n{\n${body} def Scope "Materials"\n {\n${mats} }\n}\n`;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function emitUSDZ(recipe, mesh) {
|
|
38
|
+
const usda = emitUSDA(recipe, mesh);
|
|
39
|
+
return zip([{ name: `${slug(recipe.title)}.usda`, data: usda }], { align: 64 });
|
|
40
|
+
}
|