bambu-printer-mcp 1.1.46 → 1.1.48
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 +117 -3
- package/dist/blender-mcp-bridge.d.ts +15 -0
- package/dist/blender-mcp-bridge.js +21 -3
- package/dist/counterpart/info.d.ts +10 -0
- package/dist/counterpart/info.js +34 -0
- package/dist/counterpart/make-3mf.d.ts +16 -0
- package/dist/counterpart/make-3mf.js +219 -0
- package/dist/counterpart/progress.d.ts +28 -0
- package/dist/counterpart/progress.js +254 -0
- package/dist/counterpart/schemas.d.ts +322 -0
- package/dist/counterpart/schemas.js +124 -0
- package/dist/fusion-mcp-bridge.d.ts +182 -0
- package/dist/fusion-mcp-bridge.js +557 -0
- package/dist/index.js +197 -17
- package/dist/printers/bambu-stages.d.ts +7 -0
- package/dist/printers/bambu-stages.js +89 -0
- package/dist/printers/bambu.d.ts +79 -8
- package/dist/printers/bambu.js +311 -56
- package/dist/printers/camera-models.d.ts +7 -0
- package/dist/printers/camera-models.js +18 -0
- package/dist/safety/hms-messages.d.ts +42 -0
- package/dist/safety/hms-messages.js +6194 -0
- package/dist/safety/printer-state.d.ts +20 -2
- package/dist/safety/printer-state.js +5 -5
- package/dist/slicer/process-overrides.d.ts +12 -0
- package/dist/slicer/process-overrides.js +33 -0
- package/dist/slicer/remote-slicer.js +2 -0
- package/dist/stl/stl-manipulator.d.ts +2 -0
- package/dist/stl/stl-manipulator.js +19 -0
- package/package.json +1 -1
- package/src/blender-mcp-bridge.ts +22 -3
- package/src/counterpart/info.ts +36 -0
- package/src/counterpart/make-3mf.ts +220 -0
- package/src/counterpart/progress.ts +254 -0
- package/src/counterpart/schemas.ts +154 -0
- package/src/fusion-mcp-bridge.ts +545 -0
- package/src/index.ts +204 -17
- package/src/printers/bambu-stages.ts +90 -0
- package/src/printers/bambu.ts +329 -56
- package/src/printers/camera-models.ts +18 -0
- package/src/safety/hms-messages.ts +6198 -0
- package/src/safety/printer-state.ts +6 -6
- package/src/slicer/process-overrides.ts +42 -0
- package/src/slicer/remote-slicer.ts +2 -0
- package/src/stl/stl-manipulator.ts +22 -0
|
@@ -39,6 +39,7 @@ export interface ValidatedPrinterState {
|
|
|
39
39
|
reportedNozzles: ReportedNozzle[];
|
|
40
40
|
filaments: ReportedFilament[];
|
|
41
41
|
}
|
|
42
|
+
export declare function finiteNumber(value: unknown): number | undefined;
|
|
42
43
|
/**
|
|
43
44
|
* X2D retains FAILED after a canceled job even with no active print error.
|
|
44
45
|
* Bambu Studio classifies FAILED as a finished job; its v02.08.02.61
|
|
@@ -46,19 +47,36 @@ export interface ValidatedPrinterState {
|
|
|
46
47
|
* calls 0300400C "The task was canceled."
|
|
47
48
|
* Only this observed terminal condition qualifies, never an arbitrary failure.
|
|
48
49
|
* Callers still validate HMS, identity, hardware and material configuration,
|
|
49
|
-
* and print dispatch
|
|
50
|
+
* and print dispatch rechecks the identity of the observed job.
|
|
50
51
|
*/
|
|
51
52
|
export declare function isCancelledX2DJob(raw: Record<string, any>, model: string): boolean;
|
|
52
53
|
/** Bambu Studio 2.8.2.61 marks FAILED as finished. Limit P1S recovery to
|
|
53
54
|
* a named prior job explicitly reporting idle, no print error and no HMS.
|
|
54
|
-
*
|
|
55
|
+
* Dispatch rechecks the observed job identity. */
|
|
55
56
|
export declare function isFinishedP1SJob(raw: Record<string, any>, model: string): boolean;
|
|
56
57
|
/** Nozzles whose reported diameter and type are configured settings rather than chip readings. */
|
|
57
58
|
export declare function unchippedNozzles(raw: unknown): number[];
|
|
59
|
+
export type HmsEntry = {
|
|
60
|
+
attr: number;
|
|
61
|
+
code: number;
|
|
62
|
+
severity: number;
|
|
63
|
+
hex: string;
|
|
64
|
+
};
|
|
65
|
+
export declare function hmsCode(entry: any): HmsEntry | undefined;
|
|
58
66
|
/** The one key format for a reported entry, shared by the gate and clear_hms_errors. */
|
|
59
67
|
export declare function reportedHmsKey(entry: unknown): string;
|
|
60
68
|
/** Bambu's display form of a cleared-code key such as "hms:83887616:131184"; other keys unchanged. */
|
|
61
69
|
export declare function describeHmsKey(key: string): string;
|
|
70
|
+
/**
|
|
71
|
+
* A serious or common entry that Bambu lists for this serial prefix with empty
|
|
72
|
+
* text: Bambu Studio, Bambu Handy and the printer screen never show it, and
|
|
73
|
+
* the printer keeps printing with it (an X2D raises 0500-0600-0002-0070 at
|
|
74
|
+
* every boot). Bambu Studio selects the table by serial prefix, so this does
|
|
75
|
+
* too, but only when that prefix belongs to the verified model: a sparse report
|
|
76
|
+
* without a serial must not let a misconfigured serial pick another model's
|
|
77
|
+
* table. Fatal, invalid-level and unlisted entries never qualify.
|
|
78
|
+
*/
|
|
79
|
+
export declare function isHiddenNotice(serial: string, model: string, entry: HmsEntry): boolean;
|
|
62
80
|
/** Labels of reported entries that pass only because Bambu hides them for this printer. */
|
|
63
81
|
export declare function hiddenHmsNotices(raw: unknown, serial: string, model: string): string[];
|
|
64
82
|
/** Cleared-code keys of reported hidden entries; clearing never removes them, so they are not re-acknowledged. */
|
|
@@ -110,7 +110,7 @@ export function readFreshPrinterStatus(printer, serial, timeoutMs = 5000) {
|
|
|
110
110
|
.then(() => { requestsPublished = true; maybeResolve(); }, fail);
|
|
111
111
|
});
|
|
112
112
|
}
|
|
113
|
-
function finiteNumber(value) {
|
|
113
|
+
export function finiteNumber(value) {
|
|
114
114
|
if (typeof value !== "number" && (typeof value !== "string" || !value.trim()))
|
|
115
115
|
return undefined;
|
|
116
116
|
const number = Number(value);
|
|
@@ -123,7 +123,7 @@ function finiteNumber(value) {
|
|
|
123
123
|
* calls 0300400C "The task was canceled."
|
|
124
124
|
* Only this observed terminal condition qualifies, never an arbitrary failure.
|
|
125
125
|
* Callers still validate HMS, identity, hardware and material configuration,
|
|
126
|
-
* and print dispatch
|
|
126
|
+
* and print dispatch rechecks the identity of the observed job.
|
|
127
127
|
*/
|
|
128
128
|
export function isCancelledX2DJob(raw, model) {
|
|
129
129
|
return normalizeModel(model) === "x2d" && raw.gcode_state === "FAILED" &&
|
|
@@ -132,7 +132,7 @@ export function isCancelledX2DJob(raw, model) {
|
|
|
132
132
|
}
|
|
133
133
|
/** Bambu Studio 2.8.2.61 marks FAILED as finished. Limit P1S recovery to
|
|
134
134
|
* a named prior job explicitly reporting idle, no print error and no HMS.
|
|
135
|
-
*
|
|
135
|
+
* Dispatch rechecks the observed job identity. */
|
|
136
136
|
export function isFinishedP1SJob(raw, model) {
|
|
137
137
|
return normalizeModel(model) === "p1s" && raw.gcode_state === "FAILED" && raw.print_type === "idle" &&
|
|
138
138
|
finiteNumber(raw.print_error) === 0 && Array.isArray(raw.hms) && raw.hms.length === 0 &&
|
|
@@ -247,7 +247,7 @@ function reportedNozzles(raw) {
|
|
|
247
247
|
return output;
|
|
248
248
|
}
|
|
249
249
|
const hiddenHmsSets = new Map(Object.entries(HIDDEN_HMS).map(([prefix, codes]) => [prefix, new Set(codes)]));
|
|
250
|
-
function hmsCode(entry) {
|
|
250
|
+
export function hmsCode(entry) {
|
|
251
251
|
const code = finiteNumber(entry?.code);
|
|
252
252
|
const attr = finiteNumber(entry?.attr);
|
|
253
253
|
const valid = (value) => value !== undefined && Number.isInteger(value) && value >= 0 && value <= 0xffffffff;
|
|
@@ -278,7 +278,7 @@ export function describeHmsKey(key) {
|
|
|
278
278
|
* without a serial must not let a misconfigured serial pick another model's
|
|
279
279
|
* table. Fatal, invalid-level and unlisted entries never qualify.
|
|
280
280
|
*/
|
|
281
|
-
function isHiddenNotice(serial, model, entry) {
|
|
281
|
+
export function isHiddenNotice(serial, model, entry) {
|
|
282
282
|
if (entry.severity !== 2 && entry.severity !== 3)
|
|
283
283
|
return false;
|
|
284
284
|
const prefix = serial.trim().toUpperCase().slice(0, 3);
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* slice_stl's layer_height, wall_loops and sparse_infill_density arguments
|
|
3
|
+
* (PRD §8.4). They are written over the process preset the slicer already
|
|
4
|
+
* resolved, using Bambu Studio/Orca keys and their string forms ("0.2", "2",
|
|
5
|
+
* "15%"), so the machine preset and every other process value stay as resolved.
|
|
6
|
+
*/
|
|
7
|
+
export type ProcessOverrides = Partial<Record<"layer_height" | "wall_loops" | "sparse_infill_density", string>>;
|
|
8
|
+
export declare const PROCESS_OVERRIDE_KEYS: readonly ["layer_height", "wall_loops", "sparse_infill_density"];
|
|
9
|
+
/** Validate the tool arguments; undefined when none are given. */
|
|
10
|
+
export declare function parseProcessOverrides(args: Record<string, unknown> | undefined, nozzleDiameter: number): ProcessOverrides | undefined;
|
|
11
|
+
/** The process profile with the overrides written over its values. */
|
|
12
|
+
export declare function applyProcessOverrides(profile: Record<string, unknown>, overrides: ProcessOverrides): Record<string, unknown>;
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
export const PROCESS_OVERRIDE_KEYS = ["layer_height", "wall_loops", "sparse_infill_density"];
|
|
2
|
+
/** Validate the tool arguments; undefined when none are given. */
|
|
3
|
+
export function parseProcessOverrides(args, nozzleDiameter) {
|
|
4
|
+
const overrides = {};
|
|
5
|
+
const layerHeight = args?.layer_height;
|
|
6
|
+
if (layerHeight !== undefined) {
|
|
7
|
+
if (typeof layerHeight !== "number" || !Number.isFinite(layerHeight) || layerHeight <= 0 ||
|
|
8
|
+
(Number.isFinite(nozzleDiameter) && nozzleDiameter > 0 && layerHeight > nozzleDiameter)) {
|
|
9
|
+
throw new Error("layer_height must be a positive number of millimetres, no larger than the nozzle diameter.");
|
|
10
|
+
}
|
|
11
|
+
overrides.layer_height = String(Number(layerHeight.toFixed(4)));
|
|
12
|
+
}
|
|
13
|
+
const wallLoops = args?.wall_loops;
|
|
14
|
+
if (wallLoops !== undefined) {
|
|
15
|
+
// Bambu Studio's wall_loops option ranges from 0 to 1000.
|
|
16
|
+
if (typeof wallLoops !== "number" || !Number.isInteger(wallLoops) || wallLoops < 0 || wallLoops > 1000) {
|
|
17
|
+
throw new Error("wall_loops must be an integer from 0 to 1000.");
|
|
18
|
+
}
|
|
19
|
+
overrides.wall_loops = String(wallLoops);
|
|
20
|
+
}
|
|
21
|
+
const density = args?.sparse_infill_density;
|
|
22
|
+
if (density !== undefined) {
|
|
23
|
+
const match = typeof density === "string" ? /^\s*(\d+(?:\.\d+)?)\s*%\s*$/.exec(density) : null;
|
|
24
|
+
if (!match || Number(match[1]) > 100)
|
|
25
|
+
throw new Error('sparse_infill_density must be a percentage from 0% to 100%, such as "15%".');
|
|
26
|
+
overrides.sparse_infill_density = `${Number(match[1])}%`;
|
|
27
|
+
}
|
|
28
|
+
return Object.keys(overrides).length ? overrides : undefined;
|
|
29
|
+
}
|
|
30
|
+
/** The process profile with the overrides written over its values. */
|
|
31
|
+
export function applyProcessOverrides(profile, overrides) {
|
|
32
|
+
return { ...profile, ...overrides };
|
|
33
|
+
}
|
|
@@ -8,6 +8,8 @@ const MAX_BYTES = 100000000;
|
|
|
8
8
|
const SUPPORTED_OPTIONS = new Set([
|
|
9
9
|
'arrange', 'orient', 'loadFilaments', 'filamentColours', 'bedType',
|
|
10
10
|
'nozzleType', 'nozzleVolumeType', 'slicePlate',
|
|
11
|
+
// Written into the uploaded process preset before the request, not sent as API options.
|
|
12
|
+
'processOverrides',
|
|
11
13
|
]);
|
|
12
14
|
function configuration() {
|
|
13
15
|
let url;
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import * as THREE from 'three';
|
|
2
2
|
import { EventEmitter } from 'events';
|
|
3
|
+
import { type ProcessOverrides } from '../slicer/process-overrides.js';
|
|
3
4
|
export type ProgressCallback = (progress: number, message?: string) => void;
|
|
4
5
|
export type OperationResult = {
|
|
5
6
|
success: boolean;
|
|
@@ -49,6 +50,7 @@ export interface BambuSliceOptions {
|
|
|
49
50
|
minSave?: boolean;
|
|
50
51
|
skipModifiedGcodes?: boolean;
|
|
51
52
|
slicePlate?: number;
|
|
53
|
+
processOverrides?: ProcessOverrides;
|
|
52
54
|
}
|
|
53
55
|
export declare class STLManipulator extends EventEmitter {
|
|
54
56
|
private tempDir;
|
|
@@ -10,6 +10,7 @@ import { EventEmitter } from 'events';
|
|
|
10
10
|
import * as crypto from 'crypto';
|
|
11
11
|
import { execFile } from 'child_process';
|
|
12
12
|
import { flattenForCli, detectProfilesRoot, resolveBblMachineProfile } from '../slicer/profile-flatten.js';
|
|
13
|
+
import { applyProcessOverrides } from '../slicer/process-overrides.js';
|
|
13
14
|
import { profileJsonFiles } from '../slicer/profile-files.js';
|
|
14
15
|
import { materializeOrcaProfilesRoot, stageOrcaCliProfiles } from '../slicer/orca-profile-cache.js';
|
|
15
16
|
import { sliceWithOrcaApi, validateRemoteSliceOptions } from '../slicer/remote-slicer.js';
|
|
@@ -1315,6 +1316,9 @@ export class STLManipulator extends EventEmitter {
|
|
|
1315
1316
|
}
|
|
1316
1317
|
const outputFileName = path.basename(stlFilePath, '.stl') + '.gcode';
|
|
1317
1318
|
let outputFilePath = path.join(this.tempDir, outputFileName);
|
|
1319
|
+
if (bambuOptions?.processOverrides && !['bambustudio', 'orcaslicer', 'orcaslicer-bambulab', 'orca-slicer-api'].includes(slicerType)) {
|
|
1320
|
+
throw new Error(`layer_height, wall_loops and sparse_infill_density need a Bambu-compatible slicer (bambustudio, orcaslicer, orcaslicer-bambulab or orca-slicer-api), not ${slicerType}.`);
|
|
1321
|
+
}
|
|
1318
1322
|
let args = [];
|
|
1319
1323
|
let cliResult;
|
|
1320
1324
|
const orcaTemporaryDirectories = [];
|
|
@@ -1403,6 +1407,21 @@ export class STLManipulator extends EventEmitter {
|
|
|
1403
1407
|
this.writeTempJson(outputBase, 'process_orca_resolved', this.sanitizeProcessForOrca(this.readJsonFile(processPath), printerPreset)),
|
|
1404
1408
|
].join(';');
|
|
1405
1409
|
}
|
|
1410
|
+
// Print-sheet quality settings go over the fully resolved process
|
|
1411
|
+
// preset, after flattening and Orca normalization, so every
|
|
1412
|
+
// Bambu-compatible route (local CLI, Orca cache staging, remote API)
|
|
1413
|
+
// slices with them and the machine preset is untouched.
|
|
1414
|
+
if (bambuOptions?.processOverrides) {
|
|
1415
|
+
const [machinePath, processPath, ...rest] = settingsBundle.settingsArg?.split(';') ?? [];
|
|
1416
|
+
if (!machinePath || !processPath) {
|
|
1417
|
+
throw new Error('layer_height, wall_loops and sparse_infill_density need a resolved machine and process preset.');
|
|
1418
|
+
}
|
|
1419
|
+
settingsBundle.settingsArg = [
|
|
1420
|
+
machinePath,
|
|
1421
|
+
this.writeTempJson(outputBase, 'process_override', applyProcessOverrides(this.readJsonFile(processPath), bambuOptions.processOverrides)),
|
|
1422
|
+
...rest,
|
|
1423
|
+
].join(';');
|
|
1424
|
+
}
|
|
1406
1425
|
let cliBundle = this.isolateMachineSettings(settingsBundle);
|
|
1407
1426
|
let orcaExtraArgs = [];
|
|
1408
1427
|
if (!remote && profileSlicerType === 'orcaslicer' && profilesRoot !== selectedProfilesRoot) {
|
package/package.json
CHANGED
|
@@ -84,7 +84,15 @@ function normalizeToolFailure(result: CallToolResult): CallToolResult {
|
|
|
84
84
|
return failed ? { ...result, isError: true } : result;
|
|
85
85
|
}
|
|
86
86
|
|
|
87
|
-
|
|
87
|
+
export type StlBoundingBox = { min: [number, number, number]; max: [number, number, number]; dimensions: [number, number, number] };
|
|
88
|
+
|
|
89
|
+
export async function regularStl(filePath: string): Promise<{ bytes: number; triangles: number }> {
|
|
90
|
+
const { bytes, triangles } = await stlMetadata(filePath);
|
|
91
|
+
return { bytes, triangles };
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** regularStl plus the mesh's bounding box in the STL's own units (rounded to 1e-4). */
|
|
95
|
+
export async function stlMetadata(filePath: string): Promise<{ bytes: number; triangles: number; bounding_box: StlBoundingBox }> {
|
|
88
96
|
const stat = await fs.lstat(filePath).catch(() => { throw new BlenderError("STL file does not exist or is not readable."); });
|
|
89
97
|
if (!stat.isFile() || stat.size === 0 || stat.size > MAX_STL_BYTES) throw new BlenderError("STL must be a non-empty regular file of at most 256 MiB.");
|
|
90
98
|
const buffer = await fs.readFile(filePath);
|
|
@@ -94,10 +102,21 @@ async function regularStl(filePath: string): Promise<{ bytes: number; triangles:
|
|
|
94
102
|
const positions = geometry.getAttribute("position");
|
|
95
103
|
if (!positions || positions.count < 3 || positions.count % 3 !== 0) throw new Error("invalid vertices");
|
|
96
104
|
// Scan the typed array in place; boxing a large mesh can exhaust the JS heap.
|
|
105
|
+
const min = [Infinity, Infinity, Infinity], max = [-Infinity, -Infinity, -Infinity];
|
|
97
106
|
for (let index = 0; index < positions.array.length; index++) {
|
|
98
|
-
|
|
107
|
+
const value = positions.array[index];
|
|
108
|
+
if (!Number.isFinite(value)) throw new Error("invalid vertices");
|
|
109
|
+
const axis = index % 3;
|
|
110
|
+
if (value < min[axis]) min[axis] = value;
|
|
111
|
+
if (value > max[axis]) max[axis] = value;
|
|
99
112
|
}
|
|
100
|
-
|
|
113
|
+
const round = (value: number) => Math.round(value * 1e4) / 1e4;
|
|
114
|
+
const bounding_box: StlBoundingBox = {
|
|
115
|
+
min: [round(min[0]), round(min[1]), round(min[2])],
|
|
116
|
+
max: [round(max[0]), round(max[1]), round(max[2])],
|
|
117
|
+
dimensions: [round(max[0] - min[0]), round(max[1] - min[1]), round(max[2] - min[2])],
|
|
118
|
+
};
|
|
119
|
+
return { bytes: stat.size, triangles: positions.count / 3, bounding_box };
|
|
101
120
|
} catch { throw new BlenderError("STL contains no valid finite triangle mesh."); }
|
|
102
121
|
finally { geometry?.dispose(); }
|
|
103
122
|
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/** counterpart_printer_info for Bambu printers (PRD §8.4). Pure: no printer traffic. */
|
|
2
|
+
import { RTSP_CAMERA_MODELS, TCP_CAMERA_MODELS } from "../printers/camera-models.js";
|
|
3
|
+
import { normalizeModel } from "../safety/limits.js";
|
|
4
|
+
import { SERIAL_MODELS } from "../safety/printer-state.js";
|
|
5
|
+
import { COUNTERPART_CONTRACT, type PrinterInfo } from "./schemas.js";
|
|
6
|
+
|
|
7
|
+
/** Bambu's display names ("P1S", "A1 Mini", "H2D Pro"), keyed by normalized model. */
|
|
8
|
+
const DISPLAY_NAMES = new Map(Object.values(SERIAL_MODELS).map(name => [normalizeModel(name), name]));
|
|
9
|
+
|
|
10
|
+
export function bambuPrinterInfo(options: { server: { name: string; version: string }; host: string; serial?: string; model?: string }): PrinterInfo {
|
|
11
|
+
const model = normalizeModel(options.model);
|
|
12
|
+
const serial = options.serial?.trim();
|
|
13
|
+
return {
|
|
14
|
+
contract: COUNTERPART_CONTRACT,
|
|
15
|
+
server: options.server,
|
|
16
|
+
printer: {
|
|
17
|
+
kind: "bambu",
|
|
18
|
+
...(model ? { model: DISPLAY_NAMES.get(model) ?? model.toUpperCase() } : {}),
|
|
19
|
+
...(serial ? { serial } : {}),
|
|
20
|
+
host: options.host,
|
|
21
|
+
},
|
|
22
|
+
capabilities: {
|
|
23
|
+
progress: true,
|
|
24
|
+
layers: true,
|
|
25
|
+
// camera_snapshot needs the model to choose its transport.
|
|
26
|
+
camera: model && TCP_CAMERA_MODELS.has(model) ? "bambu-tcp" : model && RTSP_CAMERA_MODELS.has(model) ? "rtsp" : "none",
|
|
27
|
+
filaments: "ams",
|
|
28
|
+
pause: true,
|
|
29
|
+
resume: true,
|
|
30
|
+
cancel: true,
|
|
31
|
+
print3mf: true,
|
|
32
|
+
// X2D jobs go through its native route; FTPS/remote-file G-code starts stay blocked there.
|
|
33
|
+
gcode: model !== "x2d",
|
|
34
|
+
},
|
|
35
|
+
};
|
|
36
|
+
}
|
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* counterpart_make_3mf: combine separately exported STL parts into one 3MF for
|
|
3
|
+
* multi-colour printing (PRD §8.4/§8.5, M3b).
|
|
4
|
+
*
|
|
5
|
+
* The 3MF holds one object, an assembly with one part per STL, and each part
|
|
6
|
+
* names its filament in Metadata/model_settings.config. One object per part
|
|
7
|
+
* does not work with Bambu Studio 02.08.02.61's CLI: it arranges separate
|
|
8
|
+
* objects apart, with arrange off it reports G-code path conflicts between
|
|
9
|
+
* stacked parts, and --load-filament-ids is refused for 3MF input. An assembly
|
|
10
|
+
* keeps the parts where they were exported and still slices one filament per
|
|
11
|
+
* part. Vertices are copied unchanged, so parts keep their relative positions;
|
|
12
|
+
* one shared transform puts the assembly on the plate.
|
|
13
|
+
*/
|
|
14
|
+
import { randomUUID } from "node:crypto";
|
|
15
|
+
import fs from "node:fs/promises";
|
|
16
|
+
import path from "node:path";
|
|
17
|
+
import JSZip from "jszip";
|
|
18
|
+
import { STLLoader } from "three/examples/jsm/loaders/STLLoader.js";
|
|
19
|
+
import { MACHINE_LIMITS, normalizeModel } from "../safety/limits.js";
|
|
20
|
+
import { COUNTERPART_CONTRACT } from "./schemas.js";
|
|
21
|
+
|
|
22
|
+
const MAX_PARTS = 64;
|
|
23
|
+
const MAX_FILAMENT = 64;
|
|
24
|
+
const MAX_STL_BYTES = 256 * 1024 * 1024;
|
|
25
|
+
const MAX_TOTAL_TRIANGLES = 5_000_000;
|
|
26
|
+
const PART_KEYS = new Set(["stl_path", "name", "filament"]);
|
|
27
|
+
|
|
28
|
+
export class Make3mfError extends Error {}
|
|
29
|
+
|
|
30
|
+
type Mesh = { vertices: Float32Array; indices: Uint32Array; triangles: number; min: number[]; max: number[] };
|
|
31
|
+
type Part = { name: string; stlPath: string; filament: number; mesh: Mesh };
|
|
32
|
+
export type Make3mfResult = {
|
|
33
|
+
contract: typeof COUNTERPART_CONTRACT;
|
|
34
|
+
path: string;
|
|
35
|
+
objects: number;
|
|
36
|
+
filaments: number;
|
|
37
|
+
parts: { name: string; stl_path: string; filament: number; triangles: number }[];
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
function fail(message: string): never { throw new Make3mfError(message); }
|
|
41
|
+
|
|
42
|
+
function nonEmptyText(value: unknown, label: string): string {
|
|
43
|
+
if (typeof value !== "string" || !value.trim() || value.includes("\0")) fail(`${label} must be a non-empty string without NUL characters.`);
|
|
44
|
+
return value;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Parse a binary or ASCII STL into an indexed mesh, merging bit-identical vertices so edges stay shared. */
|
|
48
|
+
async function readMesh(filePath: string, label: string): Promise<Mesh> {
|
|
49
|
+
const stat = await fs.lstat(filePath).catch(() => fail(`${label} does not exist or is not readable.`));
|
|
50
|
+
if (!stat.isFile() || stat.size === 0 || stat.size > MAX_STL_BYTES) fail(`${label} must be a non-empty regular STL file of at most 256 MiB.`);
|
|
51
|
+
const buffer = await fs.readFile(filePath);
|
|
52
|
+
let geometry;
|
|
53
|
+
try {
|
|
54
|
+
geometry = new STLLoader().parse(Uint8Array.from(buffer).buffer);
|
|
55
|
+
const positions = geometry.getAttribute("position");
|
|
56
|
+
if (!positions || positions.count < 3 || positions.count % 3 !== 0) throw new Error("no triangles");
|
|
57
|
+
const source = positions.array as Float32Array;
|
|
58
|
+
const bits = new Uint32Array(source.buffer, source.byteOffset, source.length);
|
|
59
|
+
const lookup = new Map<string, number>();
|
|
60
|
+
const vertices: number[] = [];
|
|
61
|
+
const indices = new Uint32Array(positions.count);
|
|
62
|
+
const min = [Infinity, Infinity, Infinity], max = [-Infinity, -Infinity, -Infinity];
|
|
63
|
+
for (let vertex = 0; vertex < positions.count; vertex++) {
|
|
64
|
+
const offset = vertex * 3;
|
|
65
|
+
for (let axis = 0; axis < 3; axis++) {
|
|
66
|
+
const value = source[offset + axis];
|
|
67
|
+
if (!Number.isFinite(value)) throw new Error("non-finite vertex");
|
|
68
|
+
if (value < min[axis]) min[axis] = value;
|
|
69
|
+
if (value > max[axis]) max[axis] = value;
|
|
70
|
+
}
|
|
71
|
+
const key = `${bits[offset]},${bits[offset + 1]},${bits[offset + 2]}`;
|
|
72
|
+
let index = lookup.get(key);
|
|
73
|
+
if (index === undefined) {
|
|
74
|
+
index = vertices.length / 3;
|
|
75
|
+
vertices.push(source[offset], source[offset + 1], source[offset + 2]);
|
|
76
|
+
lookup.set(key, index);
|
|
77
|
+
}
|
|
78
|
+
indices[vertex] = index;
|
|
79
|
+
}
|
|
80
|
+
return { vertices: Float32Array.from(vertices), indices, triangles: positions.count / 3, min, max };
|
|
81
|
+
} catch {
|
|
82
|
+
throw new Make3mfError(`${label} contains no valid finite triangle mesh.`);
|
|
83
|
+
} finally {
|
|
84
|
+
geometry?.dispose();
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function xmlAttribute(value: string): string {
|
|
89
|
+
return value.replace(/&/g, "&").replace(/"/g, """).replace(/</g, "<").replace(/>/g, ">")
|
|
90
|
+
.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f]/g, "");
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Shortest decimal that reads back as the same float32. */
|
|
94
|
+
const coordinate = (value: number) => String(Number(value.toPrecision(9)));
|
|
95
|
+
|
|
96
|
+
/** The model XML as buffers, so a large mesh never becomes one giant string. */
|
|
97
|
+
function modelXml(parts: Part[], transform: number[]): Buffer {
|
|
98
|
+
const chunks: Buffer[] = [];
|
|
99
|
+
let pending: string[] = [];
|
|
100
|
+
const write = (line: string) => {
|
|
101
|
+
pending.push(line);
|
|
102
|
+
if (pending.length >= 20_000) { chunks.push(Buffer.from(pending.join(""))); pending = []; }
|
|
103
|
+
};
|
|
104
|
+
write(`<?xml version="1.0" encoding="UTF-8"?>\n<model unit="millimeter" xml:lang="en-US" xmlns="http://schemas.microsoft.com/3dmanufacturing/core/2015/02" xmlns:BambuStudio="http://schemas.bambulab.com/package/2021">\n`);
|
|
105
|
+
write(` <metadata name="Application">bambu-printer-mcp counterpart_make_3mf</metadata>\n <metadata name="BambuStudio:3mfVersion">1</metadata>\n <resources>\n`);
|
|
106
|
+
parts.forEach((part, index) => {
|
|
107
|
+
write(` <object id="${index + 1}" type="model">\n <mesh>\n <vertices>\n`);
|
|
108
|
+
const { vertices, indices } = part.mesh;
|
|
109
|
+
for (let i = 0; i < vertices.length; i += 3) write(` <vertex x="${coordinate(vertices[i])}" y="${coordinate(vertices[i + 1])}" z="${coordinate(vertices[i + 2])}"/>\n`);
|
|
110
|
+
write(` </vertices>\n <triangles>\n`);
|
|
111
|
+
for (let i = 0; i < indices.length; i += 3) write(` <triangle v1="${indices[i]}" v2="${indices[i + 1]}" v3="${indices[i + 2]}"/>\n`);
|
|
112
|
+
write(` </triangles>\n </mesh>\n </object>\n`);
|
|
113
|
+
});
|
|
114
|
+
const assembly = parts.length + 1;
|
|
115
|
+
write(` <object id="${assembly}" type="model">\n <components>\n`);
|
|
116
|
+
parts.forEach((_, index) => write(` <component objectid="${index + 1}"/>\n`));
|
|
117
|
+
write(` </components>\n </object>\n </resources>\n <build>\n`);
|
|
118
|
+
write(` <item objectid="${assembly}" transform="1 0 0 0 1 0 0 0 1 ${transform.map(coordinate).join(" ")}"/>\n </build>\n</model>\n`);
|
|
119
|
+
chunks.push(Buffer.from(pending.join("")));
|
|
120
|
+
return Buffer.concat(chunks);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function modelSettingsXml(parts: Part[], name: string): string {
|
|
124
|
+
const assembly = parts.length + 1;
|
|
125
|
+
const partBlocks = parts.map((part, index) => ` <part id="${index + 1}" subtype="normal_part">
|
|
126
|
+
<metadata key="name" value="${xmlAttribute(part.name)}"/>
|
|
127
|
+
<metadata key="extruder" value="${part.filament}"/>
|
|
128
|
+
</part>`).join("\n");
|
|
129
|
+
return `<?xml version="1.0" encoding="UTF-8"?>
|
|
130
|
+
<config>
|
|
131
|
+
<object id="${assembly}">
|
|
132
|
+
<metadata key="name" value="${xmlAttribute(name)}"/>
|
|
133
|
+
<metadata key="extruder" value="${parts[0].filament}"/>
|
|
134
|
+
${partBlocks}
|
|
135
|
+
</object>
|
|
136
|
+
</config>
|
|
137
|
+
`;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
const CONTENT_TYPES = `<?xml version="1.0" encoding="UTF-8"?>
|
|
141
|
+
<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">
|
|
142
|
+
<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>
|
|
143
|
+
<Default Extension="model" ContentType="application/vnd.ms-package.3dmanufacturing-3dmodel+xml"/>
|
|
144
|
+
<Default Extension="config" ContentType="application/octet-stream"/>
|
|
145
|
+
</Types>
|
|
146
|
+
`;
|
|
147
|
+
const RELATIONSHIPS = `<?xml version="1.0" encoding="UTF-8"?>
|
|
148
|
+
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
|
|
149
|
+
<Relationship Target="/3D/3dmodel.model" Id="rel-1" Type="http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel"/>
|
|
150
|
+
</Relationships>
|
|
151
|
+
`;
|
|
152
|
+
|
|
153
|
+
/** Where the assembly's footprint centre goes: the configured model's bed centre, else a 256 mm bed's. */
|
|
154
|
+
function plateCentre(): [number, number] {
|
|
155
|
+
const model = normalizeModel(process.env.BAMBU_PRINTER_MODEL || process.env.BAMBU_MODEL);
|
|
156
|
+
const volume = model ? MACHINE_LIMITS[model]?.volume : undefined;
|
|
157
|
+
return volume ? [volume[0] / 2, volume[1] / 2] : [128, 128];
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
export async function makeCounterpart3mf(args: Record<string, unknown>): Promise<Make3mfResult> {
|
|
161
|
+
if (Object.keys(args).some(key => key !== "parts" && key !== "out_path")) fail("counterpart_make_3mf accepts only parts and out_path.");
|
|
162
|
+
if (!Array.isArray(args.parts) || args.parts.length === 0 || args.parts.length > MAX_PARTS) fail(`parts must list 1 to ${MAX_PARTS} STL parts.`);
|
|
163
|
+
const requested = path.resolve(nonEmptyText(args.out_path, "out_path"));
|
|
164
|
+
if (path.extname(requested).toLowerCase() !== ".3mf") fail("out_path must name a new .3mf file.");
|
|
165
|
+
const directory = await fs.realpath(path.dirname(requested)).catch(() => fail("out_path parent directory must already exist."));
|
|
166
|
+
const outPath = path.join(directory, path.basename(requested));
|
|
167
|
+
const existing = await fs.lstat(outPath).catch((error: NodeJS.ErrnoException) => {
|
|
168
|
+
if (error.code !== "ENOENT") fail("out_path cannot be accessed.");
|
|
169
|
+
return undefined;
|
|
170
|
+
});
|
|
171
|
+
if (existing) fail("out_path already exists; choose a new file. Existing files are never overwritten.");
|
|
172
|
+
|
|
173
|
+
const parts: Part[] = [];
|
|
174
|
+
let triangles = 0;
|
|
175
|
+
for (const [index, value] of args.parts.entries()) {
|
|
176
|
+
const label = `parts[${index}]`;
|
|
177
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) fail(`${label} must be an object with stl_path and name.`);
|
|
178
|
+
const entry = value as Record<string, unknown>;
|
|
179
|
+
if (Object.keys(entry).some(key => !PART_KEYS.has(key))) fail(`${label} accepts only stl_path, name and filament.`);
|
|
180
|
+
const name = nonEmptyText(entry.name, `${label}.name`).trim();
|
|
181
|
+
const stlPath = path.resolve(nonEmptyText(entry.stl_path, `${label}.stl_path`));
|
|
182
|
+
if (path.extname(stlPath).toLowerCase() !== ".stl") fail(`${label}.stl_path must name an STL file.`);
|
|
183
|
+
const filament = entry.filament ?? index + 1;
|
|
184
|
+
if (typeof filament !== "number" || !Number.isInteger(filament) || filament < 1 || filament > MAX_FILAMENT) {
|
|
185
|
+
fail(`${label}.filament must be an integer from 1 to ${MAX_FILAMENT}.`);
|
|
186
|
+
}
|
|
187
|
+
const mesh = await readMesh(await fs.realpath(stlPath).catch(() => fail(`${label}.stl_path does not exist.`)), `${label}.stl_path`);
|
|
188
|
+
triangles += mesh.triangles;
|
|
189
|
+
if (triangles > MAX_TOTAL_TRIANGLES) fail(`The parts have more than ${MAX_TOTAL_TRIANGLES} triangles in total; decimate them first.`);
|
|
190
|
+
parts.push({ name, stlPath, filament, mesh });
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// One shared translation: footprint centred on the plate, lowest point on the bed.
|
|
194
|
+
const min = [0, 1, 2].map(axis => Math.min(...parts.map(part => part.mesh.min[axis])));
|
|
195
|
+
const max = [0, 1, 2].map(axis => Math.max(...parts.map(part => part.mesh.max[axis])));
|
|
196
|
+
const [centreX, centreY] = plateCentre();
|
|
197
|
+
const transform = [centreX - (min[0] + max[0]) / 2, centreY - (min[1] + max[1]) / 2, -min[2]];
|
|
198
|
+
|
|
199
|
+
const zip = new JSZip();
|
|
200
|
+
zip.file("[Content_Types].xml", CONTENT_TYPES);
|
|
201
|
+
zip.file("_rels/.rels", RELATIONSHIPS);
|
|
202
|
+
zip.file("3D/3dmodel.model", modelXml(parts, transform));
|
|
203
|
+
zip.file("Metadata/model_settings.config", modelSettingsXml(parts, path.basename(outPath, path.extname(outPath))));
|
|
204
|
+
const bytes = await zip.generateAsync({ type: "nodebuffer", compression: "DEFLATE", compressionOptions: { level: 6 } });
|
|
205
|
+
const staged = path.join(directory, `.counterpart-${randomUUID()}.3mf`);
|
|
206
|
+
try {
|
|
207
|
+
await fs.writeFile(staged, bytes, { flag: "wx" });
|
|
208
|
+
// link() publishes without replacing a file created since the check above.
|
|
209
|
+
await fs.link(staged, outPath).catch(() => fail("Cannot write out_path; it may already exist or be unwritable."));
|
|
210
|
+
} finally {
|
|
211
|
+
await fs.rm(staged, { force: true }).catch(() => {});
|
|
212
|
+
}
|
|
213
|
+
return {
|
|
214
|
+
contract: COUNTERPART_CONTRACT,
|
|
215
|
+
path: outPath,
|
|
216
|
+
objects: 1,
|
|
217
|
+
filaments: Math.max(...parts.map(part => part.filament)),
|
|
218
|
+
parts: parts.map(part => ({ name: part.name, stl_path: part.stlPath, filament: part.filament, triangles: part.mesh.triangles })),
|
|
219
|
+
};
|
|
220
|
+
}
|