bambu-printer-mcp 1.1.59 → 1.1.61
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/dist/index.js +38 -3
- package/dist/safety/print-preview.d.ts +41 -0
- package/dist/safety/print-preview.js +310 -0
- package/package.json +1 -1
- package/src/index.ts +29 -3
- package/src/safety/print-preview.ts +245 -0
package/dist/index.js
CHANGED
|
@@ -11,7 +11,7 @@ import fs from "fs";
|
|
|
11
11
|
import os from "node:os";
|
|
12
12
|
import path from "path";
|
|
13
13
|
import { createServer as createHttpServer } from "node:http";
|
|
14
|
-
import { randomUUID } from "node:crypto";
|
|
14
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
15
15
|
import { STLManipulator, SLICER_TYPES, normalizeSlicerType, SlicerRunError, } from "./stl/stl-manipulator.js";
|
|
16
16
|
import { BambuNetworkBridge, describeBambuNetworkPrintError } from "./bambu-network-bridge.js";
|
|
17
17
|
import { assertBambuNativeAvailable, bambuNativeControlsAvailable, bambuNativeUnavailableReason, interruptNativeOperations, validateBambuNativeMetadata, buildBambuNativeFanCommand, buildBambuNativeTemperatureCommand, printWithBambuNative, sendCommandWithBambuNative, uploadWithBambuNative, } from "./bambu-native.js";
|
|
@@ -23,6 +23,8 @@ import { analyze3MFAmsRequirements, analyze3MFPlateObjects, analyzeCollarCharm3M
|
|
|
23
23
|
import { BambuImplementation, assertDirectPrintSupported, checkedFile, defaultResumeStateDir } from "./printers/bambu.js";
|
|
24
24
|
import { resolveStudioPrintOptions, usedNozzleCount } from "./studio-print-options.js";
|
|
25
25
|
import { inspectPrintFile } from "./safety/print-file.js";
|
|
26
|
+
import { previewPrintFile } from "./safety/print-preview.js";
|
|
27
|
+
import { loadSafe3mfArchive } from "./safety/archive.js";
|
|
26
28
|
import { SERIAL_MODELS, externalStorageState, validatePrinterState } from "./safety/printer-state.js";
|
|
27
29
|
import { isDualNozzleModel } from "./safety/limits.js";
|
|
28
30
|
import { withPrinterOperation, withPrintSnapshot, uniquePrintName } from "./safety/artifact.js";
|
|
@@ -705,6 +707,33 @@ async function resolveTemplateSlicerProfilePath(templatePath, tempDir) {
|
|
|
705
707
|
}
|
|
706
708
|
throw new Error(`Template profile must be a .3mf, .json, or .config file: ${templatePath}`);
|
|
707
709
|
}
|
|
710
|
+
/** inspect_print_file's preview: drawn from the snapshot's own bytes, refused if they aren't the inspected ones. */
|
|
711
|
+
async function previewOfSnapshot(snapshot, plateIndex, sha256) {
|
|
712
|
+
const bytes = await fs.promises.readFile(snapshot);
|
|
713
|
+
if (createHash("sha256").update(bytes).digest("hex") !== sha256)
|
|
714
|
+
throw new Error("The file changed while it was being inspected; nothing was previewed.");
|
|
715
|
+
let gcode, projectColours;
|
|
716
|
+
if (snapshot.toLowerCase().endsWith(".3mf")) {
|
|
717
|
+
const zip = await loadSafe3mfArchive(bytes);
|
|
718
|
+
const entry = zip.file(`Metadata/plate_${plateIndex + 1}.gcode`);
|
|
719
|
+
if (!entry)
|
|
720
|
+
return undefined;
|
|
721
|
+
gcode = await entry.async("string");
|
|
722
|
+
const settings = zip.file("Metadata/project_settings.config");
|
|
723
|
+
if (settings) {
|
|
724
|
+
try {
|
|
725
|
+
const parsed = JSON.parse(await settings.async("string"));
|
|
726
|
+
if (Array.isArray(parsed?.filament_colour))
|
|
727
|
+
projectColours = parsed.filament_colour;
|
|
728
|
+
}
|
|
729
|
+
catch { /* colours fall back to the G-code header */ }
|
|
730
|
+
}
|
|
731
|
+
}
|
|
732
|
+
else
|
|
733
|
+
gcode = bytes.toString("utf8");
|
|
734
|
+
const preview = await previewPrintFile({ gcode, ...(projectColours ? { projectColours } : {}) });
|
|
735
|
+
return preview ? { ...preview, artifact_sha256: sha256, plate_index: plateIndex } : undefined;
|
|
736
|
+
}
|
|
708
737
|
function hasExplicitSlicerProfile(args) {
|
|
709
738
|
return typeof args?.slicer_profile === "string" && args.slicer_profile.trim().length > 0;
|
|
710
739
|
}
|
|
@@ -2640,6 +2669,7 @@ class BambuPrinterMCPServer {
|
|
|
2640
2669
|
plate_index: { type: "integer", minimum: 0, description: "Zero-based selected plate; defaults to 0. Raw G-code only supports 0." },
|
|
2641
2670
|
nozzle_diameters: { type: "array", minItems: 1, maxItems: 2, items: { type: "number", enum: [0.2, 0.4, 0.6, 0.8] }, description: "Optional requested nozzle diameters to compare with file declarations; this does not observe installed hardware." },
|
|
2642
2671
|
bed_type: { type: "string", enum: [...VALID_BED_TYPES], description: "Optional declared bed type to compare with file metadata." },
|
|
2672
|
+
include_preview: { type: "boolean", description: "Also return preview: PNG pictures drawn from this exact file's G-code (every extruding line in its filament's colour; the top as it sits on the bed, and the bed side turned over), with the artifact's sha256. Large (tens of KB of base64); for apps that show the person what will print, not for agents." },
|
|
2643
2673
|
},
|
|
2644
2674
|
required: ["file_path", "bambu_model"],
|
|
2645
2675
|
},
|
|
@@ -3081,9 +3111,11 @@ class BambuPrinterMCPServer {
|
|
|
3081
3111
|
let result;
|
|
3082
3112
|
switch (name) {
|
|
3083
3113
|
case "inspect_print_file": {
|
|
3084
|
-
const allowed = new Set(["file_path", "bambu_model", "plate_index", "nozzle_diameters", "bed_type"]);
|
|
3114
|
+
const allowed = new Set(["file_path", "bambu_model", "plate_index", "nozzle_diameters", "bed_type", "include_preview"]);
|
|
3085
3115
|
if (!args || Object.keys(args).some(key => !allowed.has(key)))
|
|
3086
|
-
throw new Error("inspect_print_file accepts only file/model/plate/nozzle/bed arguments.");
|
|
3116
|
+
throw new Error("inspect_print_file accepts only file/model/plate/nozzle/bed/preview arguments.");
|
|
3117
|
+
if (args.include_preview !== undefined && typeof args.include_preview !== "boolean")
|
|
3118
|
+
throw new Error("include_preview must be true or false.");
|
|
3087
3119
|
if (typeof args.file_path !== "string" || !args.file_path.trim() || args.file_path.includes("\0"))
|
|
3088
3120
|
throw new Error("file_path must name a local prepared artifact.");
|
|
3089
3121
|
if (typeof args.bambu_model !== "string" || !args.bambu_model.trim())
|
|
@@ -3105,6 +3137,8 @@ class BambuPrinterMCPServer {
|
|
|
3105
3137
|
if (extra.signal.aborted)
|
|
3106
3138
|
throw new Error("File inspection cancelled.");
|
|
3107
3139
|
const byteLength = (await fs.promises.stat(snapshot)).size;
|
|
3140
|
+
// The picture is drawn from these same snapshot bytes, so it is of exactly the file inspected.
|
|
3141
|
+
const preview = args.include_preview === true ? await previewOfSnapshot(snapshot, plateIndex, inspection.sha256) : undefined;
|
|
3108
3142
|
return {
|
|
3109
3143
|
receipt_version: "1",
|
|
3110
3144
|
evidence: "file-only",
|
|
@@ -3112,6 +3146,7 @@ class BambuPrinterMCPServer {
|
|
|
3112
3146
|
artifact: { sha256: inspection.sha256, byte_length: byteLength, file_format: path.extname(snapshot).toLowerCase() === ".3mf" ? "3mf" : "gcode" },
|
|
3113
3147
|
selection: { bambu_model: model, plate_index: plateIndex, ...(nozzles === undefined ? {} : { nozzle_diameters: nozzles }), ...(bedType === undefined ? {} : { bed_type: bedType }) },
|
|
3114
3148
|
inspection,
|
|
3149
|
+
...(preview ? { preview } : {}),
|
|
3115
3150
|
};
|
|
3116
3151
|
});
|
|
3117
3152
|
break;
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
export interface PreviewView {
|
|
2
|
+
name: "top" | "bed_side";
|
|
3
|
+
label: string;
|
|
4
|
+
png_base64: string;
|
|
5
|
+
width: number;
|
|
6
|
+
height: number;
|
|
7
|
+
}
|
|
8
|
+
export interface PrintPreview {
|
|
9
|
+
views: PreviewView[];
|
|
10
|
+
/** Millimetres per pixel in both views. */
|
|
11
|
+
mm_per_pixel: number;
|
|
12
|
+
/** The drawn area on the bed, in millimetres: [minX, minY, maxX, maxY]. */
|
|
13
|
+
extent_mm: [number, number, number, number];
|
|
14
|
+
layers: number;
|
|
15
|
+
/** Filament slots (0-based, as the G-code's T numbers) that extrude on this plate. */
|
|
16
|
+
filaments_used: number[];
|
|
17
|
+
}
|
|
18
|
+
/** RGB pixels (row-major) as a PNG. */
|
|
19
|
+
export declare function encodePng(width: number, height: number, rgb: Uint8Array): Buffer;
|
|
20
|
+
interface Segment {
|
|
21
|
+
x0: number;
|
|
22
|
+
y0: number;
|
|
23
|
+
x1: number;
|
|
24
|
+
y1: number;
|
|
25
|
+
z: number;
|
|
26
|
+
tool: number;
|
|
27
|
+
width: number;
|
|
28
|
+
}
|
|
29
|
+
/** Extruding moves of one plate's G-code, start-up purge and filament-change flushing excluded. */
|
|
30
|
+
export declare function extrusionSegments(gcode: string): {
|
|
31
|
+
segments: Segment[];
|
|
32
|
+
layers: number;
|
|
33
|
+
};
|
|
34
|
+
/** The top and bed-side pictures of one plate's G-code. `colours` are the project's filament colours by slot. */
|
|
35
|
+
export declare function renderPrintPreview(gcode: string, colours?: unknown[]): PrintPreview | undefined;
|
|
36
|
+
/** The preview of one plate of a sliced .3mf or a .gcode file, or undefined when it has no extruding moves. */
|
|
37
|
+
export declare function previewPrintFile(source: {
|
|
38
|
+
gcode: string;
|
|
39
|
+
projectColours?: unknown[];
|
|
40
|
+
}): Promise<PrintPreview | undefined>;
|
|
41
|
+
export {};
|
|
@@ -0,0 +1,310 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A picture of what the printer will lay down, drawn from the exact sliced G-code (never from a
|
|
3
|
+
* thumbnail: Bambu Studio's CLI copies a project's old plate PNGs into the sliced file unchanged).
|
|
4
|
+
* Every extruding move on the selected plate is drawn in its filament's colour, except the slicer's
|
|
5
|
+
* start-up purge and prime lines (feature "Custom") and Bambu's filament-change flushing (between
|
|
6
|
+
* M620 and M621). Features are read from Bambu Studio/Orca "; FEATURE:" and PrusaSlicer/Cura ";TYPE:"
|
|
7
|
+
* comments; G-code with neither is drawn whole. Two views: the top as it sits on the bed, and
|
|
8
|
+
* the bed side as you see it after turning the part over toward you (top to bottom), so text on
|
|
9
|
+
* that face reads as it will.
|
|
10
|
+
* Deterministic: the same bytes always give the same pictures.
|
|
11
|
+
*/
|
|
12
|
+
import { deflateSync } from "zlib";
|
|
13
|
+
const BACKGROUND = [245, 245, 247];
|
|
14
|
+
const MAX_PIXELS = 1400;
|
|
15
|
+
function parseColour(value) {
|
|
16
|
+
const match = typeof value === "string" ? /^#?([0-9a-f]{6})/i.exec(value.trim()) : null;
|
|
17
|
+
if (!match)
|
|
18
|
+
return undefined;
|
|
19
|
+
const n = parseInt(match[1], 16);
|
|
20
|
+
return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
|
|
21
|
+
}
|
|
22
|
+
const crcTable = (() => {
|
|
23
|
+
const table = new Uint32Array(256);
|
|
24
|
+
for (let n = 0; n < 256; n++) {
|
|
25
|
+
let c = n;
|
|
26
|
+
for (let k = 0; k < 8; k++)
|
|
27
|
+
c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
|
|
28
|
+
table[n] = c >>> 0;
|
|
29
|
+
}
|
|
30
|
+
return table;
|
|
31
|
+
})();
|
|
32
|
+
function crc32(bytes) {
|
|
33
|
+
let c = 0xffffffff;
|
|
34
|
+
for (const b of bytes)
|
|
35
|
+
c = crcTable[(c ^ b) & 255] ^ (c >>> 8);
|
|
36
|
+
return (c ^ 0xffffffff) >>> 0;
|
|
37
|
+
}
|
|
38
|
+
function chunk(type, data) {
|
|
39
|
+
const length = Buffer.alloc(4);
|
|
40
|
+
length.writeUInt32BE(data.length);
|
|
41
|
+
const body = Buffer.concat([Buffer.from(type, "ascii"), Buffer.from(data)]);
|
|
42
|
+
const crc = Buffer.alloc(4);
|
|
43
|
+
crc.writeUInt32BE(crc32(body));
|
|
44
|
+
return Buffer.concat([length, body, crc]);
|
|
45
|
+
}
|
|
46
|
+
/** RGB pixels (row-major) as a PNG. */
|
|
47
|
+
export function encodePng(width, height, rgb) {
|
|
48
|
+
const raw = Buffer.alloc((width * 3 + 1) * height);
|
|
49
|
+
for (let y = 0; y < height; y++) {
|
|
50
|
+
raw[y * (width * 3 + 1)] = 0;
|
|
51
|
+
Buffer.from(rgb.buffer, rgb.byteOffset + y * width * 3, width * 3).copy(raw, y * (width * 3 + 1) + 1);
|
|
52
|
+
}
|
|
53
|
+
const header = Buffer.alloc(13);
|
|
54
|
+
header.writeUInt32BE(width, 0);
|
|
55
|
+
header.writeUInt32BE(height, 4);
|
|
56
|
+
header[8] = 8;
|
|
57
|
+
header[9] = 2;
|
|
58
|
+
header[10] = 0;
|
|
59
|
+
header[11] = 0;
|
|
60
|
+
header[12] = 0;
|
|
61
|
+
return Buffer.concat([Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), chunk("IHDR", header), chunk("IDAT", deflateSync(raw, { level: 9 })), chunk("IEND", new Uint8Array())]);
|
|
62
|
+
}
|
|
63
|
+
/** Extruding moves of one plate's G-code, start-up purge and filament-change flushing excluded. */
|
|
64
|
+
export function extrusionSegments(gcode) {
|
|
65
|
+
const marked = [], unmarked = [];
|
|
66
|
+
let x = 0, y = 0, z = 0, e = 0, absoluteXY = true, relativeE = false, tool = 0, feature = "", layers = 0, width = 0.42;
|
|
67
|
+
let sawFeature = false, changingFilament = false;
|
|
68
|
+
const lines = gcode.split(/\r\n|\n|\r/);
|
|
69
|
+
for (const raw of lines) {
|
|
70
|
+
const comment = raw.indexOf(";");
|
|
71
|
+
if (comment >= 0) {
|
|
72
|
+
const note = raw.slice(comment + 1).trim();
|
|
73
|
+
const featureMatch = /^(?:FEATURE|TYPE)\s*:\s*(.*)$/i.exec(note);
|
|
74
|
+
if (featureMatch) {
|
|
75
|
+
feature = featureMatch[1].trim().toLowerCase();
|
|
76
|
+
sawFeature = true;
|
|
77
|
+
}
|
|
78
|
+
else if (/^(CHANGE_LAYER|LAYER_CHANGE)$/i.test(note))
|
|
79
|
+
layers++;
|
|
80
|
+
else {
|
|
81
|
+
const w = /^(?:LINE_WIDTH|WIDTH)\s*:\s*([\d.]+)/i.exec(note);
|
|
82
|
+
if (w && Number(w[1]) > 0 && Number(w[1]) < 5)
|
|
83
|
+
width = Number(w[1]);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
// The syntax file inspection accepts (print-file.ts): optional line number and checksum, a command word that
|
|
87
|
+
// may be zero-padded (G01) or touch its first parameter (G1X20), and parameters with or without spaces or a + sign.
|
|
88
|
+
const line = (comment >= 0 ? raw.slice(0, comment) : raw).trim().toUpperCase().replace(/^N\d+\s*/, "").replace(/\*\d+\s*$/, "");
|
|
89
|
+
if (!line)
|
|
90
|
+
continue;
|
|
91
|
+
const command = /^([GMT])(\d+(?:\.\d+)?)/.exec(line);
|
|
92
|
+
if (!command)
|
|
93
|
+
continue;
|
|
94
|
+
const word = command[1] + String(Number(command[2].split(".")[0])) + (command[2].includes(".") ? "." + command[2].split(".")[1] : "");
|
|
95
|
+
const words = parameterWords(line.slice(command[0].length));
|
|
96
|
+
if (command[1] === "T") {
|
|
97
|
+
const t = Number(command[2]);
|
|
98
|
+
if (Number.isInteger(t) && t < 255)
|
|
99
|
+
tool = t;
|
|
100
|
+
continue;
|
|
101
|
+
}
|
|
102
|
+
// Bambu's AMS filament change (cut, retract, flush into the chute) runs from M620 S<slot> to M621 S<slot>: not
|
|
103
|
+
// the part. Other M620 forms (the H2C start template's M620 O1) are setup, as file inspection reads them too.
|
|
104
|
+
if (word === "M620") {
|
|
105
|
+
if (words.has("S"))
|
|
106
|
+
changingFilament = true;
|
|
107
|
+
continue;
|
|
108
|
+
}
|
|
109
|
+
if (word === "M621") {
|
|
110
|
+
if (words.has("S"))
|
|
111
|
+
changingFilament = false;
|
|
112
|
+
continue;
|
|
113
|
+
}
|
|
114
|
+
if (word === "G90") {
|
|
115
|
+
absoluteXY = true;
|
|
116
|
+
continue;
|
|
117
|
+
}
|
|
118
|
+
if (word === "G91") {
|
|
119
|
+
absoluteXY = false;
|
|
120
|
+
continue;
|
|
121
|
+
}
|
|
122
|
+
if (word === "M82") {
|
|
123
|
+
relativeE = false;
|
|
124
|
+
continue;
|
|
125
|
+
}
|
|
126
|
+
if (word === "M83") {
|
|
127
|
+
relativeE = true;
|
|
128
|
+
continue;
|
|
129
|
+
}
|
|
130
|
+
if (word === "G92") {
|
|
131
|
+
const reset = words.get("E");
|
|
132
|
+
if (reset !== undefined)
|
|
133
|
+
e = reset;
|
|
134
|
+
continue;
|
|
135
|
+
}
|
|
136
|
+
if (word !== "G0" && word !== "G1" && word !== "G2" && word !== "G3")
|
|
137
|
+
continue;
|
|
138
|
+
const value = (axis) => words.get(axis);
|
|
139
|
+
const nx = value("X"), ny = value("Y"), nz = value("Z"), ne = value("E");
|
|
140
|
+
const tx = nx === undefined ? x : absoluteXY ? nx : x + nx;
|
|
141
|
+
const ty = ny === undefined ? y : absoluteXY ? ny : y + ny;
|
|
142
|
+
if (nz !== undefined)
|
|
143
|
+
z = absoluteXY ? nz : z + nz;
|
|
144
|
+
let extruding = false;
|
|
145
|
+
if (ne !== undefined) {
|
|
146
|
+
const delta = relativeE ? ne : ne - e;
|
|
147
|
+
e = relativeE ? e + ne : ne;
|
|
148
|
+
extruding = delta > 0 && word !== "G0";
|
|
149
|
+
}
|
|
150
|
+
const arc = word === "G2" || word === "G3";
|
|
151
|
+
const centre = arc ? arcCentre(x, y, tx, ty, word === "G2", value("I"), value("J"), value("R")) : undefined;
|
|
152
|
+
const segments = feature ? marked : unmarked;
|
|
153
|
+
if (extruding && !changingFilament && feature !== "custom" && (tx !== x || ty !== y || centre)) {
|
|
154
|
+
if (centre) {
|
|
155
|
+
// Arc about its centre, swept clockwise (G2) or counter-clockwise (G3); the same end point is a full circle.
|
|
156
|
+
const [cx, cy] = centre;
|
|
157
|
+
const r = Math.hypot(x - cx, y - cy);
|
|
158
|
+
let a0 = Math.atan2(y - cy, x - cx), a1 = Math.atan2(ty - cy, tx - cx);
|
|
159
|
+
if (word === "G2") {
|
|
160
|
+
while (a1 >= a0)
|
|
161
|
+
a1 -= 2 * Math.PI;
|
|
162
|
+
}
|
|
163
|
+
else {
|
|
164
|
+
while (a1 <= a0)
|
|
165
|
+
a1 += 2 * Math.PI;
|
|
166
|
+
}
|
|
167
|
+
const steps = Math.max(2, Math.ceil(Math.abs(a1 - a0) * r / 0.2));
|
|
168
|
+
let px = x, py = y;
|
|
169
|
+
for (let i = 1; i <= steps; i++) {
|
|
170
|
+
const a = a0 + (a1 - a0) * i / steps;
|
|
171
|
+
const qx = i === steps ? tx : cx + r * Math.cos(a), qy = i === steps ? ty : cy + r * Math.sin(a);
|
|
172
|
+
segments.push({ x0: px, y0: py, x1: qx, y1: qy, z, tool, width });
|
|
173
|
+
px = qx;
|
|
174
|
+
py = qy;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
else
|
|
178
|
+
segments.push({ x0: x, y0: y, x1: tx, y1: ty, z, tool, width });
|
|
179
|
+
}
|
|
180
|
+
x = tx;
|
|
181
|
+
y = ty;
|
|
182
|
+
}
|
|
183
|
+
// G-code that names no features at all is drawn whole rather than not at all.
|
|
184
|
+
return { segments: sawFeature ? marked : unmarked, layers };
|
|
185
|
+
}
|
|
186
|
+
/** A command's parameters, as file inspection reads them: letter then number, spaces and a + sign optional. */
|
|
187
|
+
function parameterWords(text) {
|
|
188
|
+
const words = new Map();
|
|
189
|
+
let rest = text.trim();
|
|
190
|
+
while (rest) {
|
|
191
|
+
const token = /^([A-Z])\s*([+-]?(?:\d+(?:\.\d*)?|\.\d+))?/.exec(rest);
|
|
192
|
+
if (!token)
|
|
193
|
+
break;
|
|
194
|
+
if (token[2] !== undefined && !words.has(token[1]))
|
|
195
|
+
words.set(token[1], Number(token[2]));
|
|
196
|
+
rest = rest.slice(token[0].length).trimStart();
|
|
197
|
+
}
|
|
198
|
+
return words;
|
|
199
|
+
}
|
|
200
|
+
/** An arc's centre from I/J (offsets from the start) or R (radius; negative takes the longer way round). */
|
|
201
|
+
function arcCentre(x, y, tx, ty, clockwise, i, j, r) {
|
|
202
|
+
if (i !== undefined || j !== undefined)
|
|
203
|
+
return [x + (i ?? 0), y + (j ?? 0)];
|
|
204
|
+
if (r === undefined || r === 0 || (tx === x && ty === y))
|
|
205
|
+
return undefined;
|
|
206
|
+
const dx = tx - x, dy = ty - y, chord = Math.hypot(dx, dy);
|
|
207
|
+
if (chord > 2 * Math.abs(r) + 1e-9)
|
|
208
|
+
return undefined;
|
|
209
|
+
const h = Math.sqrt(Math.max(0, r * r - (chord / 2) ** 2));
|
|
210
|
+
const mx = (x + tx) / 2, my = (y + ty) / 2;
|
|
211
|
+
// Which side of the chord the centre lies on: clockwise short arcs keep it to the right of the travel.
|
|
212
|
+
const side = (clockwise ? -1 : 1) * (r > 0 ? 1 : -1);
|
|
213
|
+
return [mx - side * h * dy / chord, my + side * h * dx / chord];
|
|
214
|
+
}
|
|
215
|
+
/** The top and bed-side pictures of one plate's G-code. `colours` are the project's filament colours by slot. */
|
|
216
|
+
export function renderPrintPreview(gcode, colours = []) {
|
|
217
|
+
const { segments, layers } = extrusionSegments(gcode);
|
|
218
|
+
if (!segments.length)
|
|
219
|
+
return undefined;
|
|
220
|
+
let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity, minZ = Infinity, maxZ = -Infinity;
|
|
221
|
+
for (const s of segments) {
|
|
222
|
+
minX = Math.min(minX, s.x0, s.x1);
|
|
223
|
+
maxX = Math.max(maxX, s.x0, s.x1);
|
|
224
|
+
minY = Math.min(minY, s.y0, s.y1);
|
|
225
|
+
maxY = Math.max(maxY, s.y0, s.y1);
|
|
226
|
+
minZ = Math.min(minZ, s.z);
|
|
227
|
+
maxZ = Math.max(maxZ, s.z);
|
|
228
|
+
}
|
|
229
|
+
const margin = 2;
|
|
230
|
+
minX -= margin;
|
|
231
|
+
minY -= margin;
|
|
232
|
+
maxX += margin;
|
|
233
|
+
maxY += margin;
|
|
234
|
+
const span = Math.max(maxX - minX, maxY - minY);
|
|
235
|
+
// Fine enough for 0.3 mm ruler ticks (at least 4 px/mm) whenever the plate's drawn area allows.
|
|
236
|
+
const ppm = Math.min(8, Math.max(1, MAX_PIXELS / span));
|
|
237
|
+
const width = Math.max(1, Math.ceil((maxX - minX) * ppm)), height = Math.max(1, Math.ceil((maxY - minY) * ppm));
|
|
238
|
+
const palette = (tool) => parseColour(colours[tool]) ?? [40, 40, 40];
|
|
239
|
+
const used = new Set();
|
|
240
|
+
const draw = (top) => {
|
|
241
|
+
const depth = new Float64Array(width * height).fill(top ? -Infinity : Infinity);
|
|
242
|
+
const toolAt = new Int16Array(width * height).fill(-1);
|
|
243
|
+
for (const s of segments) {
|
|
244
|
+
used.add(s.tool);
|
|
245
|
+
const ax = (s.x0 - minX) * ppm, ay = (maxY - s.y0) * ppm, bx = (s.x1 - minX) * ppm, by = (maxY - s.y1) * ppm;
|
|
246
|
+
// Each line at its extrusion width, so a surface's lines meet as they do on the part.
|
|
247
|
+
const radius = Math.max(0.5, s.width * ppm / 2), r2 = radius * radius, reach = Math.ceil(radius);
|
|
248
|
+
const steps = Math.max(1, Math.ceil(Math.hypot(bx - ax, by - ay) / Math.max(0.5, radius / 2)));
|
|
249
|
+
for (let i = 0; i <= steps; i++) {
|
|
250
|
+
const cx = ax + (bx - ax) * i / steps, cy = ay + (by - ay) * i / steps;
|
|
251
|
+
for (let dy = -reach; dy <= reach; dy++)
|
|
252
|
+
for (let dx = -reach; dx <= reach; dx++) {
|
|
253
|
+
if (dx * dx + dy * dy > r2)
|
|
254
|
+
continue;
|
|
255
|
+
const px = Math.floor(cx + dx), py = Math.floor(cy + dy);
|
|
256
|
+
if (px < 0 || py < 0 || px >= width || py >= height)
|
|
257
|
+
continue;
|
|
258
|
+
const k = py * width + px;
|
|
259
|
+
if (top ? s.z >= depth[k] : s.z <= depth[k]) {
|
|
260
|
+
depth[k] = s.z;
|
|
261
|
+
toolAt[k] = s.tool;
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
const rgb = new Uint8Array(width * height * 3);
|
|
267
|
+
const zRange = Math.max(1e-6, maxZ - minZ);
|
|
268
|
+
for (let py = 0; py < height; py++)
|
|
269
|
+
for (let px = 0; px < width; px++) {
|
|
270
|
+
// The bed side is the part turned over top to bottom, so its text reads as it will on the part.
|
|
271
|
+
const sy = top ? py : height - 1 - py;
|
|
272
|
+
const k = sy * width + px, o = (py * width + px) * 3, t = toolAt[k];
|
|
273
|
+
if (t < 0) {
|
|
274
|
+
rgb[o] = BACKGROUND[0];
|
|
275
|
+
rgb[o + 1] = BACKGROUND[1];
|
|
276
|
+
rgb[o + 2] = BACKGROUND[2];
|
|
277
|
+
continue;
|
|
278
|
+
}
|
|
279
|
+
const [r, g, b] = palette(t);
|
|
280
|
+
// Height shading, toward white so it shows on dark filament too: on the top view the highest
|
|
281
|
+
// lines (raised tabs, top surfaces) are lightest; on the bed side the face on the bed is.
|
|
282
|
+
const h = (depth[k] - minZ) / zRange, lift = 0.4 * (top ? h : 1 - h);
|
|
283
|
+
rgb[o] = Math.round(r + (255 - r) * lift);
|
|
284
|
+
rgb[o + 1] = Math.round(g + (255 - g) * lift);
|
|
285
|
+
rgb[o + 2] = Math.round(b + (255 - b) * lift);
|
|
286
|
+
}
|
|
287
|
+
return encodePng(width, height, rgb).toString("base64");
|
|
288
|
+
};
|
|
289
|
+
const top = draw(true), bed = draw(false);
|
|
290
|
+
return {
|
|
291
|
+
views: [
|
|
292
|
+
{ name: "top", label: "Top, as it sits on the bed", png_base64: top, width, height },
|
|
293
|
+
{ name: "bed_side", label: "Bed side, turned over toward you", png_base64: bed, width, height },
|
|
294
|
+
],
|
|
295
|
+
mm_per_pixel: Math.round(1e6 / ppm) / 1e6,
|
|
296
|
+
extent_mm: [minX, minY, maxX, maxY].map(v => Math.round(v * 100) / 100),
|
|
297
|
+
layers,
|
|
298
|
+
filaments_used: [...used].sort((a, b) => a - b),
|
|
299
|
+
};
|
|
300
|
+
}
|
|
301
|
+
/** The preview of one plate of a sliced .3mf or a .gcode file, or undefined when it has no extruding moves. */
|
|
302
|
+
export async function previewPrintFile(source) {
|
|
303
|
+
let colours = source.projectColours;
|
|
304
|
+
if (!colours?.length) {
|
|
305
|
+
// A bare .gcode file carries its colours in its header: "; filament_colour = #000000;#FFFFFF".
|
|
306
|
+
const header = /^\s*;\s*filament_colou?r\s*[=:]\s*(.+)$/im.exec(source.gcode);
|
|
307
|
+
colours = header ? header[1].split(/[;,]/).map(v => v.trim()) : [];
|
|
308
|
+
}
|
|
309
|
+
return renderPrintPreview(source.gcode, colours);
|
|
310
|
+
}
|
package/package.json
CHANGED
package/src/index.ts
CHANGED
|
@@ -21,7 +21,7 @@ import fs from "fs";
|
|
|
21
21
|
import os from "node:os";
|
|
22
22
|
import path from "path";
|
|
23
23
|
import { createServer as createHttpServer, type IncomingMessage, type Server as HttpServer, type ServerResponse } from "node:http";
|
|
24
|
-
import { randomUUID } from "node:crypto";
|
|
24
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
25
25
|
import {
|
|
26
26
|
STLManipulator,
|
|
27
27
|
SLICER_TYPES,
|
|
@@ -53,6 +53,8 @@ import type { ThreeMFAmsRequirements } from "./types.js";
|
|
|
53
53
|
import { BambuImplementation, assertDirectPrintSupported, checkedFile, defaultResumeStateDir } from "./printers/bambu.js";
|
|
54
54
|
import { resolveStudioPrintOptions, usedNozzleCount, type CallerPrintOptions } from "./studio-print-options.js";
|
|
55
55
|
import { inspectPrintFile } from "./safety/print-file.js";
|
|
56
|
+
import { previewPrintFile } from "./safety/print-preview.js";
|
|
57
|
+
import { loadSafe3mfArchive } from "./safety/archive.js";
|
|
56
58
|
import { SERIAL_MODELS, externalStorageState, validatePrinterState } from "./safety/printer-state.js";
|
|
57
59
|
import { isDualNozzleModel } from "./safety/limits.js";
|
|
58
60
|
import { withPrinterOperation, withPrintSnapshot, uniquePrintName } from "./safety/artifact.js";
|
|
@@ -916,6 +918,25 @@ async function resolveTemplateSlicerProfilePath(
|
|
|
916
918
|
throw new Error(`Template profile must be a .3mf, .json, or .config file: ${templatePath}`);
|
|
917
919
|
}
|
|
918
920
|
|
|
921
|
+
/** inspect_print_file's preview: drawn from the snapshot's own bytes, refused if they aren't the inspected ones. */
|
|
922
|
+
async function previewOfSnapshot(snapshot: string, plateIndex: number, sha256: string) {
|
|
923
|
+
const bytes = await fs.promises.readFile(snapshot);
|
|
924
|
+
if (createHash("sha256").update(bytes).digest("hex") !== sha256) throw new Error("The file changed while it was being inspected; nothing was previewed.");
|
|
925
|
+
let gcode: string, projectColours: unknown[] | undefined;
|
|
926
|
+
if (snapshot.toLowerCase().endsWith(".3mf")) {
|
|
927
|
+
const zip = await loadSafe3mfArchive(bytes);
|
|
928
|
+
const entry = zip.file(`Metadata/plate_${plateIndex + 1}.gcode`);
|
|
929
|
+
if (!entry) return undefined;
|
|
930
|
+
gcode = await entry.async("string");
|
|
931
|
+
const settings = zip.file("Metadata/project_settings.config");
|
|
932
|
+
if (settings) {
|
|
933
|
+
try { const parsed = JSON.parse(await settings.async("string")); if (Array.isArray(parsed?.filament_colour)) projectColours = parsed.filament_colour; } catch { /* colours fall back to the G-code header */ }
|
|
934
|
+
}
|
|
935
|
+
} else gcode = bytes.toString("utf8");
|
|
936
|
+
const preview = await previewPrintFile({ gcode, ...(projectColours ? { projectColours } : {}) });
|
|
937
|
+
return preview ? { ...preview, artifact_sha256: sha256, plate_index: plateIndex } : undefined;
|
|
938
|
+
}
|
|
939
|
+
|
|
919
940
|
function hasExplicitSlicerProfile(args: any): boolean {
|
|
920
941
|
return typeof args?.slicer_profile === "string" && args.slicer_profile.trim().length > 0;
|
|
921
942
|
}
|
|
@@ -3175,6 +3196,7 @@ class BambuPrinterMCPServer {
|
|
|
3175
3196
|
plate_index: { type: "integer", minimum: 0, description: "Zero-based selected plate; defaults to 0. Raw G-code only supports 0." },
|
|
3176
3197
|
nozzle_diameters: { type: "array", minItems: 1, maxItems: 2, items: { type: "number", enum: [0.2, 0.4, 0.6, 0.8] }, description: "Optional requested nozzle diameters to compare with file declarations; this does not observe installed hardware." },
|
|
3177
3198
|
bed_type: { type: "string", enum: [...VALID_BED_TYPES], description: "Optional declared bed type to compare with file metadata." },
|
|
3199
|
+
include_preview: { type: "boolean", description: "Also return preview: PNG pictures drawn from this exact file's G-code (every extruding line in its filament's colour; the top as it sits on the bed, and the bed side turned over), with the artifact's sha256. Large (tens of KB of base64); for apps that show the person what will print, not for agents." },
|
|
3178
3200
|
},
|
|
3179
3201
|
required: ["file_path", "bambu_model"],
|
|
3180
3202
|
},
|
|
@@ -3626,8 +3648,9 @@ class BambuPrinterMCPServer {
|
|
|
3626
3648
|
|
|
3627
3649
|
switch (name) {
|
|
3628
3650
|
case "inspect_print_file": {
|
|
3629
|
-
const allowed = new Set(["file_path", "bambu_model", "plate_index", "nozzle_diameters", "bed_type"]);
|
|
3630
|
-
if (!args || Object.keys(args).some(key => !allowed.has(key))) throw new Error("inspect_print_file accepts only file/model/plate/nozzle/bed arguments.");
|
|
3651
|
+
const allowed = new Set(["file_path", "bambu_model", "plate_index", "nozzle_diameters", "bed_type", "include_preview"]);
|
|
3652
|
+
if (!args || Object.keys(args).some(key => !allowed.has(key))) throw new Error("inspect_print_file accepts only file/model/plate/nozzle/bed/preview arguments.");
|
|
3653
|
+
if (args.include_preview !== undefined && typeof args.include_preview !== "boolean") throw new Error("include_preview must be true or false.");
|
|
3631
3654
|
if (typeof args.file_path !== "string" || !args.file_path.trim() || args.file_path.includes("\0")) throw new Error("file_path must name a local prepared artifact.");
|
|
3632
3655
|
if (typeof args.bambu_model !== "string" || !args.bambu_model.trim()) throw new Error("An explicit bambu_model is required for file inspection.");
|
|
3633
3656
|
const model = validateBambuModel(args.bambu_model);
|
|
@@ -3642,6 +3665,8 @@ class BambuPrinterMCPServer {
|
|
|
3642
3665
|
const inspection = await inspectPrintFile(snapshot, { model, nozzleDiameters: nozzles, plateIndex, bedType });
|
|
3643
3666
|
if (extra.signal.aborted) throw new Error("File inspection cancelled.");
|
|
3644
3667
|
const byteLength = (await fs.promises.stat(snapshot)).size;
|
|
3668
|
+
// The picture is drawn from these same snapshot bytes, so it is of exactly the file inspected.
|
|
3669
|
+
const preview = args.include_preview === true ? await previewOfSnapshot(snapshot, plateIndex, inspection.sha256) : undefined;
|
|
3645
3670
|
return {
|
|
3646
3671
|
receipt_version: "1",
|
|
3647
3672
|
evidence: "file-only",
|
|
@@ -3649,6 +3674,7 @@ class BambuPrinterMCPServer {
|
|
|
3649
3674
|
artifact: { sha256: inspection.sha256, byte_length: byteLength, file_format: path.extname(snapshot).toLowerCase() === ".3mf" ? "3mf" : "gcode" },
|
|
3650
3675
|
selection: { bambu_model: model, plate_index: plateIndex, ...(nozzles === undefined ? {} : { nozzle_diameters: nozzles }), ...(bedType === undefined ? {} : { bed_type: bedType }) },
|
|
3651
3676
|
inspection,
|
|
3677
|
+
...(preview ? { preview } : {}),
|
|
3652
3678
|
};
|
|
3653
3679
|
});
|
|
3654
3680
|
break;
|
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A picture of what the printer will lay down, drawn from the exact sliced G-code (never from a
|
|
3
|
+
* thumbnail: Bambu Studio's CLI copies a project's old plate PNGs into the sliced file unchanged).
|
|
4
|
+
* Every extruding move on the selected plate is drawn in its filament's colour, except the slicer's
|
|
5
|
+
* start-up purge and prime lines (feature "Custom") and Bambu's filament-change flushing (between
|
|
6
|
+
* M620 and M621). Features are read from Bambu Studio/Orca "; FEATURE:" and PrusaSlicer/Cura ";TYPE:"
|
|
7
|
+
* comments; G-code with neither is drawn whole. Two views: the top as it sits on the bed, and
|
|
8
|
+
* the bed side as you see it after turning the part over toward you (top to bottom), so text on
|
|
9
|
+
* that face reads as it will.
|
|
10
|
+
* Deterministic: the same bytes always give the same pictures.
|
|
11
|
+
*/
|
|
12
|
+
import { deflateSync } from "zlib";
|
|
13
|
+
|
|
14
|
+
export interface PreviewView { name: "top" | "bed_side"; label: string; png_base64: string; width: number; height: number }
|
|
15
|
+
export interface PrintPreview {
|
|
16
|
+
views: PreviewView[];
|
|
17
|
+
/** Millimetres per pixel in both views. */
|
|
18
|
+
mm_per_pixel: number;
|
|
19
|
+
/** The drawn area on the bed, in millimetres: [minX, minY, maxX, maxY]. */
|
|
20
|
+
extent_mm: [number, number, number, number];
|
|
21
|
+
layers: number;
|
|
22
|
+
/** Filament slots (0-based, as the G-code's T numbers) that extrude on this plate. */
|
|
23
|
+
filaments_used: number[];
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const BACKGROUND = [245, 245, 247];
|
|
27
|
+
const MAX_PIXELS = 1400;
|
|
28
|
+
|
|
29
|
+
function parseColour(value: unknown): [number, number, number] | undefined {
|
|
30
|
+
const match = typeof value === "string" ? /^#?([0-9a-f]{6})/i.exec(value.trim()) : null;
|
|
31
|
+
if (!match) return undefined;
|
|
32
|
+
const n = parseInt(match[1], 16);
|
|
33
|
+
return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const crcTable = (() => {
|
|
37
|
+
const table = new Uint32Array(256);
|
|
38
|
+
for (let n = 0; n < 256; n++) {
|
|
39
|
+
let c = n;
|
|
40
|
+
for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
|
|
41
|
+
table[n] = c >>> 0;
|
|
42
|
+
}
|
|
43
|
+
return table;
|
|
44
|
+
})();
|
|
45
|
+
function crc32(bytes: Uint8Array): number {
|
|
46
|
+
let c = 0xffffffff;
|
|
47
|
+
for (const b of bytes) c = crcTable[(c ^ b) & 255] ^ (c >>> 8);
|
|
48
|
+
return (c ^ 0xffffffff) >>> 0;
|
|
49
|
+
}
|
|
50
|
+
function chunk(type: string, data: Uint8Array): Buffer {
|
|
51
|
+
const length = Buffer.alloc(4); length.writeUInt32BE(data.length);
|
|
52
|
+
const body = Buffer.concat([Buffer.from(type, "ascii"), Buffer.from(data)]);
|
|
53
|
+
const crc = Buffer.alloc(4); crc.writeUInt32BE(crc32(body));
|
|
54
|
+
return Buffer.concat([length, body, crc]);
|
|
55
|
+
}
|
|
56
|
+
/** RGB pixels (row-major) as a PNG. */
|
|
57
|
+
export function encodePng(width: number, height: number, rgb: Uint8Array): Buffer {
|
|
58
|
+
const raw = Buffer.alloc((width * 3 + 1) * height);
|
|
59
|
+
for (let y = 0; y < height; y++) {
|
|
60
|
+
raw[y * (width * 3 + 1)] = 0;
|
|
61
|
+
Buffer.from(rgb.buffer, rgb.byteOffset + y * width * 3, width * 3).copy(raw, y * (width * 3 + 1) + 1);
|
|
62
|
+
}
|
|
63
|
+
const header = Buffer.alloc(13);
|
|
64
|
+
header.writeUInt32BE(width, 0); header.writeUInt32BE(height, 4);
|
|
65
|
+
header[8] = 8; header[9] = 2; header[10] = 0; header[11] = 0; header[12] = 0;
|
|
66
|
+
return Buffer.concat([Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), chunk("IHDR", header), chunk("IDAT", deflateSync(raw, { level: 9 })), chunk("IEND", new Uint8Array())]);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
interface Segment { x0: number; y0: number; x1: number; y1: number; z: number; tool: number; width: number }
|
|
70
|
+
|
|
71
|
+
/** Extruding moves of one plate's G-code, start-up purge and filament-change flushing excluded. */
|
|
72
|
+
export function extrusionSegments(gcode: string): { segments: Segment[]; layers: number } {
|
|
73
|
+
const marked: Segment[] = [], unmarked: Segment[] = [];
|
|
74
|
+
let x = 0, y = 0, z = 0, e = 0, absoluteXY = true, relativeE = false, tool = 0, feature = "", layers = 0, width = 0.42;
|
|
75
|
+
let sawFeature = false, changingFilament = false;
|
|
76
|
+
const lines = gcode.split(/\r\n|\n|\r/);
|
|
77
|
+
for (const raw of lines) {
|
|
78
|
+
const comment = raw.indexOf(";");
|
|
79
|
+
if (comment >= 0) {
|
|
80
|
+
const note = raw.slice(comment + 1).trim();
|
|
81
|
+
const featureMatch = /^(?:FEATURE|TYPE)\s*:\s*(.*)$/i.exec(note);
|
|
82
|
+
if (featureMatch) { feature = featureMatch[1].trim().toLowerCase(); sawFeature = true; }
|
|
83
|
+
else if (/^(CHANGE_LAYER|LAYER_CHANGE)$/i.test(note)) layers++;
|
|
84
|
+
else { const w = /^(?:LINE_WIDTH|WIDTH)\s*:\s*([\d.]+)/i.exec(note); if (w && Number(w[1]) > 0 && Number(w[1]) < 5) width = Number(w[1]); }
|
|
85
|
+
}
|
|
86
|
+
// The syntax file inspection accepts (print-file.ts): optional line number and checksum, a command word that
|
|
87
|
+
// may be zero-padded (G01) or touch its first parameter (G1X20), and parameters with or without spaces or a + sign.
|
|
88
|
+
const line = (comment >= 0 ? raw.slice(0, comment) : raw).trim().toUpperCase().replace(/^N\d+\s*/, "").replace(/\*\d+\s*$/, "");
|
|
89
|
+
if (!line) continue;
|
|
90
|
+
const command = /^([GMT])(\d+(?:\.\d+)?)/.exec(line);
|
|
91
|
+
if (!command) continue;
|
|
92
|
+
const word = command[1] + String(Number(command[2].split(".")[0])) + (command[2].includes(".") ? "." + command[2].split(".")[1] : "");
|
|
93
|
+
const words = parameterWords(line.slice(command[0].length));
|
|
94
|
+
if (command[1] === "T") { const t = Number(command[2]); if (Number.isInteger(t) && t < 255) tool = t; continue; }
|
|
95
|
+
// Bambu's AMS filament change (cut, retract, flush into the chute) runs from M620 S<slot> to M621 S<slot>: not
|
|
96
|
+
// the part. Other M620 forms (the H2C start template's M620 O1) are setup, as file inspection reads them too.
|
|
97
|
+
if (word === "M620") { if (words.has("S")) changingFilament = true; continue; }
|
|
98
|
+
if (word === "M621") { if (words.has("S")) changingFilament = false; continue; }
|
|
99
|
+
if (word === "G90") { absoluteXY = true; continue; }
|
|
100
|
+
if (word === "G91") { absoluteXY = false; continue; }
|
|
101
|
+
if (word === "M82") { relativeE = false; continue; }
|
|
102
|
+
if (word === "M83") { relativeE = true; continue; }
|
|
103
|
+
if (word === "G92") { const reset = words.get("E"); if (reset !== undefined) e = reset; continue; }
|
|
104
|
+
if (word !== "G0" && word !== "G1" && word !== "G2" && word !== "G3") continue;
|
|
105
|
+
const value = (axis: string) => words.get(axis);
|
|
106
|
+
const nx = value("X"), ny = value("Y"), nz = value("Z"), ne = value("E");
|
|
107
|
+
const tx = nx === undefined ? x : absoluteXY ? nx : x + nx;
|
|
108
|
+
const ty = ny === undefined ? y : absoluteXY ? ny : y + ny;
|
|
109
|
+
if (nz !== undefined) z = absoluteXY ? nz : z + nz;
|
|
110
|
+
let extruding = false;
|
|
111
|
+
if (ne !== undefined) {
|
|
112
|
+
const delta = relativeE ? ne : ne - e;
|
|
113
|
+
e = relativeE ? e + ne : ne;
|
|
114
|
+
extruding = delta > 0 && word !== "G0";
|
|
115
|
+
}
|
|
116
|
+
const arc = word === "G2" || word === "G3";
|
|
117
|
+
const centre = arc ? arcCentre(x, y, tx, ty, word === "G2", value("I"), value("J"), value("R")) : undefined;
|
|
118
|
+
const segments = feature ? marked : unmarked;
|
|
119
|
+
if (extruding && !changingFilament && feature !== "custom" && (tx !== x || ty !== y || centre)) {
|
|
120
|
+
if (centre) {
|
|
121
|
+
// Arc about its centre, swept clockwise (G2) or counter-clockwise (G3); the same end point is a full circle.
|
|
122
|
+
const [cx, cy] = centre;
|
|
123
|
+
const r = Math.hypot(x - cx, y - cy);
|
|
124
|
+
let a0 = Math.atan2(y - cy, x - cx), a1 = Math.atan2(ty - cy, tx - cx);
|
|
125
|
+
if (word === "G2") { while (a1 >= a0) a1 -= 2 * Math.PI; } else { while (a1 <= a0) a1 += 2 * Math.PI; }
|
|
126
|
+
const steps = Math.max(2, Math.ceil(Math.abs(a1 - a0) * r / 0.2));
|
|
127
|
+
let px = x, py = y;
|
|
128
|
+
for (let i = 1; i <= steps; i++) {
|
|
129
|
+
const a = a0 + (a1 - a0) * i / steps;
|
|
130
|
+
const qx = i === steps ? tx : cx + r * Math.cos(a), qy = i === steps ? ty : cy + r * Math.sin(a);
|
|
131
|
+
segments.push({ x0: px, y0: py, x1: qx, y1: qy, z, tool, width });
|
|
132
|
+
px = qx; py = qy;
|
|
133
|
+
}
|
|
134
|
+
} else segments.push({ x0: x, y0: y, x1: tx, y1: ty, z, tool, width });
|
|
135
|
+
}
|
|
136
|
+
x = tx; y = ty;
|
|
137
|
+
}
|
|
138
|
+
// G-code that names no features at all is drawn whole rather than not at all.
|
|
139
|
+
return { segments: sawFeature ? marked : unmarked, layers };
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** A command's parameters, as file inspection reads them: letter then number, spaces and a + sign optional. */
|
|
143
|
+
function parameterWords(text: string): Map<string, number> {
|
|
144
|
+
const words = new Map<string, number>();
|
|
145
|
+
let rest = text.trim();
|
|
146
|
+
while (rest) {
|
|
147
|
+
const token = /^([A-Z])\s*([+-]?(?:\d+(?:\.\d*)?|\.\d+))?/.exec(rest);
|
|
148
|
+
if (!token) break;
|
|
149
|
+
if (token[2] !== undefined && !words.has(token[1])) words.set(token[1], Number(token[2]));
|
|
150
|
+
rest = rest.slice(token[0].length).trimStart();
|
|
151
|
+
}
|
|
152
|
+
return words;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** An arc's centre from I/J (offsets from the start) or R (radius; negative takes the longer way round). */
|
|
156
|
+
function arcCentre(x: number, y: number, tx: number, ty: number, clockwise: boolean, i?: number, j?: number, r?: number): [number, number] | undefined {
|
|
157
|
+
if (i !== undefined || j !== undefined) return [x + (i ?? 0), y + (j ?? 0)];
|
|
158
|
+
if (r === undefined || r === 0 || (tx === x && ty === y)) return undefined;
|
|
159
|
+
const dx = tx - x, dy = ty - y, chord = Math.hypot(dx, dy);
|
|
160
|
+
if (chord > 2 * Math.abs(r) + 1e-9) return undefined;
|
|
161
|
+
const h = Math.sqrt(Math.max(0, r * r - (chord / 2) ** 2));
|
|
162
|
+
const mx = (x + tx) / 2, my = (y + ty) / 2;
|
|
163
|
+
// Which side of the chord the centre lies on: clockwise short arcs keep it to the right of the travel.
|
|
164
|
+
const side = (clockwise ? -1 : 1) * (r > 0 ? 1 : -1);
|
|
165
|
+
return [mx - side * h * dy / chord, my + side * h * dx / chord];
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** The top and bed-side pictures of one plate's G-code. `colours` are the project's filament colours by slot. */
|
|
169
|
+
export function renderPrintPreview(gcode: string, colours: unknown[] = []): PrintPreview | undefined {
|
|
170
|
+
const { segments, layers } = extrusionSegments(gcode);
|
|
171
|
+
if (!segments.length) return undefined;
|
|
172
|
+
let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity, minZ = Infinity, maxZ = -Infinity;
|
|
173
|
+
for (const s of segments) {
|
|
174
|
+
minX = Math.min(minX, s.x0, s.x1); maxX = Math.max(maxX, s.x0, s.x1);
|
|
175
|
+
minY = Math.min(minY, s.y0, s.y1); maxY = Math.max(maxY, s.y0, s.y1);
|
|
176
|
+
minZ = Math.min(minZ, s.z); maxZ = Math.max(maxZ, s.z);
|
|
177
|
+
}
|
|
178
|
+
const margin = 2;
|
|
179
|
+
minX -= margin; minY -= margin; maxX += margin; maxY += margin;
|
|
180
|
+
const span = Math.max(maxX - minX, maxY - minY);
|
|
181
|
+
// Fine enough for 0.3 mm ruler ticks (at least 4 px/mm) whenever the plate's drawn area allows.
|
|
182
|
+
const ppm = Math.min(8, Math.max(1, MAX_PIXELS / span));
|
|
183
|
+
const width = Math.max(1, Math.ceil((maxX - minX) * ppm)), height = Math.max(1, Math.ceil((maxY - minY) * ppm));
|
|
184
|
+
const palette = (tool: number) => parseColour(colours[tool]) ?? [40, 40, 40];
|
|
185
|
+
const used = new Set<number>();
|
|
186
|
+
const draw = (top: boolean) => {
|
|
187
|
+
const depth = new Float64Array(width * height).fill(top ? -Infinity : Infinity);
|
|
188
|
+
const toolAt = new Int16Array(width * height).fill(-1);
|
|
189
|
+
for (const s of segments) {
|
|
190
|
+
used.add(s.tool);
|
|
191
|
+
const ax = (s.x0 - minX) * ppm, ay = (maxY - s.y0) * ppm, bx = (s.x1 - minX) * ppm, by = (maxY - s.y1) * ppm;
|
|
192
|
+
// Each line at its extrusion width, so a surface's lines meet as they do on the part.
|
|
193
|
+
const radius = Math.max(0.5, s.width * ppm / 2), r2 = radius * radius, reach = Math.ceil(radius);
|
|
194
|
+
const steps = Math.max(1, Math.ceil(Math.hypot(bx - ax, by - ay) / Math.max(0.5, radius / 2)));
|
|
195
|
+
for (let i = 0; i <= steps; i++) {
|
|
196
|
+
const cx = ax + (bx - ax) * i / steps, cy = ay + (by - ay) * i / steps;
|
|
197
|
+
for (let dy = -reach; dy <= reach; dy++) for (let dx = -reach; dx <= reach; dx++) {
|
|
198
|
+
if (dx * dx + dy * dy > r2) continue;
|
|
199
|
+
const px = Math.floor(cx + dx), py = Math.floor(cy + dy);
|
|
200
|
+
if (px < 0 || py < 0 || px >= width || py >= height) continue;
|
|
201
|
+
const k = py * width + px;
|
|
202
|
+
if (top ? s.z >= depth[k] : s.z <= depth[k]) { depth[k] = s.z; toolAt[k] = s.tool; }
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
const rgb = new Uint8Array(width * height * 3);
|
|
207
|
+
const zRange = Math.max(1e-6, maxZ - minZ);
|
|
208
|
+
for (let py = 0; py < height; py++) for (let px = 0; px < width; px++) {
|
|
209
|
+
// The bed side is the part turned over top to bottom, so its text reads as it will on the part.
|
|
210
|
+
const sy = top ? py : height - 1 - py;
|
|
211
|
+
const k = sy * width + px, o = (py * width + px) * 3, t = toolAt[k];
|
|
212
|
+
if (t < 0) { rgb[o] = BACKGROUND[0]; rgb[o + 1] = BACKGROUND[1]; rgb[o + 2] = BACKGROUND[2]; continue; }
|
|
213
|
+
const [r, g, b] = palette(t);
|
|
214
|
+
// Height shading, toward white so it shows on dark filament too: on the top view the highest
|
|
215
|
+
// lines (raised tabs, top surfaces) are lightest; on the bed side the face on the bed is.
|
|
216
|
+
const h = (depth[k] - minZ) / zRange, lift = 0.4 * (top ? h : 1 - h);
|
|
217
|
+
rgb[o] = Math.round(r + (255 - r) * lift);
|
|
218
|
+
rgb[o + 1] = Math.round(g + (255 - g) * lift);
|
|
219
|
+
rgb[o + 2] = Math.round(b + (255 - b) * lift);
|
|
220
|
+
}
|
|
221
|
+
return encodePng(width, height, rgb).toString("base64");
|
|
222
|
+
};
|
|
223
|
+
const top = draw(true), bed = draw(false);
|
|
224
|
+
return {
|
|
225
|
+
views: [
|
|
226
|
+
{ name: "top", label: "Top, as it sits on the bed", png_base64: top, width, height },
|
|
227
|
+
{ name: "bed_side", label: "Bed side, turned over toward you", png_base64: bed, width, height },
|
|
228
|
+
],
|
|
229
|
+
mm_per_pixel: Math.round(1e6 / ppm) / 1e6,
|
|
230
|
+
extent_mm: [minX, minY, maxX, maxY].map(v => Math.round(v * 100) / 100) as [number, number, number, number],
|
|
231
|
+
layers,
|
|
232
|
+
filaments_used: [...used].sort((a, b) => a - b),
|
|
233
|
+
};
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/** The preview of one plate of a sliced .3mf or a .gcode file, or undefined when it has no extruding moves. */
|
|
237
|
+
export async function previewPrintFile(source: { gcode: string; projectColours?: unknown[] }): Promise<PrintPreview | undefined> {
|
|
238
|
+
let colours = source.projectColours;
|
|
239
|
+
if (!colours?.length) {
|
|
240
|
+
// A bare .gcode file carries its colours in its header: "; filament_colour = #000000;#FFFFFF".
|
|
241
|
+
const header = /^\s*;\s*filament_colou?r\s*[=:]\s*(.+)$/im.exec(source.gcode);
|
|
242
|
+
colours = header ? header[1].split(/[;,]/).map(v => v.trim()) : [];
|
|
243
|
+
}
|
|
244
|
+
return renderPrintPreview(source.gcode, colours);
|
|
245
|
+
}
|