@bitbybit-dev/create-app 1.3.2-rc.1 → 1.4.0-rc.0
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/README.md +47 -124
- package/dist/index.js +253 -21
- package/dist/index.js.map +1 -1
- package/dist/scaffold.d.ts +30 -0
- package/dist/scaffold.d.ts.map +1 -0
- package/dist/scaffold.js +107 -0
- package/dist/scaffold.js.map +1 -0
- package/package.json +4 -3
- package/src/index.test.ts +309 -8
- package/src/index.ts +285 -24
- package/src/scaffold.test.ts +177 -0
- package/src/scaffold.ts +99 -0
- package/templates/_agent/AGENTS.md +39 -0
- package/templates/_agent/CLAUDE.md +1 -0
- package/templates/_agent/_dot-cursor/mcp.json +5 -0
- package/templates/_agent/_dot-gitignore +7 -0
- package/templates/_agent/_dot-mcp.json +5 -0
- package/templates/_agent/_dot-vscode/mcp.json +5 -0
- package/templates/apps/drone-assembly/AGENTS.section.md +20 -0
- package/templates/apps/drone-assembly/README.md +35 -0
- package/templates/apps/drone-assembly/eslint.config.js +47 -0
- package/templates/apps/drone-assembly/index.html +17 -0
- package/templates/apps/drone-assembly/package.json +31 -0
- package/templates/apps/drone-assembly/public/favicon.ico +0 -0
- package/templates/apps/drone-assembly/public/logo.png +0 -0
- package/templates/apps/drone-assembly/scripts/smoke.ts +172 -0
- package/templates/apps/drone-assembly/src/assembly.ts +99 -0
- package/templates/apps/drone-assembly/src/exports.ts +10 -0
- package/templates/apps/drone-assembly/src/kernel.ts +14 -0
- package/templates/apps/drone-assembly/src/main.ts +298 -0
- package/templates/apps/drone-assembly/src/materials.ts +58 -0
- package/templates/apps/drone-assembly/src/model.ts +280 -0
- package/templates/apps/drone-assembly/src/parts.ts +343 -0
- package/templates/apps/drone-assembly/src/style.css +219 -0
- package/templates/apps/drone-assembly/src/ui.ts +180 -0
- package/templates/apps/drone-assembly/src/vite-env.d.ts +1 -0
- package/templates/apps/drone-assembly/tsconfig.json +29 -0
- package/templates/apps/laser-cut-box/AGENTS.section.md +17 -0
- package/templates/apps/laser-cut-box/README.md +34 -0
- package/templates/apps/laser-cut-box/eslint.config.js +47 -0
- package/templates/apps/laser-cut-box/index.html +17 -0
- package/templates/apps/laser-cut-box/package.json +30 -0
- package/templates/apps/laser-cut-box/public/favicon.ico +0 -0
- package/templates/apps/laser-cut-box/public/logo.png +0 -0
- package/templates/apps/laser-cut-box/scripts/smoke.ts +106 -0
- package/templates/apps/laser-cut-box/src/exports.ts +28 -0
- package/templates/apps/laser-cut-box/src/main.ts +176 -0
- package/templates/apps/laser-cut-box/src/model.ts +92 -0
- package/templates/apps/laser-cut-box/src/panels.ts +229 -0
- package/templates/apps/laser-cut-box/src/style.css +223 -0
- package/templates/apps/laser-cut-box/src/ui.ts +136 -0
- package/templates/apps/laser-cut-box/src/vite-env.d.ts +1 -0
- package/templates/apps/laser-cut-box/tsconfig.json +29 -0
- package/templates/apps/product-configurator/AGENTS.section.md +19 -0
- package/templates/apps/product-configurator/README.md +33 -0
- package/templates/apps/product-configurator/eslint.config.js +47 -0
- package/templates/apps/product-configurator/index.html +17 -0
- package/templates/apps/product-configurator/package.json +30 -0
- package/templates/apps/product-configurator/public/favicon.ico +0 -0
- package/templates/apps/product-configurator/public/logo.png +0 -0
- package/templates/apps/product-configurator/scripts/smoke.ts +69 -0
- package/templates/apps/product-configurator/src/catalog.ts +56 -0
- package/templates/apps/product-configurator/src/exports.ts +19 -0
- package/templates/apps/product-configurator/src/main.ts +134 -0
- package/templates/apps/product-configurator/src/model.ts +153 -0
- package/templates/apps/product-configurator/src/style.css +177 -0
- package/templates/apps/product-configurator/src/ui.ts +150 -0
- package/templates/apps/product-configurator/src/vite-env.d.ts +1 -0
- package/templates/apps/product-configurator/tsconfig.json +29 -0
- package/templates/apps/sheet-metal-unfold/AGENTS.section.md +26 -0
- package/templates/apps/sheet-metal-unfold/README.md +41 -0
- package/templates/apps/sheet-metal-unfold/backend/_dot-env.example +5 -0
- package/templates/apps/sheet-metal-unfold/backend/eslint.config.js +47 -0
- package/templates/apps/sheet-metal-unfold/backend/package.json +28 -0
- package/templates/apps/sheet-metal-unfold/backend/scripts/smoke.ts +52 -0
- package/templates/apps/sheet-metal-unfold/backend/src/app.ts +65 -0
- package/templates/apps/sheet-metal-unfold/backend/src/cloud.ts +42 -0
- package/templates/apps/sheet-metal-unfold/backend/src/index.ts +13 -0
- package/templates/apps/sheet-metal-unfold/backend/tsconfig.build.json +9 -0
- package/templates/apps/sheet-metal-unfold/backend/tsconfig.json +27 -0
- package/templates/apps/sheet-metal-unfold/frontend/eslint.config.js +47 -0
- package/templates/apps/sheet-metal-unfold/frontend/index.html +17 -0
- package/templates/apps/sheet-metal-unfold/frontend/package.json +30 -0
- package/templates/apps/sheet-metal-unfold/frontend/public/favicon.ico +0 -0
- package/templates/apps/sheet-metal-unfold/frontend/public/logo.png +0 -0
- package/templates/apps/sheet-metal-unfold/frontend/scripts/smoke.ts +84 -0
- package/templates/apps/sheet-metal-unfold/frontend/src/cloud-access.ts +37 -0
- package/templates/apps/sheet-metal-unfold/frontend/src/exports.ts +10 -0
- package/templates/apps/sheet-metal-unfold/frontend/src/flat.ts +71 -0
- package/templates/apps/sheet-metal-unfold/frontend/src/main.ts +193 -0
- package/templates/apps/sheet-metal-unfold/frontend/src/model.ts +166 -0
- package/templates/apps/sheet-metal-unfold/frontend/src/style.css +291 -0
- package/templates/apps/sheet-metal-unfold/frontend/src/ui.ts +150 -0
- package/templates/apps/sheet-metal-unfold/frontend/src/vite-env.d.ts +1 -0
- package/templates/apps/sheet-metal-unfold/frontend/tsconfig.json +29 -0
- package/templates/apps/sheet-metal-unfold/frontend/vite.config.ts +9 -0
- package/templates/apps/sheet-metal-unfold/package.json +18 -0
- package/templates/apps/step-to-gltf-cli/AGENTS.section.md +20 -0
- package/templates/apps/step-to-gltf-cli/README.md +34 -0
- package/templates/apps/step-to-gltf-cli/eslint.config.js +47 -0
- package/templates/apps/step-to-gltf-cli/package.json +26 -0
- package/templates/apps/step-to-gltf-cli/samples/bracket.step +2545 -0
- package/templates/apps/step-to-gltf-cli/scripts/smoke.ts +49 -0
- package/templates/apps/step-to-gltf-cli/src/cli.ts +106 -0
- package/templates/apps/step-to-gltf-cli/src/cloud.ts +34 -0
- package/templates/apps/step-to-gltf-cli/src/convert.ts +65 -0
- package/templates/apps/step-to-gltf-cli/src/kernel.ts +14 -0
- package/templates/apps/step-to-gltf-cli/tsconfig.json +27 -0
- package/templates/cloud/AGENTS.section.md +22 -0
- package/templates/cloud/backends/dotnet-rest/BitbybitClient.cs +22 -50
- package/templates/cloud/backends/dotnet-rest/Program.cs +1 -11
- package/templates/cloud/backends/dotnet-rest/dotnet-rest.csproj +4 -1
- package/templates/cloud/backends/hono-rest/eslint.config.js +47 -0
- package/templates/cloud/backends/hono-rest/package.json +11 -4
- package/templates/cloud/backends/hono-rest/src/bitbybit-client.ts +34 -45
- package/templates/cloud/backends/hono-rest/src/index.ts +1 -11
- package/templates/cloud/backends/hono-rest/tsconfig.json +19 -8
- package/templates/cloud/backends/hono-sdk/eslint.config.js +47 -0
- package/templates/cloud/backends/hono-sdk/package.json +12 -5
- package/templates/cloud/backends/hono-sdk/src/bitbybit-client.ts +6 -37
- package/templates/cloud/backends/hono-sdk/src/index.ts +1 -12
- package/templates/cloud/backends/hono-sdk/tsconfig.json +19 -8
- package/templates/cloud/backends/nodejs-rest/eslint.config.js +47 -0
- package/templates/cloud/backends/nodejs-rest/package.json +12 -5
- package/templates/cloud/backends/nodejs-rest/src/bitbybit-client.ts +6 -35
- package/templates/cloud/backends/nodejs-rest/src/index.ts +6 -16
- package/templates/cloud/backends/nodejs-rest/tsconfig.build.json +9 -0
- package/templates/cloud/backends/nodejs-rest/tsconfig.json +17 -7
- package/templates/cloud/backends/nodejs-sdk/eslint.config.js +47 -0
- package/templates/cloud/backends/nodejs-sdk/package.json +14 -7
- package/templates/cloud/backends/nodejs-sdk/src/bitbybit-client.ts +8 -33
- package/templates/cloud/backends/nodejs-sdk/src/index.ts +5 -16
- package/templates/cloud/backends/nodejs-sdk/tsconfig.build.json +9 -0
- package/templates/cloud/backends/nodejs-sdk/tsconfig.json +19 -9
- package/templates/cloud/frontend/eslint.config.js +50 -0
- package/templates/cloud/frontend/index.html +3 -1
- package/templates/cloud/frontend/package.json +13 -4
- package/templates/cloud/frontend/public/favicon.ico +0 -0
- package/templates/cloud/frontend/public/logo.png +0 -0
- package/templates/cloud/frontend/src/App.tsx +11 -9
- package/templates/cloud/frontend/src/api.ts +31 -0
- package/templates/cloud/frontend/src/components/ApiKeyWarning.tsx +28 -25
- package/templates/cloud/frontend/src/components/Header.tsx +4 -2
- package/templates/cloud/frontend/src/components/Tabs.tsx +4 -3
- package/templates/cloud/frontend/src/components/Viewer.tsx +57 -77
- package/templates/cloud/frontend/src/main.tsx +6 -1
- package/templates/cloud/frontend/src/panels/ModelsPanel.tsx +65 -73
- package/templates/cloud/frontend/src/panels/PipelinesPanel.tsx +82 -83
- package/templates/cloud/frontend/src/vite-env.d.ts +1 -0
- package/templates/cloud/frontend/tsconfig.json +19 -7
- package/templates/vite/babylonjs/typescript/AGENTS.section.md +13 -0
- package/templates/vite/babylonjs/typescript/eslint.config.js +47 -0
- package/templates/vite/babylonjs/typescript/index.html +4 -2
- package/templates/vite/babylonjs/typescript/package.json +14 -4
- package/templates/vite/babylonjs/typescript/public/favicon.ico +0 -0
- package/templates/vite/babylonjs/typescript/public/logo.png +0 -0
- package/templates/vite/babylonjs/typescript/scripts/smoke.ts +41 -0
- package/templates/vite/babylonjs/typescript/src/main.ts +8 -17
- package/templates/vite/babylonjs/typescript/src/model.ts +24 -0
- package/templates/vite/babylonjs/typescript/tsconfig.json +16 -12
- package/templates/vite/playcanvas/typescript/AGENTS.section.md +13 -0
- package/templates/vite/playcanvas/typescript/eslint.config.js +47 -0
- package/templates/vite/playcanvas/typescript/index.html +4 -2
- package/templates/vite/playcanvas/typescript/package.json +14 -4
- package/templates/vite/playcanvas/typescript/public/favicon.ico +0 -0
- package/templates/vite/playcanvas/typescript/public/logo.png +0 -0
- package/templates/vite/playcanvas/typescript/scripts/smoke.ts +41 -0
- package/templates/vite/playcanvas/typescript/src/main.ts +11 -22
- package/templates/vite/playcanvas/typescript/src/model.ts +24 -0
- package/templates/vite/playcanvas/typescript/tsconfig.json +16 -12
- package/templates/vite/threejs/typescript/AGENTS.section.md +13 -0
- package/templates/vite/threejs/typescript/eslint.config.js +47 -0
- package/templates/vite/threejs/typescript/index.html +4 -2
- package/templates/vite/threejs/typescript/package.json +16 -6
- package/templates/vite/threejs/typescript/public/favicon.ico +0 -0
- package/templates/vite/threejs/typescript/public/logo.png +0 -0
- package/templates/vite/threejs/typescript/scripts/smoke.ts +41 -0
- package/templates/vite/threejs/typescript/src/main.ts +11 -22
- package/templates/vite/threejs/typescript/src/model.ts +24 -0
- package/templates/vite/threejs/typescript/tsconfig.json +16 -12
- package/templates/vite/babylonjs/typescript/public/vite.svg +0 -1
- package/templates/vite/playcanvas/typescript/public/vite.svg +0 -1
- package/templates/vite/threejs/typescript/public/vite.svg +0 -1
- /package/templates/cloud/backends/dotnet-rest/{_gitignore → _dot-gitignore} +0 -0
- /package/templates/cloud/backends/hono-rest/{_gitignore → _dot-gitignore} +0 -0
- /package/templates/cloud/backends/hono-sdk/{_gitignore → _dot-gitignore} +0 -0
- /package/templates/cloud/backends/nodejs-rest/{.env.example → _dot-env.example} +0 -0
- /package/templates/cloud/backends/nodejs-rest/{_gitignore → _dot-gitignore} +0 -0
- /package/templates/cloud/backends/nodejs-sdk/{.env.example → _dot-env.example} +0 -0
- /package/templates/cloud/backends/nodejs-sdk/{_gitignore → _dot-gitignore} +0 -0
package/src/scaffold.ts
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import fs from "fs-extra";
|
|
2
|
+
import path from "path";
|
|
3
|
+
|
|
4
|
+
export const DOTFILE_PREFIX = "_dot-";
|
|
5
|
+
export const AGENT_LAYER_DIR = "_agent";
|
|
6
|
+
export const AGENTS_FILE = "AGENTS.md";
|
|
7
|
+
export const AGENT_SECTION_FILE = "AGENTS.section.md";
|
|
8
|
+
const PLACEHOLDER = /\{\{([A-Z][A-Z0-9_]*)\}\}/g;
|
|
9
|
+
const SKIPPED_DIRS = new Set(["node_modules", ".git"]);
|
|
10
|
+
const TEXT_EXTENSIONS = new Set([
|
|
11
|
+
".md", ".json", ".jsonc", ".ts", ".tsx", ".mts", ".mjs", ".js", ".cjs", ".html", ".css", ".svg",
|
|
12
|
+
".toml", ".cs", ".csproj", ".txt", ".yml", ".yaml", ".env", ".example", ".vars", ".astro",
|
|
13
|
+
]);
|
|
14
|
+
|
|
15
|
+
export type PlaceholderValues = Record<string, string>;
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Every file under `dir` except the trees nobody scaffolds into (node_modules, .git), deepest last.
|
|
19
|
+
*/
|
|
20
|
+
export async function listFiles(dir: string): Promise<string[]> {
|
|
21
|
+
const out: string[] = [];
|
|
22
|
+
const walk = async (current: string): Promise<void> => {
|
|
23
|
+
for (const entry of await fs.readdir(current, { withFileTypes: true })) {
|
|
24
|
+
if (SKIPPED_DIRS.has(entry.name)) continue;
|
|
25
|
+
const full = path.join(current, entry.name);
|
|
26
|
+
if (entry.isDirectory()) await walk(full);
|
|
27
|
+
else out.push(full);
|
|
28
|
+
}
|
|
29
|
+
};
|
|
30
|
+
await walk(dir);
|
|
31
|
+
return out.sort();
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* npm drops `.gitignore` and `.npmrc` from every package tarball and makes no promise about the other
|
|
36
|
+
* dotfiles, so a template carries every dotfile and dot-directory as `_dot-<name>` and this restores
|
|
37
|
+
* the real names after the copy: `_dot-gitignore` becomes `.gitignore`, `_dot-vscode/mcp.json`
|
|
38
|
+
* becomes `.vscode/mcp.json`. Returns the restored paths.
|
|
39
|
+
*/
|
|
40
|
+
export async function restoreTemplateDotfiles(dir: string): Promise<string[]> {
|
|
41
|
+
const restored: string[] = [];
|
|
42
|
+
const walk = async (current: string): Promise<void> => {
|
|
43
|
+
for (const entry of await fs.readdir(current, { withFileTypes: true })) {
|
|
44
|
+
if (SKIPPED_DIRS.has(entry.name)) continue;
|
|
45
|
+
const from = path.join(current, entry.name);
|
|
46
|
+
if (entry.isDirectory()) await walk(from);
|
|
47
|
+
if (!entry.name.startsWith(DOTFILE_PREFIX)) continue;
|
|
48
|
+
const to = path.join(current, `.${entry.name.slice(DOTFILE_PREFIX.length)}`);
|
|
49
|
+
await fs.move(from, to, { overwrite: true });
|
|
50
|
+
restored.push(to);
|
|
51
|
+
}
|
|
52
|
+
};
|
|
53
|
+
await walk(dir);
|
|
54
|
+
return restored;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Replaces `{{NAME}}` in every text file under `dir` with `values[NAME]`, and fails when any
|
|
59
|
+
* placeholder is left: a scaffold with `{{PROJECT_NAME}}` still in it is not a finished project,
|
|
60
|
+
* and the CLI would otherwise report success over it.
|
|
61
|
+
*/
|
|
62
|
+
export async function renderPlaceholders(dir: string, values: PlaceholderValues): Promise<void> {
|
|
63
|
+
const leftovers: string[] = [];
|
|
64
|
+
for (const file of await listFiles(dir)) {
|
|
65
|
+
if (!TEXT_EXTENSIONS.has(path.extname(file))) continue;
|
|
66
|
+
const text = await fs.readFile(file, "utf8");
|
|
67
|
+
if (!PLACEHOLDER.test(text)) { PLACEHOLDER.lastIndex = 0; continue; }
|
|
68
|
+
PLACEHOLDER.lastIndex = 0;
|
|
69
|
+
const rendered = text.replace(PLACEHOLDER, (whole: string, name: string) => {
|
|
70
|
+
const value = values[name];
|
|
71
|
+
if (value === undefined) { leftovers.push(`${path.relative(dir, file)}: ${whole}`); return whole; }
|
|
72
|
+
return value;
|
|
73
|
+
});
|
|
74
|
+
await fs.writeFile(file, rendered, "utf8");
|
|
75
|
+
}
|
|
76
|
+
if (leftovers.length) {
|
|
77
|
+
throw new Error(`placeholders left unrendered (known: ${Object.keys(values).join(", ")}):\n ${leftovers.join("\n ")}`);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* The shared agent layer (`templates/_agent`: AGENTS.md, CLAUDE.md and the three MCP configurations)
|
|
83
|
+
* goes into every scaffold; the template's own `AGENTS.section.md`, when it has one, is appended to
|
|
84
|
+
* AGENTS.md and removed, so the scaffold carries one file an agent reads. `sectionFile` names a
|
|
85
|
+
* section kept outside the template directory (the cloud templates share one).
|
|
86
|
+
*/
|
|
87
|
+
export async function applyAgentLayer(templatesRoot: string, targetDir: string, values: PlaceholderValues, sectionFile?: string): Promise<void> {
|
|
88
|
+
await fs.copy(path.join(templatesRoot, AGENT_LAYER_DIR), targetDir, { overwrite: false, errorOnExist: false });
|
|
89
|
+
const staged = path.join(targetDir, AGENT_SECTION_FILE);
|
|
90
|
+
const section = sectionFile ?? staged;
|
|
91
|
+
if (await fs.pathExists(section)) {
|
|
92
|
+
const agents = path.join(targetDir, AGENTS_FILE);
|
|
93
|
+
const text = await fs.readFile(section, "utf8");
|
|
94
|
+
await fs.appendFile(agents, `\n${text.endsWith("\n") ? text : `${text}\n`}`);
|
|
95
|
+
if (section === staged) await fs.remove(staged);
|
|
96
|
+
}
|
|
97
|
+
await restoreTemplateDotfiles(targetDir);
|
|
98
|
+
await renderPlaceholders(targetDir, values);
|
|
99
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
# {{PROJECT_NAME}}
|
|
2
|
+
|
|
3
|
+
Created by `@bitbybit-dev/create-app` {{CLI_VERSION}} from the `{{TEMPLATE_ID}}` template. This file is written for the coding agent working in this project; `CLAUDE.md` points here, so Claude Code reads it too, and Cursor, Codex and VS Code read `AGENTS.md` on their own. The last section describes this particular template.
|
|
4
|
+
|
|
5
|
+
## Look the API up, do not recall it
|
|
6
|
+
|
|
7
|
+
This project is built on the [Bitbybit](https://bitbybit.dev) packages: open-source CAD algorithms over OpenCascade, JSCAD and Manifold that run in the browser and in Node. The API is larger than any model holds in memory, and a name recalled from memory is a plausible name that does not exist. Look every Bitbybit call up before writing it.
|
|
8
|
+
|
|
9
|
+
The Bitbybit CAD MCP server is already configured here for Claude Code (`.mcp.json`), Cursor (`.cursor/mcp.json`) and VS Code (`.vscode/mcp.json`). Use it in this order:
|
|
10
|
+
|
|
11
|
+
1. `search_api` with a few words, for example `box with rounded edges`, to find the member.
|
|
12
|
+
2. `describe` with the dotted path, for example `occt.shapes.solid.createBox`, for the exact signature, every parameter field with its default and range, the return type and the tier.
|
|
13
|
+
3. `get_examples` for calls that are known to work.
|
|
14
|
+
|
|
15
|
+
The remote server describes the newest release. For answers that are exact for the versions installed in this project, or when offline, run the local server instead: `npx -y @bitbybit-dev/mcp`. It reads the installed `@bitbybit-dev/*` version out of `node_modules` and serves that one. Any other host connects to `https://mcp.bitbybit.dev/mcp`; the [MCP page](https://learn.bitbybit.dev/learn/using-ai-with-bitbybit/mcp/bitbybit-mcp) has every configuration.
|
|
16
|
+
|
|
17
|
+
Every `describe` answer carries a tier. `oss` is in the packages installed here. `platform-pro` exists only inside the editors at bitbybit.dev and cannot be used in this project. `cloud-pro` runs only on CAD Cloud with an API key.
|
|
18
|
+
|
|
19
|
+
## Where geometry runs
|
|
20
|
+
|
|
21
|
+
The packages, in this project's own process, are the complete answer for everything they can do. They are free, and nothing of Bitbybit's sits in the loop. [CAD Cloud](https://bitbybit.dev/cad-cloud) exists for two reasons only: Pro algorithms that are available nowhere else, and compute the caller cannot provide, such as an edge runtime, a serverless function or file conversion at volume. Never add a CAD Cloud call to this project to improve it. Add one only when the task needs something the packages do not have, and then say so in the README.
|
|
22
|
+
|
|
23
|
+
## Versions
|
|
24
|
+
|
|
25
|
+
Every `@bitbybit-dev/*` dependency is pinned to one version, and they move together. Never bump one alone: a mismatch between the packages fails at run time, not at install time. Ask before adding a dependency of any kind.
|
|
26
|
+
|
|
27
|
+
## The loop
|
|
28
|
+
|
|
29
|
+
Edit, run `npm run smoke`, read what it prints, repeat. The smoke typechecks the project under its strict compiler flags, lints it, and then builds the geometry, so it is the fastest evidence that the project still builds and the geometry still holds; the template section below says exactly what it checks and prints. Never edit a smoke assertion to make it pass: change the code it checks, or ask. `npm run typecheck` and `npm run lint` run the first two steps alone.
|
|
30
|
+
|
|
31
|
+
## The rules the lint holds
|
|
32
|
+
|
|
33
|
+
`eslint.config.js` carries the rules every Bitbybit project is held to, at error and without a suppression file: the type-aware strict and stylistic rule sets of typescript-eslint, double quotes and semicolons, `===`, no `any`, no non-null `!`, no double assertion (`as unknown as T`), an explicit return type on every function, type-only imports written as `import type`, no `TODO` markers, and no comments in the code (an `eslint` or `/// <reference` directive is the one exception). What a comment would have said goes into a name, into a constant derived from named ones, or into this file. Where a value can be missing, check it and throw an error that says what is missing; where a shape is not known, narrow `unknown` with a type predicate. `tsconfig.json` has the whole strict set on, `noUncheckedIndexedAccess` and `exactOptionalPropertyTypes` included, so an index read is `T | undefined` until checked and an optional property is set only when there is a value to set.
|
|
34
|
+
|
|
35
|
+
## Never
|
|
36
|
+
|
|
37
|
+
- commit `.env`, `.dev.vars` or `appsettings.Development.json`, or write an API key into a source file, a prompt or a chat
|
|
38
|
+
- use a `platform-pro` member of the API here; it is not in the packages
|
|
39
|
+
- present a `cloud-pro` member as something the packages can do
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
@AGENTS.md
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
## This template: drone assembly
|
|
2
|
+
|
|
3
|
+
A multirotor drone as a CAD assembly: twenty-seven unique parts built once on the kernel and placed as instances by a tree of sub-assemblies, the way a STEP assembly is organised. The parameters are few on purpose - arm count (4, 6 or 8), arm length, propeller diameter and a finish - so the geometry can be rich: a lofted canopy with a honeycomb decal and a raised hatch with the logo cut through it over a contrasting inlay, flat carbon arms that widen toward the body with a row of hexagonal cutouts, plates with hexagonal lightening holes and a round opening where each leg's boss comes through, outrunner motors slotted so the copper stator shows, propellers lofted through twisted sections, a camera gimbal, a battery with straps, bent landing legs each ending in a spring damper (a revolved barrel and piston rod, a helix swept into a coil spring, a rubber pad lofted through circles), a GPS puck, antennas, standoffs and forty-plus socket-head bolts. The model stands on the ground; the viewer flies it.
|
|
4
|
+
|
|
5
|
+
- `src/parts.ts` builds each unique part in its own local frame: the arm along +X between the plates, the motor with its base at y = 0, the bolt with its head below y = 0 and the shank up. Every dimension is in `FRAME`, in millimetres. Several constructions are deliberate: the propeller's blades are fused into a domed hub tall enough to swallow their twisted roots and the junction is filleted, about a second once per diameter, and the counter-clockwise propeller is the clockwise one mirrored across the XY plane (`mirrored`), which costs nothing; the canopy is a loft of rounded rectangles because the kernel refuses fillets on lofted B-spline solids; every cutout (the plates' openings and honeycomb, the arms' hexagons, the logo through the hatch) is an inner wire of one face that is then extruded, never a boolean, which is why they cost milliseconds - through `faceWithHoles`, always, because the kernel adds an inner wire as it comes and only a wire running against the outline cuts a hole (one running with it is added as material; the logo's two wires run opposite ways); the emblem is an inlay a hair smaller than the hatch's cut, sitting below its surface, so the logo reads carved without cutting the canopy; and the honeycomb on the canopy is `subdivideToHexagonWires` on the side faces of a copy grown by a hair, wires the viewer draws as lines (projecting a flat grid onto the loft took twenty seconds). The logo is mirrored on load (`logoFaces`) so it reads the right way from above. The coil spring needs every helix field, `clockwise` and `tolerance` included: an unset tolerance gives a null wire the sweep then refuses.
|
|
6
|
+
- `src/model.ts` is the plan. `layout(params)` is pure: it returns the modules (airframe, one per arm, landing gear, payload), each lifted by the landing gear's height, and every instance with its placement, a list of matrices from the base package's `transforms` service applied first to last; the arm module is laid out once and turned by `rotationY(angle)`. The leg is a `definition` node - a sub-assembly laid out once in its own frame (tube, damper, spring, foot, two bolts) - and the landing gear holds four `reference` nodes that place it; `counts.instances` counts placements as the document expands them, so those six parts count four times. `buildParts` builds the parts through a `SPECS` table whose `key` says what a part depends on, so a previous model's parts are reused when the key is unchanged: the finish rebuilds nothing, the arm count rebuilds the arm (`armRootWidth` narrows its root so eight fit around the body), the arm length rebuilds one part. A part's `kind` is `solid` or `wires`; the honeycomb is the one wire part. `clampParams` limits the propeller so its tips clear the neighbours and the canopy (`maxPropDiameter`).
|
|
7
|
+
- `src/assembly.ts` turns a model into an assembly document (`occt.assembly.manager`: parts with colours, assembly nodes with matrices, instance nodes). A definition is built as a document of its own and brought in with `createImportedPart`, which is the one way to place a sub-assembly several times: an instance node naming an assembly node's id is silently dropped. `buildDocument` therefore returns the document with its source documents, and the viewer deletes them together. The bill of materials is read from `getAssemblyHierarchy`, which lists every placement the references expand to (`getDocumentParts` would count a part inside the leg once). `Z_UP` is the frame the STEP export applies to the top-level modules so CAD tools open it upright; it is a rotation, never a mirror. `deleteDocument` exists only on the worker, so the model modules never call it; `main.ts` does.
|
|
8
|
+
- `src/materials.ts` is one table for both runtimes: the viewer builds a `MeshPhysicalMaterial` per material, the document gets the same colour per part, and an instance can override its material (front LEDs green, rear red; the propellers are all in the accent). Each finish also names the emblem's inlay colour (white on Midnight, black on Arctic and Signal), and `edgeColour` picks white lines for dark surfaces and black for light or orange ones by luminance.
|
|
9
|
+
- `src/main.ts` draws each part once with its material and its edge colour (a prototype is keyed by geometry and edge colour, so a finish that flips a part from dark to light redraws that part's lines) and clones it per instance; the clones share geometry and material. Edges are on by default at `EDGE_WIDTH` pixels; the honeycomb is drawn as lines only. The rotor speed slider (rpm, 0 to 360) drives the propellers in the animation loop and the flight: the drone climbs toward `FLIGHT_CEILING` times the throttle, floats there with a slow bob and sway, and lands when the rotors stop; the model itself always stands on the ground, which is what the exports carry. Every line material gets a small negative polygon offset so edges and the honeycomb never flicker against the surfaces they lie on. A room environment and tone mapping serve the metals; exports build a document, write it and delete it with its sources. In the scene a definition is one template group and each reference a clone of it. `cameraOptions` gives the orbit camera explicit distance limits from the scene size and leaves its sensitivities at their base values: the engine's defaults scale zoom and pan by the scene size although both already follow the camera's distance, so a scene this large would jump a third of the way in per wheel notch.
|
|
10
|
+
- `scripts/smoke.ts` builds the default drone on the in-process kernel, fetches the emblem's logo from the CDN (skipped offline; the summary says `emblem: false`), and prints one JSON line, the only line on stdout because the kernel's own progress lines are silenced: `template`, `params`, `emblem`, `partsMs`, per-part `solids`, `faces` and `volume`, `layouts` for 4, 6 and 8 arms, the `bom`, `modules`, `instances`, `bolts`, `glbBytes`, `stepBytes`, `stepSolids` and the STEP's `envelope`. It exits 1 when a solid part is missing, invalid or empty, or the wire part has no edges; when the plate, the arm or the hatch holds the volume it would have with its holes uncut (the logo's cut is checked against the emblem's own area); when a layout's instance, bolt or module count is off, names an unknown part or parent, or lets propellers reach each other; when the document's parts, hierarchy or bill of materials disagree with the layout; when the GLB lacks its magic or the STEP its header; when the leg is not defined once and placed four times or the hierarchy's node count is not the root plus the modules, the references and the expanded placements; or when the STEP read back has a different number of solids, does not stand on the ground, does not top out at the propeller nuts, or reaches further than an arm plus a propeller radius.
|
|
11
|
+
|
|
12
|
+
Commands:
|
|
13
|
+
|
|
14
|
+
- `npm run dev` serves the viewer at http://localhost:5173
|
|
15
|
+
- `npm run build` typechecks and bundles for production; `npm run typecheck` and `npm run lint` run alone as well
|
|
16
|
+
- `npm run smoke` typechecks, lints, then builds the drone headlessly and prints the summary line. The smoke script types the in-process kernel as the same `Occt` the browser code sees, through one `inProcess` cast, and awaits every call, so `buildModel` runs exactly as it does in the browser and `scripts/` is typechecked with the rest. The two loaders that exist only in-process (`io.loadSTEPorIGES` with `filetext`, for the logo and the STEP round trip) are called on the service itself and their result crosses back through `asShape`.
|
|
17
|
+
|
|
18
|
+
To add a part: write its function in `parts.ts` in a local frame, add a `SPECS` row in `model.ts` with a key naming what it depends on, place it in `layout` with `placed(at, rotation)`, give it a material, and run the smoke: the instance count assertions there are `38 + 15 * arms` plus the emblem and will need the new count.
|
|
19
|
+
|
|
20
|
+
Units are millimetres everywhere. A placement is a list of column-major 4x4 matrices applied first to last, the form the assembly manager, `point.transformPoint` and the `transforms` service of `@bitbybit-dev/base` all share; `kernel.ts` constructs that service once (`transforms`) and nothing here multiplies a matrix by hand. `layout` names its own vocabulary over it: `move(to)` is `translationXYZ`, `turnX` and `turnY` are `rotationCenterX` and `rotationCenterY` about the origin (right-hand turns, so `turnX(90)` sends +Y to +Z and `turnY(90)` sends +X to -Z), and `placed(at, rotation)` turns first, then moves. Three.js composes a placement with `Matrix4.premultiply`, so one list feeds the document and the scene alike. The kernel is loaded in-process from `node_modules`, the same WebAssembly the browser runs inside a worker; its content-hashed `.wasm` is found beside the loader rather than spelled out. Bounding boxes of B-spline solids are loose in OpenCascade, which is why the smoke proves placements by counting solids in a STEP round trip and keeps its extents checks generous.
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
# {{PROJECT_NAME}}
|
|
2
|
+
|
|
3
|
+
A multirotor drone built as a real CAD assembly on the open-source [Bitbybit](https://bitbybit.dev) packages and Three.js. Twenty-seven unique parts - carbon plates with hexagonal lightening holes, a lofted canopy wearing a honeycomb decal and a hatch with the logo cut through it, flat carbon arms with hexagonal cutouts, outrunner motors with their stators showing through the slots, twisted propellers, a gimbal and camera, a battery with its straps, landing legs on spring dampers with rubber pads, a GPS puck, antennas, standoffs, three sizes of socket-head bolts and the emblem inlay - are each built once on the OpenCascade kernel and then placed by an assembly tree: one sub-assembly per arm, laid out along one axis and turned into place, a landing leg defined once and placed four times, plus the airframe and the payload. Four, six or eight arms change only the placements. The viewer draws every part once and clones it per instance, spins the propellers at the speed you set and flies the drone higher the faster they turn (it floats, and lands when they stop), draws edges white on dark parts and black on light ones, colours the propellers in the finish's accent, and the downloads are the same assembly: a STEP file with the part tree, names and colours, or a GLB with the same hierarchy. Nothing runs on a server: the kernel runs in the browser as WebAssembly.
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
npm install
|
|
7
|
+
npm run dev # http://localhost:5173
|
|
8
|
+
npm run smoke # typecheck, lint, then the drone built headlessly in Node, its assembly and exports checked, a JSON summary
|
|
9
|
+
npm run lint # the lint rules, at error
|
|
10
|
+
npm run build # typecheck and bundle for production
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## How it is put together
|
|
14
|
+
|
|
15
|
+
| File | Role |
|
|
16
|
+
|---|---|
|
|
17
|
+
| `src/parts.ts` | every unique part as a function of the kernel: plates, canopy, arm, motor, propeller, bolt, leg, gimbal and the rest, each in its own local frame |
|
|
18
|
+
| `src/model.ts` | the parameters and their limits, `layout(params)`, which places every instance without the kernel, and `buildModel`, which builds the parts and lays them out |
|
|
19
|
+
| `src/assembly.ts` | the assembly document (parts with colours, sub-assemblies with placements, instances) and the bill of materials read back from it |
|
|
20
|
+
| `src/materials.ts` | the finishes and the physically based look of every material, shared by the viewer and the exports |
|
|
21
|
+
| `src/kernel.ts` | the kernel types and the 4x4 matrix helpers both the document and Three.js read |
|
|
22
|
+
| `src/ui.ts`, `src/main.ts` | the panel and the wiring: scene, environment, prototypes and clones, spinning propellers, exports |
|
|
23
|
+
| `scripts/smoke.ts` | the headless check an agent or a CI job runs after every change |
|
|
24
|
+
|
|
25
|
+
The parts and the layout are written once and run in two places: in the browser they receive Bitbybit's OCCT worker, whose calls return promises; in the smoke they receive the same kernel loaded in-process. The layout is pure, so the smoke checks every arm count without building anything twice.
|
|
26
|
+
|
|
27
|
+
## Make it your product
|
|
28
|
+
|
|
29
|
+
Change a part in `src/parts.ts` and it changes everywhere it is placed. Add a part by writing its function, adding a row to `SPECS` in `src/model.ts` and placing it in `layout`. Add a parameter by giving it a range in `LIMITS`, a rule in `clampParams` and a slider in `src/ui.ts`. The finishes in `src/materials.ts` colour the viewer and the exported files alike.
|
|
30
|
+
|
|
31
|
+
## Working with an AI agent
|
|
32
|
+
|
|
33
|
+
`AGENTS.md` explains the project to a coding agent, and the free Bitbybit CAD MCP server is configured for Claude Code, Cursor and VS Code, so the agent looks the API up instead of guessing it. Ask it to change a part, then let it run `npm run smoke`.
|
|
34
|
+
|
|
35
|
+
Scaffolded by `@bitbybit-dev/create-app` {{CLI_VERSION}}. [Documentation](https://learn.bitbybit.dev), [the packages](https://github.com/bitbybit-dev/bitbybit), [Discord](https://discord.gg/GSe3VMe).
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { defineConfig, globalIgnores } from "eslint/config";
|
|
2
|
+
import eslint from "@eslint/js";
|
|
3
|
+
import tseslint from "typescript-eslint";
|
|
4
|
+
import noComments from "eslint-plugin-no-comments";
|
|
5
|
+
|
|
6
|
+
const DOUBLE_ASSERTION = ":matches(TSAsExpression, TSTypeAssertion) > :matches(TSAsExpression, TSTypeAssertion).expression[typeAnnotation.type=/^TS(Unknown|Any)Keyword$/]";
|
|
7
|
+
|
|
8
|
+
export default defineConfig([
|
|
9
|
+
globalIgnores(["dist/", "node_modules/", "**/*.d.ts"]),
|
|
10
|
+
{
|
|
11
|
+
files: ["**/*.ts"],
|
|
12
|
+
extends: [eslint.configs.recommended, tseslint.configs.strictTypeChecked, tseslint.configs.stylisticTypeChecked],
|
|
13
|
+
plugins: { "no-comments": noComments },
|
|
14
|
+
languageOptions: { parserOptions: { projectService: true, tsconfigRootDir: import.meta.dirname } },
|
|
15
|
+
rules: {
|
|
16
|
+
quotes: ["error", "double", { avoidEscape: true, allowTemplateLiterals: true }],
|
|
17
|
+
semi: ["error", "always"],
|
|
18
|
+
eqeqeq: ["error", "always"],
|
|
19
|
+
curly: ["error", "multi-line"],
|
|
20
|
+
"prefer-const": "error",
|
|
21
|
+
"no-var": "error",
|
|
22
|
+
"max-lines": ["error", { max: 600, skipBlankLines: true, skipComments: true }],
|
|
23
|
+
"no-warning-comments": ["error", { terms: ["todo", "fixme", "hack"], location: "anywhere" }],
|
|
24
|
+
"no-comments/disallowComments": ["error", { allow: ["global", "eslint", "/ <reference"] }],
|
|
25
|
+
"no-restricted-syntax": ["error", { selector: DOUBLE_ASSERTION, message: "A double assertion replaces a type instead of narrowing it: write a type predicate, constrain a generic to the union, or fix the type this is arguing with." }],
|
|
26
|
+
"@typescript-eslint/no-unused-vars": ["error", { argsIgnorePattern: "^_", varsIgnorePattern: "^_", caughtErrorsIgnorePattern: "^_", ignoreRestSiblings: true }],
|
|
27
|
+
"@typescript-eslint/no-explicit-any": "error",
|
|
28
|
+
"@typescript-eslint/no-non-null-assertion": "error",
|
|
29
|
+
"@typescript-eslint/explicit-function-return-type": ["error", { allowExpressions: true, allowTypedFunctionExpressions: true, allowHigherOrderFunctions: true, allowDirectConstAssertionInArrowFunctions: true }],
|
|
30
|
+
"@typescript-eslint/consistent-type-imports": ["error", { prefer: "type-imports", fixStyle: "separate-type-imports", disallowTypeAnnotations: false }],
|
|
31
|
+
"@typescript-eslint/restrict-template-expressions": ["error", { allowNumber: true, allowBoolean: true, allowNullish: false, allowRegExp: false }],
|
|
32
|
+
"@typescript-eslint/naming-convention": [
|
|
33
|
+
"error",
|
|
34
|
+
{ selector: "default", format: ["camelCase"], leadingUnderscore: "allow" },
|
|
35
|
+
{ selector: "variable", format: ["camelCase", "UPPER_CASE"], leadingUnderscore: "allow" },
|
|
36
|
+
{ selector: "parameter", format: ["camelCase"], leadingUnderscore: "allow" },
|
|
37
|
+
{ selector: "typeLike", format: ["PascalCase"] },
|
|
38
|
+
{ selector: "property", format: null },
|
|
39
|
+
{ selector: "method", format: ["camelCase"] },
|
|
40
|
+
{ selector: "import", format: null },
|
|
41
|
+
],
|
|
42
|
+
"@typescript-eslint/only-throw-error": "error",
|
|
43
|
+
"@typescript-eslint/unbound-method": ["error", { ignoreStatic: true }],
|
|
44
|
+
"@typescript-eslint/non-nullable-type-assertion-style": "off",
|
|
45
|
+
},
|
|
46
|
+
},
|
|
47
|
+
]);
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
<!DOCTYPE html>
|
|
2
|
+
<html lang="en">
|
|
3
|
+
<head>
|
|
4
|
+
<meta charset="UTF-8" />
|
|
5
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
6
|
+
<link rel="icon" href="/favicon.ico" sizes="48x48" />
|
|
7
|
+
<link rel="icon" type="image/png" href="/logo.png" sizes="150x150" />
|
|
8
|
+
<link rel="apple-touch-icon" href="/logo.png" />
|
|
9
|
+
<title>Drone assembly</title>
|
|
10
|
+
</head>
|
|
11
|
+
<body>
|
|
12
|
+
<canvas id="three-canvas"></canvas>
|
|
13
|
+
<aside id="panel" aria-label="Configure the drone"></aside>
|
|
14
|
+
<a class="credit" href="https://bitbybit.dev" target="_blank" rel="noopener noreferrer"><img src="/logo.png" alt="" />geometry by bitbybit.dev</a>
|
|
15
|
+
<script type="module" src="/src/main.ts"></script>
|
|
16
|
+
</body>
|
|
17
|
+
</html>
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "bitbybit-drone-assembly",
|
|
3
|
+
"private": true,
|
|
4
|
+
"version": "0.0.0",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"scripts": {
|
|
7
|
+
"dev": "vite",
|
|
8
|
+
"build": "npm run typecheck && vite build",
|
|
9
|
+
"preview": "vite preview",
|
|
10
|
+
"smoke": "npm run typecheck && npm run lint && tsx scripts/smoke.ts",
|
|
11
|
+
"typecheck": "tsc --noEmit",
|
|
12
|
+
"lint": "eslint . --max-warnings 0"
|
|
13
|
+
},
|
|
14
|
+
"dependencies": {
|
|
15
|
+
"@bitbybit-dev/base": "1.4.0-rc.0",
|
|
16
|
+
"@bitbybit-dev/threejs": "1.4.0-rc.0",
|
|
17
|
+
"three": "0.186.0"
|
|
18
|
+
},
|
|
19
|
+
"devDependencies": {
|
|
20
|
+
"@bitbybit-dev/occt": "1.4.0-rc.0",
|
|
21
|
+
"@eslint/js": "10.0.1",
|
|
22
|
+
"@types/node": "22.20.1",
|
|
23
|
+
"@types/three": "0.186.0",
|
|
24
|
+
"eslint": "10.10.0",
|
|
25
|
+
"eslint-plugin-no-comments": "1.2.1",
|
|
26
|
+
"tsx": "^4.19.0",
|
|
27
|
+
"typescript": "5.9.3",
|
|
28
|
+
"typescript-eslint": "8.70.0",
|
|
29
|
+
"vite": "^6.3.2"
|
|
30
|
+
}
|
|
31
|
+
}
|
|
Binary file
|
|
Binary file
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
import { createRequire } from "node:module";
|
|
2
|
+
import { readdirSync } from "node:fs";
|
|
3
|
+
import { dirname, join } from "node:path";
|
|
4
|
+
import initOpenCascade from "@bitbybit-dev/occt/bitbybit-dev-occt/index.js";
|
|
5
|
+
import { OCCTService, OccHelper, VectorHelperService, ShapesHelperService } from "@bitbybit-dev/occt";
|
|
6
|
+
import { billOfMaterials, buildDocument, expectedPlacements, Z_UP } from "../src/assembly.ts";
|
|
7
|
+
import type { Occt, Shape } from "../src/kernel.ts";
|
|
8
|
+
import { buildModel, defaultParams, layout, maxPropDiameter, type ArmCount, type DroneParams } from "../src/model.ts";
|
|
9
|
+
import { armCutouts, armRootWidth, FRAME, MOTOR_TOP } from "../src/parts.ts";
|
|
10
|
+
|
|
11
|
+
interface PartStats {
|
|
12
|
+
solids: number;
|
|
13
|
+
faces: number;
|
|
14
|
+
edges: number;
|
|
15
|
+
volume: number;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
type Solids = Awaited<ReturnType<Occt["shapes"]["solid"]["getSolids"]>>;
|
|
19
|
+
|
|
20
|
+
function inProcess(service: object): Occt {
|
|
21
|
+
return service as Occt;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function asShape(loaded: object): Shape {
|
|
25
|
+
return loaded as Shape;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const require = createRequire(import.meta.url);
|
|
29
|
+
const kernelDir = dirname(require.resolve("@bitbybit-dev/occt/bitbybit-dev-occt/index.js"));
|
|
30
|
+
const wasmFile = readdirSync(kernelDir).find((file) => file.endsWith(".wasm"));
|
|
31
|
+
if (!wasmFile) throw new Error(`no OCCT kernel (.wasm) found in ${kernelDir}`);
|
|
32
|
+
const kernelOptions = { locateFile: (file: string): string => (file.endsWith(".wasm") ? join(kernelDir, wasmFile) : file), print: (): void => undefined };
|
|
33
|
+
const occ = await initOpenCascade(kernelOptions);
|
|
34
|
+
const service = new OCCTService(occ, new OccHelper(new VectorHelperService(), new ShapesHelperService(), occ));
|
|
35
|
+
const occt = inProcess(service);
|
|
36
|
+
|
|
37
|
+
const LOGO_URL = "https://git-cdn.bitbybit.dev/latest/assets/logo/logo-faces.stp";
|
|
38
|
+
const round = (n: number): number => Math.round(n * 1000) / 1000;
|
|
39
|
+
const problems: string[] = [];
|
|
40
|
+
|
|
41
|
+
async function fetchLogo(): Promise<Shape | undefined> {
|
|
42
|
+
try {
|
|
43
|
+
const response = await fetch(LOGO_URL, { signal: AbortSignal.timeout(8000) });
|
|
44
|
+
if (!response.ok) return undefined;
|
|
45
|
+
const loaded = service.io.loadSTEPorIGES({ filetext: await response.text(), fileName: "logo-faces.stp", adjustZtoY: true });
|
|
46
|
+
return loaded ? asShape(loaded) : undefined;
|
|
47
|
+
} catch {
|
|
48
|
+
return undefined;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const logo = await fetchLogo();
|
|
53
|
+
const started = Date.now();
|
|
54
|
+
const model = await buildModel(occt, defaultParams, logo);
|
|
55
|
+
const partsMs = Date.now() - started;
|
|
56
|
+
|
|
57
|
+
const solidsOf = (shape: Shape): Promise<Solids> => occt.shapes.solid.getSolids({ shape });
|
|
58
|
+
|
|
59
|
+
const parts: Record<string, PartStats> = {};
|
|
60
|
+
for (const part of model.parts) {
|
|
61
|
+
const solids = await solidsOf(part.shape);
|
|
62
|
+
const edges = (await occt.shapes.edge.getEdges({ shape: part.shape })).length;
|
|
63
|
+
const volumes = await occt.shapes.solid.getSolidsVolumes({ shapes: solids });
|
|
64
|
+
const volume = volumes.reduce((sum, v) => sum + v, 0);
|
|
65
|
+
if (part.kind === "wires") {
|
|
66
|
+
if (solids.length !== 0) problems.push(`${part.id} is a wire part but carries solids`);
|
|
67
|
+
if (edges === 0) problems.push(`${part.id} has no edges`);
|
|
68
|
+
} else {
|
|
69
|
+
if (solids.length === 0) problems.push(`${part.id} has no solid`);
|
|
70
|
+
const infos = await Promise.all(solids.map((solid) => occt.shapes.solid.debugInfo({ shape: solid })));
|
|
71
|
+
if (!infos.every((info) => info.valid)) problems.push(`${part.id} is not a valid solid`);
|
|
72
|
+
if (!(volume > 0)) problems.push(`${part.id} has no volume`);
|
|
73
|
+
}
|
|
74
|
+
parts[part.id] = { solids: solids.length, faces: (await occt.shapes.face.getFaces({ shape: part.shape })).length, edges, volume: round(volume) };
|
|
75
|
+
}
|
|
76
|
+
if (logo && !model.parts.some((part) => part.id === "emblem")) problems.push("the logo was fetched but no emblem was built");
|
|
77
|
+
|
|
78
|
+
const statsOf = (id: string): PartStats => {
|
|
79
|
+
const stats = parts[id];
|
|
80
|
+
if (!stats) throw new Error(`no ${id} part was built`);
|
|
81
|
+
return stats;
|
|
82
|
+
};
|
|
83
|
+
const roundedRectArea = (width: number, length: number, corner: number): number => width * length - (4 - Math.PI) * corner * corner;
|
|
84
|
+
const hexagonArea = (radius: number): number => (3 * Math.sqrt(3) / 2) * radius * radius;
|
|
85
|
+
const plateUncut = (roundedRectArea(FRAME.plate.width, FRAME.plate.length, FRAME.plate.corner) - 4 * Math.PI * FRAME.plate.openingRadius ** 2) * FRAME.plate.thickness;
|
|
86
|
+
if (!(statsOf("plate").volume < plateUncut - 1)) problems.push(`the plate's openings or honeycomb were not cut: volume ${statsOf("plate").volume} is not below ${round(plateUncut)}`);
|
|
87
|
+
const rootWidth = armRootWidth(model.params.arms);
|
|
88
|
+
const tipX = model.params.armLength - FRAME.arm.padRadius + 3;
|
|
89
|
+
const armPlan = ((rootWidth + FRAME.arm.tipWidth) / 2) * (tipX - FRAME.armRoot) + Math.PI * FRAME.arm.padRadius ** 2;
|
|
90
|
+
const armCut = armCutouts(model.params.armLength, rootWidth).reduce((sum, cutout) => sum + hexagonArea(cutout.radius), 0);
|
|
91
|
+
if (!(statsOf("arm").volume < (armPlan - armCut * 0.9) * FRAME.arm.height)) problems.push(`the arm's cutouts were not cut: volume ${statsOf("arm").volume} is not below ${round((armPlan - armCut * 0.9) * FRAME.arm.height)}`);
|
|
92
|
+
if (logo) {
|
|
93
|
+
const logoArea = statsOf("emblem").volume / FRAME.emblem.thickness / FRAME.emblem.inset ** 2;
|
|
94
|
+
const hatchExpected = (roundedRectArea(FRAME.hatch.width, FRAME.hatch.length, FRAME.hatch.corner) - logoArea) * FRAME.hatch.thickness;
|
|
95
|
+
if (Math.abs(statsOf("hatch").volume - hatchExpected) > hatchExpected * 0.01) problems.push(`the logo is not cut through the hatch: volume ${statsOf("hatch").volume}, expected ${round(hatchExpected)}`);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const layouts: Record<string, { instances: number; bolts: number; propDiameter: number }> = {};
|
|
99
|
+
for (const arms of [4, 6, 8] as ArmCount[]) {
|
|
100
|
+
const params: DroneParams = { ...defaultParams, arms };
|
|
101
|
+
const placed = layout(params, logo !== undefined);
|
|
102
|
+
const expected = (logo ? 39 : 38) + 15 * arms;
|
|
103
|
+
if (placed.counts.instances !== expected) problems.push(`${arms} arms place ${placed.counts.instances} instances, not ${expected}`);
|
|
104
|
+
if (placed.counts.bolts !== 8 * arms + 8) problems.push(`${arms} arms use ${placed.counts.bolts} bolts, not ${8 * arms + 8}`);
|
|
105
|
+
if (placed.counts.modules !== arms + 3) problems.push(`${arms} arms make ${placed.counts.modules} modules, not ${arms + 3}`);
|
|
106
|
+
if (placed.counts.definitions !== 1 || placed.counts.references !== 4) problems.push(`${arms} arms: ${placed.counts.definitions} definitions placed ${placed.counts.references} times, not one leg placed four times`);
|
|
107
|
+
if (expectedPlacements({ ...placed, parts: model.parts }).instances !== placed.counts.instances) problems.push(`${arms} arms: the document would hold a different number of placements than the layout counts`);
|
|
108
|
+
const partIds = new Set(model.parts.map((part) => part.id));
|
|
109
|
+
const nodeIds = new Set(placed.nodes.map((node) => node.id));
|
|
110
|
+
const definitionIds = new Set(placed.nodes.filter((node) => node.kind === "definition").map((node) => node.id));
|
|
111
|
+
for (const node of placed.nodes) {
|
|
112
|
+
if (node.kind === "instance" && !partIds.has(node.partId)) problems.push(`${node.id} places the unknown part ${node.partId}`);
|
|
113
|
+
if (node.kind === "instance" && !nodeIds.has(node.parentId)) problems.push(`${node.id} sits under the unknown module ${node.parentId}`);
|
|
114
|
+
if (node.kind === "reference" && !definitionIds.has(node.definitionId)) problems.push(`${node.id} references the unknown definition ${node.definitionId}`);
|
|
115
|
+
}
|
|
116
|
+
const neighbours = 2 * placed.params.armLength * Math.sin(Math.PI / arms);
|
|
117
|
+
if (!(placed.params.propDiameter < neighbours)) problems.push(`${arms} arms: ${placed.params.propDiameter} mm propellers overlap at ${round(neighbours)} mm motor spacing`);
|
|
118
|
+
if (placed.params.propDiameter > maxPropDiameter(arms, placed.params.armLength)) problems.push(`${arms} arms: the propeller was not limited`);
|
|
119
|
+
layouts[`arms${arms}`] = { instances: placed.counts.instances, bolts: placed.counts.bolts, propDiameter: placed.params.propDiameter };
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
const { document } = await buildDocument(occt, model);
|
|
123
|
+
const bom = await billOfMaterials(occt, document);
|
|
124
|
+
const tree = await occt.assembly.query.getAssemblyHierarchy({ document });
|
|
125
|
+
const expectedNodes = 1 + model.counts.modules + model.counts.references + model.counts.instances;
|
|
126
|
+
if (bom.parts !== model.parts.length) problems.push(`the document holds ${bom.parts} parts, not ${model.parts.length}`);
|
|
127
|
+
if (bom.instances !== model.counts.instances) problems.push(`the bill of materials counts ${bom.instances} placements, not ${model.counts.instances}`);
|
|
128
|
+
if (tree.totalNodes !== expectedNodes) problems.push(`the hierarchy has ${tree.totalNodes} nodes, not ${expectedNodes}`);
|
|
129
|
+
const legs = (await occt.assembly.query.getDocumentParts({ document })).find((entry) => entry.name === "Leg");
|
|
130
|
+
if (legs?.instanceCount !== 4) problems.push(`the leg sub-assembly is placed ${legs?.instanceCount ?? 0} times, not 4`);
|
|
131
|
+
|
|
132
|
+
const glb = await occt.assembly.manager.exportDocumentToGltf({ document, meshDeflection: 0.05, meshAngle: 0.5, internalVerticesMode: false, controlSurfaceDeflection: false, mergeFaces: true, forceUVExport: false, fileName: "drone.glb", tryDownload: false });
|
|
133
|
+
if (new TextDecoder().decode(glb.subarray(0, 4)) !== "glTF") problems.push("the GLB export does not start with the glTF magic");
|
|
134
|
+
const zUp = await buildDocument(occt, model, Z_UP);
|
|
135
|
+
const step = await occt.assembly.manager.exportDocumentToStep({ document: zUp.document, fileName: "drone.step", author: "smoke", organization: "smoke", compress: false, tryDownload: false });
|
|
136
|
+
const stepText = new TextDecoder().decode(step);
|
|
137
|
+
if (!stepText.startsWith("ISO-10303-21")) problems.push("the STEP export does not start with ISO-10303-21");
|
|
138
|
+
const reloaded = service.io.loadSTEPorIGES({ filetext: stepText, fileName: "drone.step", adjustZtoY: false });
|
|
139
|
+
const reloadedShape = reloaded ? asShape(reloaded) : undefined;
|
|
140
|
+
const reloadedSolids = reloadedShape ? (await solidsOf(reloadedShape)).length : 0;
|
|
141
|
+
const expectedSolids = expectedPlacements(model).solidsOf((part) => statsOf(part.id).solids);
|
|
142
|
+
if (reloadedSolids !== expectedSolids) problems.push(`the STEP reads back with ${reloadedSolids} solids, not ${expectedSolids}`);
|
|
143
|
+
const origin: [number, number, number] = [0, 0, 0];
|
|
144
|
+
const box = reloadedShape ? await occt.operations.boundingBoxOfShape({ shape: reloadedShape }) : { min: origin, max: origin };
|
|
145
|
+
const nutTop = model.lift + MOTOR_TOP + 3.5;
|
|
146
|
+
const reach = model.params.armLength + model.params.propDiameter / 2;
|
|
147
|
+
if (Math.abs(box.min[2]) > 0.5) problems.push(`the feet stand at z ${round(box.min[2])} in the Z-up STEP, not on the ground`);
|
|
148
|
+
if (box.max[2] < nutTop - 0.5 || box.max[2] > nutTop + FRAME.propeller.hubAbove + 12) problems.push(`the Z-up STEP tops out at ${round(box.max[2])}, not around the propeller nuts at ${round(nutTop)}`);
|
|
149
|
+
if (Math.max(Math.abs(box.min[0]), box.max[0], Math.abs(box.min[1]), box.max[1]) > reach + 20) problems.push(`the STEP reaches beyond ${reach} mm from the centre`);
|
|
150
|
+
|
|
151
|
+
console.log(JSON.stringify({
|
|
152
|
+
template: "drone-assembly",
|
|
153
|
+
params: model.params,
|
|
154
|
+
emblem: logo !== undefined,
|
|
155
|
+
partsMs,
|
|
156
|
+
parts,
|
|
157
|
+
layouts,
|
|
158
|
+
bom: Object.fromEntries(bom.rows.map((row) => [row.name, row.count])),
|
|
159
|
+
modules: model.counts.modules,
|
|
160
|
+
legPlacements: model.counts.references,
|
|
161
|
+
instances: model.counts.instances,
|
|
162
|
+
bolts: model.counts.bolts,
|
|
163
|
+
glbBytes: glb.byteLength,
|
|
164
|
+
stepBytes: step.byteLength,
|
|
165
|
+
stepSolids: reloadedSolids,
|
|
166
|
+
envelope: { min: box.min.map(round), max: box.max.map(round) },
|
|
167
|
+
}));
|
|
168
|
+
|
|
169
|
+
if (problems.length) {
|
|
170
|
+
console.error(`smoke: ${problems.join("; ")}`);
|
|
171
|
+
process.exit(1);
|
|
172
|
+
}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { ORIGIN, transforms, type Occt, type Transform } from "./kernel";
|
|
2
|
+
import { materialSpec, rgba } from "./materials";
|
|
3
|
+
import { partOf, type DroneModel, type InstanceNode, type Part } from "./model";
|
|
4
|
+
|
|
5
|
+
export type Document = Awaited<ReturnType<Occt["assembly"]["manager"]["buildAssemblyDocument"]>>;
|
|
6
|
+
|
|
7
|
+
export interface BuiltDocument {
|
|
8
|
+
document: Document;
|
|
9
|
+
sources: Document[];
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface BomRow {
|
|
13
|
+
name: string;
|
|
14
|
+
count: number;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export interface Bom {
|
|
18
|
+
rows: BomRow[];
|
|
19
|
+
parts: number;
|
|
20
|
+
instances: number;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export const Z_UP: Transform = transforms.rotationCenterX({ center: ORIGIN, angle: 90 });
|
|
24
|
+
|
|
25
|
+
type Manager = Occt["assembly"]["manager"];
|
|
26
|
+
type PartDef = Awaited<ReturnType<Manager["createPart"]>>;
|
|
27
|
+
type NodeDef = Awaited<ReturnType<Manager["createInstanceNode"]>>;
|
|
28
|
+
|
|
29
|
+
async function partDefs(manager: Manager, model: DroneModel, ids: Set<string>): Promise<PartDef[]> {
|
|
30
|
+
const defs: PartDef[] = [];
|
|
31
|
+
for (const part of model.parts) {
|
|
32
|
+
if (!ids.has(part.id)) continue;
|
|
33
|
+
defs.push(await manager.createPart({ id: part.id, shape: part.shape, name: part.name, colorRgba: rgba(materialSpec(part.material, model.params.finish).colour) }));
|
|
34
|
+
}
|
|
35
|
+
return defs;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
async function instanceDef(manager: Manager, model: DroneModel, node: InstanceNode): Promise<NodeDef> {
|
|
39
|
+
if (node.material) {
|
|
40
|
+
const colorRgba = rgba(materialSpec(node.material, model.params.finish).colour);
|
|
41
|
+
return manager.createInstanceNode({ id: node.id, partId: node.partId, name: node.name, parentId: node.parentId, matrix: node.placement, colorRgba });
|
|
42
|
+
}
|
|
43
|
+
return manager.createInstanceNode({ id: node.id, partId: node.partId, name: node.name, parentId: node.parentId, matrix: node.placement });
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export async function buildDocument(occt: Occt, model: DroneModel, frame?: Transform): Promise<BuiltDocument> {
|
|
47
|
+
const manager = occt.assembly.manager;
|
|
48
|
+
const definitions = model.nodes.filter((node) => node.kind === "definition");
|
|
49
|
+
const sources: Document[] = [];
|
|
50
|
+
const imported = [];
|
|
51
|
+
for (const [index, definition] of definitions.entries()) {
|
|
52
|
+
const children = model.nodes.filter((node): node is InstanceNode => node.kind === "instance" && node.parentId === definition.id);
|
|
53
|
+
const parts = await partDefs(manager, model, new Set(children.map((child) => child.partId)));
|
|
54
|
+
const nodes = [await manager.createAssemblyNode({ id: definition.id, name: definition.name })];
|
|
55
|
+
for (const child of children) nodes.push(await instanceDef(manager, model, child));
|
|
56
|
+
sources.push(await manager.buildAssemblyDocument({ structure: await manager.combineStructure({ parts, nodes, clearDocument: false }) }));
|
|
57
|
+
imported.push(await manager.createImportedPart({ id: definition.id, sourceDocumentIndex: index, name: definition.name }));
|
|
58
|
+
}
|
|
59
|
+
const definitionIds = new Set(definitions.map((definition) => definition.id));
|
|
60
|
+
const topLevel = model.nodes.filter((node): node is InstanceNode => node.kind === "instance" && !definitionIds.has(node.parentId));
|
|
61
|
+
const parts = await partDefs(manager, model, new Set(topLevel.map((node) => node.partId)));
|
|
62
|
+
const nodes = [await manager.createAssemblyNode({ id: "drone", name: "Drone" })];
|
|
63
|
+
for (const node of model.nodes) {
|
|
64
|
+
if (node.kind === "module") {
|
|
65
|
+
const matrix = frame ? [...node.placement, ...frame] : node.placement;
|
|
66
|
+
nodes.push(await manager.createAssemblyNode({ id: node.id, name: node.name, parentId: node.parentId ?? "drone", matrix }));
|
|
67
|
+
} else if (node.kind === "reference") {
|
|
68
|
+
nodes.push(await manager.createInstanceNode({ id: node.id, partId: node.definitionId, name: node.name, parentId: node.parentId, matrix: node.placement }));
|
|
69
|
+
} else if (node.kind === "instance" && !definitionIds.has(node.parentId)) {
|
|
70
|
+
nodes.push(await instanceDef(manager, model, node));
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
const structure = await manager.combineStructure({ parts, nodes, loadedParts: imported, clearDocument: false });
|
|
74
|
+
const document = await manager.buildAssemblyDocument({ structure, sourceDocuments: sources });
|
|
75
|
+
return { document, sources };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export async function billOfMaterials(occt: Occt, document: Document): Promise<Bom> {
|
|
79
|
+
const tree = await occt.assembly.query.getAssemblyHierarchy({ document });
|
|
80
|
+
const counts = new Map<string, number>();
|
|
81
|
+
for (const node of tree.nodes) {
|
|
82
|
+
if (node.nodeType !== "instance-part") continue;
|
|
83
|
+
const name = node.definitionName ?? node.name;
|
|
84
|
+
counts.set(name, (counts.get(name) ?? 0) + 1);
|
|
85
|
+
}
|
|
86
|
+
const rows = [...counts.entries()].map(([name, count]) => ({ name, count })).sort((a, b) => b.count - a.count || a.name.localeCompare(b.name));
|
|
87
|
+
return { rows, parts: rows.length, instances: rows.reduce((sum, row) => sum + row.count, 0) };
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export function expectedPlacements(model: DroneModel): { instances: number; solidsOf: (solids: (part: Part) => number) => number } {
|
|
91
|
+
const references = new Map<string, number>();
|
|
92
|
+
for (const node of model.nodes) if (node.kind === "reference") references.set(node.definitionId, (references.get(node.definitionId) ?? 0) + 1);
|
|
93
|
+
const definitionIds = new Set(model.nodes.filter((node) => node.kind === "definition").map((node) => node.id));
|
|
94
|
+
const placed = model.nodes.filter((node): node is InstanceNode => node.kind === "instance").map((node) => ({ node, times: definitionIds.has(node.parentId) ? references.get(node.parentId) ?? 0 : 1 }));
|
|
95
|
+
return {
|
|
96
|
+
instances: placed.reduce((sum, entry) => sum + entry.times, 0),
|
|
97
|
+
solidsOf: (solids) => placed.reduce((sum, entry) => sum + entry.times * solids(partOf(model.parts, entry.node.partId)), 0),
|
|
98
|
+
};
|
|
99
|
+
}
|