bambu-printer-mcp 1.1.95 → 1.1.97
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/CONTRIBUTORS.md +1 -0
- package/README.md +13 -2
- package/dist/cad/contracts.js +7 -5
- package/dist/cad-engine.js +1 -0
- package/dist/counterpart/info.js +1 -0
- package/dist/counterpart/make-3mf.d.ts +1 -0
- package/dist/counterpart/make-3mf.js +37 -5
- package/dist/counterpart/model-plates.d.ts +2 -0
- package/dist/counterpart/model-plates.js +3 -0
- package/dist/counterpart/part-meshes.d.ts +114 -0
- package/dist/counterpart/part-meshes.js +323 -0
- package/dist/counterpart/plate-filaments.d.ts +3 -0
- package/dist/counterpart/plate-filaments.js +31 -10
- package/dist/counterpart/remote.js +1 -0
- package/dist/counterpart/schemas.d.ts +10 -0
- package/dist/counterpart/schemas.js +2 -0
- package/dist/design-app-setup.d.ts +9 -0
- package/dist/design-app-setup.js +5 -2
- package/dist/design-guidance.d.ts +3 -3
- package/dist/design-guidance.js +8 -4
- package/dist/fusion-mcp-bridge.d.ts +13 -0
- package/dist/fusion-mcp-bridge.js +35 -4
- package/dist/index.js +39 -8
- package/dist/refusal.d.ts +15 -1
- package/dist/refusal.js +19 -1
- package/dist/slicer/floating-regions.d.ts +54 -0
- package/dist/slicer/floating-regions.js +198 -0
- package/dist/slicer/profile-flatten.js +4 -0
- package/dist/tool-annotations.js +2 -0
- package/package.json +2 -2
- package/src/cad/contracts.ts +7 -5
- package/src/cad/project3mf.py +9 -4
- package/src/cad/scan_measure.py +207 -0
- package/src/cad/scan_touchup.py +4 -1
- package/src/cad/worker.py +2 -1
- package/src/cad-engine.ts +1 -0
- package/src/counterpart/info.ts +1 -0
- package/src/counterpart/make-3mf.ts +33 -7
- package/src/counterpart/model-plates.ts +4 -0
- package/src/counterpart/part-meshes.ts +304 -0
- package/src/counterpart/plate-filaments.ts +25 -9
- package/src/counterpart/remote.ts +1 -0
- package/src/counterpart/schemas.ts +4 -0
- package/src/design-app-setup.ts +7 -2
- package/src/design-guidance.ts +8 -4
- package/src/fusion-mcp-bridge.ts +34 -4
- package/src/index.ts +40 -8
- package/src/refusal.ts +19 -1
- package/src/slicer/floating-regions.ts +187 -0
- package/src/slicer/profile-flatten.ts +3 -0
- package/src/tool-annotations.ts +2 -0
package/src/design-guidance.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { CAD_DESIGN_PROMPT } from "./cad/contracts.js";
|
|
2
|
+
import { SLICE_WARNING_RULE } from "./slicer/floating-regions.js";
|
|
2
3
|
/**
|
|
3
4
|
* Manufacturing guidance for agents that design printable models: David Montgomery's FDM design
|
|
4
5
|
* prompt pack (3 November 2026), with later fit, flexure and printed-fastener guidance in the
|
|
@@ -12,7 +13,7 @@ export const FDM_CORE = `Design the finished object the user wants, with the man
|
|
|
12
13
|
|
|
13
14
|
Use the actual printer and material context: nozzle arrangement and filament routing, build volume, nozzle and line widths, layer profile, cooling, available filaments, and relevant successful prints or calibration. Missing information is unknown, not a capability the printer automatically has. Use reasonable, labeled assumptions for reversible choices; ask only when an unknown materially changes the result.
|
|
14
15
|
|
|
15
|
-
Before committing to detailed geometry, choose a plausible way to manufacture and assemble it. For a consequential tradeoff, compare the strongest one-piece approach with a meaningfully different orientation or split. Simple parts do not need a design tournament. Judge total effort to obtain a good finished object: printing, consumed filament, likely rework, support cleanup, assembly, and extra hardware. Respect the user's priorities instead of applying fixed numerical weights.
|
|
16
|
+
Before committing to detailed geometry, choose a plausible way to manufacture and assemble it. For a consequential tradeoff, compare the strongest one-piece approach with a meaningfully different orientation or split. Simple parts do not need a design tournament. Decide it in a few lines and build a rough model of it early: the first geometry is how you check a plan, not the reward for finishing one. Judge total effort to obtain a good finished object: printing, consumed filament, likely rework, support cleanup, assembly, and extra hardware. Respect the user's priorities instead of applying fixed numerical weights.
|
|
16
17
|
|
|
17
18
|
Keep assembled orientation and print orientation distinct. Preserve critical dimensions and mating surfaces. Account for measurement uncertainty and fit clearance separately; a scan or printed measuring tool does not establish its own accuracy. Use the smallest useful fit sample when uncertainty could otherwise waste a substantial print. A size the person confirmed without changing a prefilled number is not a measurement. If a case, cover, or attachment is mentioned, the bare product's size is not the size to design to.
|
|
18
19
|
|
|
@@ -25,7 +26,7 @@ Find out before you design, and before you ask. Research whenever the request na
|
|
|
25
26
|
6. For what is still unknown after about two rounds per fact, shape the design so that fact does not decide whether it works (an adjustable or sprung interface, a foot that suits more than one surface), or state a bounded assumption as an assumption. Ask the person only as the last resort, one short question, and only for what exists nowhere but with them. Never ask for something a search answers: a photo of their car's dashboard, the size of a named product, what a named surface is made of.
|
|
26
27
|
Without web tools, say so in the result, use what you recall labelled as recalled rather than published, and lean harder on step 6.
|
|
27
28
|
|
|
28
|
-
Write the concept down
|
|
29
|
+
Write the concept down in a few lines, with the first build rather than as a plan before it: the bought product you are following, its mechanism, the load path, and how it will print. Before choosing a mechanism, establish what every working bought or published version of the thing has, and keep all of it. For example, a car phone holder turns and tilts to face the driver; a mount's base is sized by the moment of what it holds, not just its weight; an adhesive mount uses a full pad of the tape's grade, not a strip, on a surface the tape suits. Start from the complete product a capable designer would describe at once, then make it printable. A design that leaves out a feature they all have says what it lost and why that is acceptable for this person.
|
|
29
30
|
|
|
30
31
|
Give it the product's form as well as its function. The bought thing's shape is evidence: a handle swells where the palm closes, a hook's arm thickens towards its root, a knob is round and knurled, a clip's jaws wrap what they hold. Do not reduce a product to a flat profile pushed up, or a box with holes, because that is quick to model and prints without thought: that is a bracket, and people can tell. Put curves where hands and objects touch and where load turns a corner. A flat, in-plane layout is right only for the element that needs it (a spring that must bend in the layer plane, a print-in-place hinge or chain), and then say so; the rest of the product keeps its form, split or turned for printing if need be. When the engine renders the model, look at a three-quarter view and ask whether a person would recognise the thing and want it.
|
|
31
32
|
|
|
@@ -43,7 +44,7 @@ On a shared-nozzle multicolor setup, reason about filament transitions across la
|
|
|
43
44
|
|
|
44
45
|
Use assembly when its benefit is worth the user's additional work. Design alignment, clearance, engagement, and assembly access deliberately. Glue is a valid planned joining method for suitable materials and loads; make joints self-locating and give them useful bonding area. Use mechanical retention when loads, repeated flexing, or serviceability call for it. State needed glue, hardware, tools, and assembly effort plainly. Avoid adding parts when a modest support or a simple one-piece print is the better result. A printed screw, nut, or threaded hole is an ordinary choice at hand sizes (M8 and up as the usual starting point, about M6 as the floor) with a coarse profile shaped to print without supports; below that floor, under sustained preload that must not relax, in heat, or under shock, a metal screw or insert is the honest choice. Keep threads out of the main load path where a shoulder, tenon, key, or serrated face can carry shear and torque, and let the thread only hold the joint closed.
|
|
45
46
|
|
|
46
|
-
Verify the chosen geometry in its actual print orientation and inspect the slice when tools permit. Check critical fits, missing or floating features, toolpaths, supports, color assignments, total time, and material consumption. Treat a slicer prediction as a prediction, not a physical test. Fix consequential problems and re-slice relevant changes. Stop when the design meets the brief and no remaining improvement justifies its cost. State "prints without supports", "holds", or "fits" only when the engine's own checks or the slice show it, and give the number that shows it; otherwise call it an untested prediction.
|
|
47
|
+
Verify the chosen geometry in its actual print orientation and inspect the slice when tools permit. Check critical fits, missing or floating features, toolpaths, supports, color assignments, total time, and material consumption. Treat a slicer prediction as a prediction, not a physical test. Fix consequential problems and re-slice relevant changes. A cosmetic slicer warning (floating regions, small islands) gets one targeted fix and one re-slice, then stops: report what remains, or slice with supports on. Stop when the design meets the brief and no remaining improvement justifies its cost. State "prints without supports", "holds", or "fits" only when the engine's own checks or the slice show it, and give the number that shows it; otherwise call it an untested prediction.
|
|
47
48
|
|
|
48
49
|
Fit and flexure guidance is longer than this text and is read when it applies: fdm_fit whenever a part meets a real object or another part, fdm_flexures whenever a part must flex, grip, snap, clip or spring. If your host did not attach them, read them with this MCP's design_guidance tool before you choose that fit or size that spring. Where the MCP's code engine is in use, its cad_examples tool lists worked designs to start from.
|
|
49
50
|
|
|
@@ -55,6 +56,8 @@ Preserve the requested visual pattern. Evaluate its colors in build coordinates
|
|
|
55
56
|
|
|
56
57
|
For a costly pattern, consider the most promising alternatives: a different build orientation, color regions confined to fewer layers, shallow face inlays, or separately printed single-color pieces with intentional assembly. A vertical stripe in use may become a low-change feature in a different print orientation. Judge each option against load direction, surface quality, support burden, and the user's exact visual requirements. Finer layers can help an overhang while adding color-change layers; evaluate local adaptive layers and re-slice the combined plan.
|
|
57
58
|
|
|
59
|
+
When this MCP's code engine makes the model, its colour parts come from the same cad_run as the model (build() returns project_3mf(), one part per colour), never from re-running the whole script once per colour.
|
|
60
|
+
|
|
58
61
|
Separating color bodies does not by itself eliminate swaps. Check plate scheduling. Single-color plates can remove repeated color changes; by-layer printing of different-color objects together usually cannot. Use sequential object printing only when supported and its clearance constraints are satisfied. Batch copies only when the user wants them.
|
|
59
62
|
|
|
60
63
|
Use the actual directional flushing matrix and filament compatibility. Purging clears previous material; priming restores consistent extrusion. Track those separately when the slicer does. Flushing into compatible infill or supports may reduce discarded material, but it does not remove switching time, has finite capacity, and can affect appearance or strength. Do not add unnecessary infill or objects merely to hide waste.
|
|
@@ -77,7 +80,7 @@ export const FDM_AFTER_SLICE = `Review this slice against the user's brief and t
|
|
|
77
80
|
|
|
78
81
|
Check that the actual toolpaths preserve critical features, fit, connected material, intended colors, and load-bearing sections. Inspect consequential first layers, bridges, islands, supported undersides, and removal access. Compare expected total print time, total material across all plates, and manual work with the best credible alternative. Keep purge, prime-tower, support, and model quantities distinct only when the data provides a non-overlapping breakdown.
|
|
79
82
|
|
|
80
|
-
If the plan is unexpectedly costly or fragile, identify the dominant cause and make the smallest change that preserves the brief. Re-slice after a relevant geometry, orientation, material, or process change. Do not optimize a minor imperfection at the expense of function or appearance, and do not invent a redesign simply to produce criticism. Check every support, fit, and hold claim in the summary against a number from the slice or the engine's checks (support area and worst overhang, engagement and gap, estimated bite at the forced opening). A claim without its number comes out or is labelled a prediction.
|
|
83
|
+
If the plan is unexpectedly costly or fragile, identify the dominant cause and make the smallest change that preserves the brief. Re-slice after a relevant geometry, orientation, material, or process change. A cosmetic warning (floating regions, small islands) gets one targeted fix and one re-slice, then stops: report what remains, or slice with supports on; never loop rebuild and re-slice to chase it. Do not optimize a minor imperfection at the expense of function or appearance, and do not invent a redesign simply to produce criticism. Check every support, fit, and hold claim in the summary against a number from the slice or the engine's checks (support area and worst overhang, engagement and gap, estimated bite at the forced opening). A claim without its number comes out or is labelled a prediction.
|
|
81
84
|
|
|
82
85
|
Return a concise decision: keep, revise, or validate one specific uncertainty. Include the decisive evidence and the exact next action. A clean slice supports a printability prediction; it does not verify physical fit, strength, or bridge quality.`;
|
|
83
86
|
|
|
@@ -399,6 +402,7 @@ export function slicingGuidance(slicerType: string, capabilities: { supports: bo
|
|
|
399
402
|
`How this printer MCP slices. Its slicer is ${slicer}.`,
|
|
400
403
|
"- When they could change a decision, read the printer's loaded filaments with get_printer_filaments and its slicing settings with get_slice_settings.",
|
|
401
404
|
"- To check a consequential choice, slice a checkpoint with slice_stl and read its structured slicer_result (return code, error and each plate's warning), not only the file path. A checkpoint is only a check: the print slices the exported model again.",
|
|
405
|
+
`- Warnings: ${SLICE_WARNING_RULE} For floating regions, slice_stl's result lists where they are (floating_regions: each one's z, depth and box), so aim the one fix there.`,
|
|
402
406
|
capabilities.orient
|
|
403
407
|
? `- Orientation: slice_stl with orient true lets ${slicer}'s own auto-orient choose how an STL sits on the bed. It keeps overhang area low; it does not check cantilevers. To see what it chooses, slice the checkpoint with orient true. When a print is oriented this way, don't promise a particular orientation on the bed: the slicer chooses it.`
|
|
404
408
|
: `- Orientation: ${slicer} doesn't auto-orient here. An STL prints in the orientation it's exported in.`,
|
package/src/fusion-mcp-bridge.ts
CHANGED
|
@@ -38,6 +38,7 @@ export const FUSION_MCP_DEFAULT_ARGS = Object.freeze([
|
|
|
38
38
|
]);
|
|
39
39
|
const DEFAULT_TIMEOUT_MS = 180_000;
|
|
40
40
|
const MAX_TIMEOUT_MS = 600_000;
|
|
41
|
+
const STATUS_PROBE_TIMEOUT_MS = 5_000;
|
|
41
42
|
const LAUNCH_WAIT_MS = 90_000;
|
|
42
43
|
const ADDIN_PING_MS = 2_000;
|
|
43
44
|
const EXPORT_NAME = /^[A-Za-z0-9][A-Za-z0-9._ -]{0,99}$/;
|
|
@@ -244,7 +245,10 @@ export const FUSION_STATUS_OUTPUT_SCHEMA = {
|
|
|
244
245
|
type: "object" as const,
|
|
245
246
|
properties: {
|
|
246
247
|
configured: { type: "boolean", description: "FUSION_MCP_COMMAND is set." },
|
|
247
|
-
connected: { type: "boolean", description: "The
|
|
248
|
+
connected: { type: "boolean", description: "The add-in answers and its command probe has not failed. Check state/ responsive for design readiness and activeDesign for an open document." },
|
|
249
|
+
responsive: { type: "boolean", description: "A fresh no-op through execute_code completed and Fusion reports startup complete; this does not guarantee a later design operation succeeds." },
|
|
250
|
+
state: { type: "string", enum: ["starting", "ready", "unresponsive"], description: "starting comes from Fusion's own isStartupComplete flag, ready requires the command probe, unresponsive means readiness could not be verified. See reason." },
|
|
251
|
+
reason: { type: "string", description: "Plain explanation and next step, provided by the MCP rather than inferred by clients." },
|
|
248
252
|
addinReachable: { type: "boolean", description: "The Fusion360MCP add-in answered a ping on FUSION_MCP_HOST:FUSION_MCP_PORT (default localhost:9877) within 2 s. Another program on that port, such as Blender's MCP add-on, does not count." },
|
|
249
253
|
fusionRunning: { type: "boolean" },
|
|
250
254
|
activeDesign: { type: "boolean", description: "When connected: whether Fusion has a design open, from the add-in's read-only get_design_type (false is its NO_ACTIVE_DESIGN). The pinned add-in refuses every design command, fusion_mcp_new_design included, without one (faust issue #12). Absent when unknown." },
|
|
@@ -255,7 +259,7 @@ export const FUSION_STATUS_OUTPUT_SCHEMA = {
|
|
|
255
259
|
server: { type: "object" },
|
|
256
260
|
error: { type: "string" },
|
|
257
261
|
},
|
|
258
|
-
required: ["configured", "connected", "addinReachable", "fusionRunning", "tools"],
|
|
262
|
+
required: ["configured", "connected", "responsive", "state", "reason", "addinReachable", "fusionRunning", "tools"],
|
|
259
263
|
};
|
|
260
264
|
|
|
261
265
|
|
|
@@ -425,7 +429,7 @@ export class FusionMcpBridge {
|
|
|
425
429
|
async status(args: Arguments, signal?: AbortSignal): Promise<Record<string, unknown>> {
|
|
426
430
|
allowedArguments(args, ["launch", "timeout_ms"]);
|
|
427
431
|
if (args.launch !== undefined && typeof args.launch !== "boolean") throw new FusionError("launch must be a boolean.");
|
|
428
|
-
const timeout = timeoutMilliseconds(args.timeout_ms);
|
|
432
|
+
const timeout = Math.min(timeoutMilliseconds(args.timeout_ms), STATUS_PROBE_TIMEOUT_MS);
|
|
429
433
|
const { host, port } = addinAddress();
|
|
430
434
|
const configured = Boolean(process.env.FUSION_MCP_COMMAND?.trim());
|
|
431
435
|
let addinReachable = await this.system.addinAnswers(host, port, ADDIN_PING_MS);
|
|
@@ -444,7 +448,8 @@ export class FusionMcpBridge {
|
|
|
444
448
|
addinReachable = await this.system.addinAnswers(host, port, ADDIN_PING_MS);
|
|
445
449
|
}
|
|
446
450
|
}
|
|
447
|
-
const result: Record<string, unknown> = { configured, connected: false,
|
|
451
|
+
const result: Record<string, unknown> = { configured, connected: false, responsive: false, state: "unresponsive",
|
|
452
|
+
reason: configured ? "Fusion isn't responding on your Mac. Restart Fusion, then Try Again." : "Set up the Fusion MCP connection first.", addinReachable, fusionRunning, tools: [], launched, transport: "stdio", pin: FUSION_MCP_PIN };
|
|
448
453
|
if (!configured) return result;
|
|
449
454
|
try {
|
|
450
455
|
await this.request({ timeout, signal }, async (live, options, dispatched) => {
|
|
@@ -467,8 +472,33 @@ export class FusionMcpBridge {
|
|
|
467
472
|
if (!failed(read, "get_design_type")) result.activeDesign = true;
|
|
468
473
|
else if (errorKind(read, "get_design_type") === "NO_ACTIVE_DESIGN") result.activeDesign = false;
|
|
469
474
|
}
|
|
475
|
+
if (result.connected === true) {
|
|
476
|
+
// At the pinned add-in execute_code traverses _MUTATION_COMMANDS snapshots and the same
|
|
477
|
+
// handler as design commands. A no-op tests that path without editing or opening a document.
|
|
478
|
+
// A late probe is harmless. Require this call's nonce; neither ping nor a design read proves readiness.
|
|
479
|
+
const nonce = randomUUID();
|
|
480
|
+
const code = `# BAMBU_FUSION status_probe
|
|
481
|
+
import json
|
|
482
|
+
json.dumps({"nonce": "${nonce}", "startupComplete": app.isStartupComplete})`;
|
|
483
|
+
const probe = await this.invoke(live, options, dispatched, "execute_code", { code });
|
|
484
|
+
if (errorKind(probe, "execute_code") === "NO_ACTIVE_DESIGN") {
|
|
485
|
+
result.activeDesign = false;
|
|
486
|
+
result.reason = "Open a design in Fusion, then Try Again.";
|
|
487
|
+
return;
|
|
488
|
+
}
|
|
489
|
+
if (failed(probe, "execute_code")) throw new FusionError("Fusion's command readiness probe failed.");
|
|
490
|
+
const receipt = argumentObject(codeJson(probe), "Fusion readiness receipt");
|
|
491
|
+
if (receipt.nonce !== nonce || typeof receipt.startupComplete !== "boolean") {
|
|
492
|
+
throw new FusionError("Fusion did not return this command readiness probe's receipt.");
|
|
493
|
+
}
|
|
494
|
+
result.responsive = receipt.startupComplete;
|
|
495
|
+
result.connected = receipt.startupComplete;
|
|
496
|
+
result.state = receipt.startupComplete ? "ready" : "starting";
|
|
497
|
+
result.reason = receipt.startupComplete ? "Fusion's command path is responding." : "Fusion is still starting. Finish any sign-in or update dialog, then Try Again.";
|
|
498
|
+
}
|
|
470
499
|
});
|
|
471
500
|
} catch (error) {
|
|
501
|
+
result.connected = false;
|
|
472
502
|
result.error = error instanceof Error ? error.message : String(error);
|
|
473
503
|
}
|
|
474
504
|
return result;
|
package/src/index.ts
CHANGED
|
@@ -7,6 +7,7 @@ import { withAnnotations } from "./tool-annotations.js";
|
|
|
7
7
|
import { withRemote } from "./counterpart/remote.js";
|
|
8
8
|
import { refusalReport, slicedFileFacts, slicerReport } from "./counterpart/sliced-file.js";
|
|
9
9
|
import { listModelPlates } from "./counterpart/model-plates.js";
|
|
10
|
+
import { floatingWarningFacts } from "./slicer/floating-regions.js";
|
|
10
11
|
|
|
11
12
|
/** The slicer's verdict beside its result.json (`slicer_report`). */
|
|
12
13
|
function reportOf(result: unknown): { slicer_report?: ReturnType<typeof slicerReport> } {
|
|
@@ -87,12 +88,13 @@ import { PROPOSE_FILAMENTS_INPUT_PROPERTIES, PROPOSE_FILAMENTS_OUTPUT_SCHEMA, NO
|
|
|
87
88
|
import { DESIGN_PROMPTS, FDM_CAPABILITY_GUIDANCE, FDM_CAPABILITY_RESOURCE, FDM_CAPABILITY_URI, FDM_FIT_GUIDANCE, FDM_FIT_RESOURCE, FDM_FIT_URI, FDM_SLICING_PROMPT, SERVER_INSTRUCTIONS, slicingGuidance } from "./design-guidance.js";
|
|
88
89
|
import { bambuProgress, offlineProgress } from "./counterpart/progress.js";
|
|
89
90
|
import { makeCounterpart3mf } from "./counterpart/make-3mf.js";
|
|
91
|
+
import { partMeshes, PART_MESHES_OUTPUT_SCHEMA } from "./counterpart/part-meshes.js";
|
|
90
92
|
import { MAKE_3MF_OUTPUT_SCHEMA, PRINT_PROGRESS_OUTPUT_SCHEMA, PRINTER_INFO_OUTPUT_SCHEMA } from "./counterpart/schemas.js";
|
|
91
93
|
import { SELF_CHECK_OUTPUT_SCHEMA, selfCheck } from "./counterpart/self-check.js";
|
|
92
94
|
import { DIAGNOSTICS_INPUT_PROPERTIES, DIAGNOSTICS_OUTPUT_SCHEMA, appVersion, buildDiagnostics, captureServerLog, diagnosticsBudget, jsonText, recordToolError, rememberSecretArguments, serverLogText, settingsSnapshot, toolErrorsText, type DiagnosticsSource } from "./counterpart/diagnostics.js";
|
|
93
95
|
import { parseProcessOverrides } from "./slicer/process-overrides.js";
|
|
94
96
|
import { PRINT_QUALITY_PROPERTIES, withPrintQuality } from "./slicer/print-quality.js";
|
|
95
|
-
import { PrinterRefusal, withPrintDispatch, markPrintCommandSent, printOutcome } from "./refusal.js";
|
|
97
|
+
import { FilamentSlotsError, PrinterRefusal, withPrintDispatch, markPrintCommandSent, printOutcome } from "./refusal.js";
|
|
96
98
|
import { uploadProgressReporter } from "./upload-progress.js";
|
|
97
99
|
import { machinePauseGcode, parsePauseLayers, pausedLayers, readPlateGcode } from "./slicer/layer-pauses.js";
|
|
98
100
|
|
|
@@ -167,7 +169,7 @@ const SERVER_INFO = {
|
|
|
167
169
|
/** Tools that declare an outputSchema: they always return structuredContent, and errors carry none. */
|
|
168
170
|
const OUTPUT_SCHEMA_TOOLS = new Set([
|
|
169
171
|
"cad_status", "cad_setup", "cad_run", "cad_check_fit", "cad_examples",
|
|
170
|
-
"counterpart_printer_info", "counterpart_self_check", "counterpart_diagnostics", "counterpart_print_progress", "counterpart_make_3mf",
|
|
172
|
+
"counterpart_printer_info", "counterpart_self_check", "counterpart_diagnostics", "counterpart_print_progress", "counterpart_make_3mf", "counterpart_part_meshes",
|
|
171
173
|
"counterpart_discover_printers", "counterpart_setup_fields", "counterpart_propose_filaments",
|
|
172
174
|
"fusion_mcp_status", "fusion_mcp_new_design", "fusion_mcp_export",
|
|
173
175
|
"camera_stream_start", "camera_frame", "camera_stream_stop",
|
|
@@ -2808,7 +2810,7 @@ class BambuPrinterMCPServer {
|
|
|
2808
2810
|
},
|
|
2809
2811
|
{
|
|
2810
2812
|
name: "slice_stl",
|
|
2811
|
-
description: "Slice an STL or 3MF file using a slicer to generate printable G-code or sliced 3MF. IMPORTANT: bambu_model must be specified to ensure the slicer generates safe G-code for the correct printer. The text result is the sliced file's path. When Bambu Studio or OrcaSlicer writes a result.json, structuredContent.slicer_result carries it verbatim, success or error: error_string, return_code and each sliced_plates[].warning_message, such as a floating cantilever. structuredContent.slicer_report says whether it failed; for a failure, its message is a plain sentence for a person and slicer_message keeps the slicer's words, which a failed slice's text gives after that sentence. A 3MF that carries its own process settings (a designer's Bambu Studio or Orca project) slices with them unless slicer_profile, template_name or template_3mf_path is given; the machine still comes from bambu_model. quality and strength adjust that process, and strength never lowers its walls or infill.",
|
|
2813
|
+
description: "Slice an STL or 3MF file using a slicer to generate printable G-code or sliced 3MF. IMPORTANT: bambu_model must be specified to ensure the slicer generates safe G-code for the correct printer. The text result is the sliced file's path. When Bambu Studio or OrcaSlicer writes a result.json, structuredContent.slicer_result carries it verbatim, success or error: error_string, return_code and each sliced_plates[].warning_message, such as a floating cantilever. structuredContent.slicer_report says whether it failed; for a failure, its message is a plain sentence for a person and slicer_message keeps the slicer's words, which a failed slice's text gives after that sentence. When a slice that worked warns of floating regions, next carries the stop rule (one targeted fix and one re-slice, then report it or slice with supports on) and, for an STL the slicer did not turn, structuredContent.floating_regions lists where they are: x and y in the STL's own millimetres, z above its lowest point, and depth_mm, how far each hangs below where it joins the rest. A 3MF that carries its own process settings (a designer's Bambu Studio or Orca project) slices with them unless slicer_profile, template_name or template_3mf_path is given; the machine still comes from bambu_model. quality and strength adjust that process, and strength never lowers its walls or infill.",
|
|
2812
2814
|
inputSchema: {
|
|
2813
2815
|
type: "object",
|
|
2814
2816
|
properties: {
|
|
@@ -3674,7 +3676,8 @@ class BambuPrinterMCPServer {
|
|
|
3674
3676
|
properties: {
|
|
3675
3677
|
stl_path: { type: "string", description: "Path to the part's STL file." },
|
|
3676
3678
|
name: { type: "string", description: "The part's name, shown in the slicer." },
|
|
3677
|
-
filament: { type: "integer", minimum: 1, maximum: 64, description: "1-based project filament for this part; defaults to the part's position (1, 2, ...)." }
|
|
3679
|
+
filament: { type: "integer", minimum: 1, maximum: 64, description: "1-based project filament for this part; defaults to the part's position (1, 2, ...)." },
|
|
3680
|
+
color: { type: "string", pattern: "^#[0-9A-Fa-f]{6}$", description: "The part's colour as #RRGGBB. Give every part one, or none: the 3MF then declares each filament's colour (project_settings.config filament_colour), as Bambu Studio does, and parts on one filament share it." }
|
|
3678
3681
|
},
|
|
3679
3682
|
required: ["stl_path", "name"],
|
|
3680
3683
|
additionalProperties: false
|
|
@@ -3687,6 +3690,20 @@ class BambuPrinterMCPServer {
|
|
|
3687
3690
|
},
|
|
3688
3691
|
outputSchema: MAKE_3MF_OUTPUT_SCHEMA
|
|
3689
3692
|
},
|
|
3693
|
+
{
|
|
3694
|
+
name: "counterpart_part_meshes",
|
|
3695
|
+
description: "Counterpart contract (counterpart/1): one STL per printable part of any 3MF (a pass's, counterpart_make_3mf's, cad_run's project_3mf, or a designer's Bambu Studio, OrcaSlicer or plain 3MF), so a client draws each part in its colour or shows the design in AR. Writes into a new folder it creates inside out_dir and never overwrites. Returns units (mm), folder and parts: [{id, name, plate?, color?, filament?, painted?, stl_path, triangles, size_mm}], one per part per printed copy. Every STL is in the 3MF's build frame in millimetres, component and build transforms applied, so the parts line up when drawn together; plate is the plate number from 1 (list_3mf_plates index + 1), absent for a 3MF without plates; color is #RRGGBB from the 3MF's own filament colours, absent when it declares none; painted means slicer painting recolours some facets. A part beyond the read limits is listed in skipped with why.",
|
|
3696
|
+
inputSchema: {
|
|
3697
|
+
type: "object",
|
|
3698
|
+
properties: {
|
|
3699
|
+
three_mf_path: { type: "string", description: "Path to the 3MF." },
|
|
3700
|
+
out_dir: { type: "string", description: "An existing folder; each call writes into a new subfolder of it." }
|
|
3701
|
+
},
|
|
3702
|
+
required: ["three_mf_path", "out_dir"],
|
|
3703
|
+
additionalProperties: false
|
|
3704
|
+
},
|
|
3705
|
+
outputSchema: PART_MESHES_OUTPUT_SCHEMA
|
|
3706
|
+
},
|
|
3690
3707
|
{
|
|
3691
3708
|
name: "blender_mcp_setup",
|
|
3692
3709
|
description: "Check or update the MCP for Blender add-on that the configured Blender bridge (BLENDER_MCP_COMMAND uvx, BLENDER_MCP_ARGS naming mcp-for-blender or blender-mcp) needs. Without update: which add-on file Blender loads, its protocol and the protocol the package expects, whether Blender is listening and the running add-on's own handshake. Changes nothing. With update: true, stages the add-on with the package's own installer (mcp-for-blender install-addon) at the inspected version, checks it, keeps the old file as a backup next to it and renames the new one into place. Never starts, stops or edits Blender; a running Blender uses the new add-on once it is re-enabled or restarted. A custom bridge returns supported false.",
|
|
@@ -3709,12 +3726,12 @@ class BambuPrinterMCPServer {
|
|
|
3709
3726
|
},
|
|
3710
3727
|
{
|
|
3711
3728
|
name: "fusion_mcp_status",
|
|
3712
|
-
description: `Check Autodesk Fusion through the configured Fusion MCP server (fusion360-mcp-server, faust-machines or the pinned fork with document binding): whether it is configured, Fusion is running, the Fusion360MCP add-in answers on its port, and the server's tools and schemas.
|
|
3729
|
+
description: `Check Autodesk Fusion through the configured Fusion MCP server (fusion360-mcp-server, faust-machines or the pinned fork with document binding): whether it is configured, Fusion is running, the Fusion360MCP add-in answers on its port, and the server's tools and schemas. Reports state (starting, ready, unresponsive), responsive and reason from a fresh no-op execute_code command probe, capped at 5 s; a ping or design read alone is not readiness. The probe never edits or opens a document. With launch: true, starts Fusion on macOS when it is not running and waits up to 90 s for the add-in. Configure FUSION_MCP_COMMAND (uvx) and FUSION_MCP_ARGS (${JSON.stringify(FUSION_MCP_DEFAULT_ARGS)}), or run fusion_mcp_setup.`,
|
|
3713
3730
|
inputSchema: {
|
|
3714
3731
|
type: "object",
|
|
3715
3732
|
properties: {
|
|
3716
3733
|
launch: { type: "boolean", description: "Start Autodesk Fusion (open -a \"Autodesk Fusion\") when it is not running, then wait up to 90 s for the add-in." },
|
|
3717
|
-
timeout_ms: { type: "integer", minimum: 100, maximum: 600000, description: "Connection and
|
|
3734
|
+
timeout_ms: { type: "integer", minimum: 100, maximum: 600000, description: "Connection, discovery and command-probe deadline, capped at 5000 ms even if a larger value is requested. Launch waiting is separate." }
|
|
3718
3735
|
},
|
|
3719
3736
|
additionalProperties: false
|
|
3720
3737
|
},
|
|
@@ -4725,7 +4742,13 @@ class BambuPrinterMCPServer {
|
|
|
4725
4742
|
await progressNotifications;
|
|
4726
4743
|
// The text stays the sliced file's path; slicer_result is the slicer's own result.json, verbatim, and
|
|
4727
4744
|
// slicer_report its verdict and words, so clients don't read the slicer's format.
|
|
4728
|
-
|
|
4745
|
+
// A warning about floating regions comes with where they are and the rule that bounds chasing it (#859).
|
|
4746
|
+
const reported = withSlicerReport(sliced);
|
|
4747
|
+
// Turned or scaled by the slicer: the STL's own coordinates would no longer match the slice.
|
|
4748
|
+
const turned = Boolean(args?.orient) || [args?.rotate, args?.rotate_x, args?.rotate_y].some(r => r !== undefined && Number(r) !== 0)
|
|
4749
|
+
|| (args?.scale !== undefined && Number(args.scale) !== 1);
|
|
4750
|
+
const located = await floatingWarningFacts(reported.slicer_report, String(args.stl_path), turned);
|
|
4751
|
+
return { content: [{ type: "text", text: sliced.path }], structuredContent: { ...reported, ...located } };
|
|
4729
4752
|
}
|
|
4730
4753
|
|
|
4731
4754
|
case "print_3mf": {
|
|
@@ -5180,6 +5203,10 @@ class BambuPrinterMCPServer {
|
|
|
5180
5203
|
result = await makeCounterpart3mf(args ?? {});
|
|
5181
5204
|
break;
|
|
5182
5205
|
|
|
5206
|
+
case "counterpart_part_meshes":
|
|
5207
|
+
result = await partMeshes(args ?? {});
|
|
5208
|
+
break;
|
|
5209
|
+
|
|
5183
5210
|
case "design_guidance":
|
|
5184
5211
|
result = designGuidance(args ?? {});
|
|
5185
5212
|
break;
|
|
@@ -5266,7 +5293,7 @@ class BambuPrinterMCPServer {
|
|
|
5266
5293
|
}
|
|
5267
5294
|
const message = error instanceof Error ? error.message : String(error);
|
|
5268
5295
|
// Refusals and printer rejections repeat unchanged; say what to fix instead of "try again".
|
|
5269
|
-
const refused = /nothing was (?:sent|uploaded)|no command was sent|does not match the job|is ambiguous|is missing or ambiguous|rejected the print command|are refused|is refused|refused because|refused until|refused before/i.test(message);
|
|
5296
|
+
const refused = error instanceof FilamentSlotsError || /nothing was (?:sent|uploaded)|no command was sent|does not match the job|is ambiguous|is missing or ambiguous|rejected the print command|are refused|is refused|refused because|refused until|refused before/i.test(message);
|
|
5270
5297
|
const structured: StructuredToolError = {
|
|
5271
5298
|
status: "error",
|
|
5272
5299
|
retryable: false,
|
|
@@ -5283,6 +5310,11 @@ class BambuPrinterMCPServer {
|
|
|
5283
5310
|
...(error.slicerResult ? { slicer_result: error.slicerResult } : {}),
|
|
5284
5311
|
slicer_report: { ...refusalReport(error.words), message: error.plain ?? error.words.slice(0, 2000) },
|
|
5285
5312
|
} : {}),
|
|
5313
|
+
// A design in more colours than filaments to slice it with: the counts and the plain answer a client shows.
|
|
5314
|
+
...(error instanceof FilamentSlotsError ? {
|
|
5315
|
+
filament_slots: { colours: error.colours, slots: error.slots },
|
|
5316
|
+
slicer_report: { failed: true, message: error.plain, slicer_message: `${error.colours} filament colours were supplied for ${error.slots} filament slots.` },
|
|
5317
|
+
} : {}),
|
|
5286
5318
|
};
|
|
5287
5319
|
|
|
5288
5320
|
// MCP clients validate structuredContent against a declared outputSchema even on
|
package/src/refusal.ts
CHANGED
|
@@ -12,8 +12,11 @@ import { AsyncLocalStorage } from "node:async_hooks";
|
|
|
12
12
|
* - printer-upload-failed: the print file didn't reach the printer, so no print command was sent.
|
|
13
13
|
* - slicer-waiting-on-dialog: the slicer stopped working (no CPU, no output) as it does while a window waits for an
|
|
14
14
|
* answer, and was stopped; nothing was sliced or sent. Not the slicer's verdict on the model: no slicer_report.
|
|
15
|
+
* - needs-more-filaments: the design is in more colours than there are filaments to slice it with (a two-colour 3MF on
|
|
16
|
+
* a printer with no AMS loaded); nothing was sliced. structuredContent.filament_slots says how many of each, and
|
|
17
|
+
* slicer_report.message the plain answer a client shows (scan-to-make #858, the DAD pass).
|
|
15
18
|
*/
|
|
16
|
-
export const REFUSAL_CODES = ["printer-command-rejected", "printer-not-ready", "printer-upload-failed", "slicer-waiting-on-dialog"] as const;
|
|
19
|
+
export const REFUSAL_CODES = ["printer-command-rejected", "printer-not-ready", "printer-upload-failed", "slicer-waiting-on-dialog", "needs-more-filaments"] as const;
|
|
17
20
|
export type RefusalCode = (typeof REFUSAL_CODES)[number];
|
|
18
21
|
|
|
19
22
|
export class PrinterRefusal extends Error {
|
|
@@ -46,3 +49,18 @@ export function printOutcome(error: unknown): PrintOutcome {
|
|
|
46
49
|
if (error instanceof PrinterRefusal && error.code === "printer-command-rejected") return "rejected";
|
|
47
50
|
return printDispatch.getStore()?.attempted === false ? "not-sent" : "unknown";
|
|
48
51
|
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* More filament colours than filament slots to slice with: the plain answer a person is shown, and the counts. The
|
|
55
|
+
* DAD pass sliced its two-colour 3MF for a P1S with no AMS loaded and got only "2 filament colours were supplied for
|
|
56
|
+
* 1 filament slots".
|
|
57
|
+
*/
|
|
58
|
+
export class FilamentSlotsError extends PrinterRefusal {
|
|
59
|
+
readonly plain: string;
|
|
60
|
+
constructor(readonly colours: number, readonly slots: number) {
|
|
61
|
+
const plain = `This design is in ${colours} colours, but only ${slots} filament${slots === 1 ? " is" : "s are"} available to print it. It needs a printer with an AMS loaded with ${colours} colours, or it can print in one colour.`;
|
|
62
|
+
super("needs-more-filaments", `${plain}\nThe slicer setup said: ${colours} filament colours were supplied for ${slots} filament slots.`);
|
|
63
|
+
this.name = "FilamentSlotsError";
|
|
64
|
+
this.plain = plain;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
import { promises as fs } from "node:fs";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Where a slice's "floating regions" warning comes from. Bambu Studio and OrcaSlicer say only that an object "has
|
|
5
|
+
* floating regions" (a layer island with nothing under it); a design worker then rebuilt and re-sliced six times
|
|
6
|
+
* chasing specks it could not see (scan-to-make #859, pass B). This finds them in the STL itself: each downward-facing
|
|
7
|
+
* low point of the surface that starts above the plate, with how far its surface hangs below the point where it joins
|
|
8
|
+
* something lower (its depth). The same mesh, the same places, so one fix can be aimed.
|
|
9
|
+
*
|
|
10
|
+
* Coordinates are the STL's own, in millimetres, with z measured from the model's lowest point (where the slicer
|
|
11
|
+
* puts the plate). Shared by bambu-printer-mcp and mcp-3D-printer-server.
|
|
12
|
+
*/
|
|
13
|
+
/** One floating region: z where it starts (its lowest point), how far it hangs, and the box of what hangs (STL x, y; z from the model's lowest point). */
|
|
14
|
+
export interface FloatingRegion { z: number; depth_mm: number; box_mm: { min: [number, number, number]; max: [number, number, number] } }
|
|
15
|
+
export interface FloatingRegions {
|
|
16
|
+
/** The deepest regions first, at most `limit`; z from the model's lowest point. */
|
|
17
|
+
regions: FloatingRegion[];
|
|
18
|
+
/** All the low points found, before the limit. */
|
|
19
|
+
count: number;
|
|
20
|
+
/** The STL's lowest z, which the slicer moves to the plate. */
|
|
21
|
+
model_min_z: number;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** About 500k binary triangles: the search runs between slicer calls, on the server's own thread. */
|
|
25
|
+
const MAX_BYTES = 25 * 1024 * 1024;
|
|
26
|
+
|
|
27
|
+
/** Triangles of a binary or ASCII STL, as a flat array of 9 numbers each. */
|
|
28
|
+
export function stlTriangles(bytes: Buffer): Float64Array {
|
|
29
|
+
const ascii = /^\s*solid\b/.test(bytes.subarray(0, 256).toString("latin1")) && bytes.includes("facet");
|
|
30
|
+
if (bytes.length >= 84) {
|
|
31
|
+
const n = bytes.readUInt32LE(80);
|
|
32
|
+
// Binary: exactly sized, or sized with trailing bytes some exporters add, unless it reads as ASCII.
|
|
33
|
+
if (84 + n * 50 === bytes.length || (84 + n * 50 < bytes.length && !ascii)) {
|
|
34
|
+
const out = new Float64Array(n * 9);
|
|
35
|
+
for (let i = 0; i < n; i++) for (let k = 0; k < 9; k++) out[i * 9 + k] = bytes.readFloatLE(84 + i * 50 + 12 + k * 4);
|
|
36
|
+
return out;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
const text = bytes.toString("latin1");
|
|
40
|
+
if (!/^\s*solid/.test(text)) throw new Error("not an STL file");
|
|
41
|
+
const values: number[] = [];
|
|
42
|
+
for (const match of text.matchAll(/vertex\s+(\S+)\s+(\S+)\s+(\S+)/g)) values.push(Number(match[1]), Number(match[2]), Number(match[3]));
|
|
43
|
+
if (!values.length || values.length % 9 || values.some(v => !Number.isFinite(v))) throw new Error("malformed ASCII STL");
|
|
44
|
+
return Float64Array.from(values);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* The floating low points of a triangle mesh. A sweep from the bottom up joins vertices into connected pieces of the
|
|
49
|
+
* surface below each height; a piece that starts above `plate_mm` is a low point, and its depth is how far up it
|
|
50
|
+
* reaches before it joins a piece that started lower (or the whole of it, if it never does: a body in mid-air).
|
|
51
|
+
* Only low points whose surface faces down count (the floor of a bowl or of a closed void faces up), and only
|
|
52
|
+
* those deeper than `min_depth_mm` (about one layer: shallower bumps fall inside the layer that already has material).
|
|
53
|
+
*/
|
|
54
|
+
export function floatingRegions(triangles: Float64Array, options: { plate_mm?: number; min_depth_mm?: number; merge_mm?: number; limit?: number } = {}): FloatingRegions {
|
|
55
|
+
const plate = options.plate_mm ?? 0.3, minDepth = options.min_depth_mm ?? 0.2, merge = options.merge_mm ?? 2, limit = options.limit ?? 12;
|
|
56
|
+
const nTri = Math.floor(triangles.length / 9);
|
|
57
|
+
// Weld the triangle soup by position.
|
|
58
|
+
const index = new Map<string, number>();
|
|
59
|
+
const xyz: number[] = [];
|
|
60
|
+
const corner = new Int32Array(nTri * 3);
|
|
61
|
+
for (let i = 0; i < nTri * 3; i++) {
|
|
62
|
+
const x = triangles[i * 3], y = triangles[i * 3 + 1], z = triangles[i * 3 + 2];
|
|
63
|
+
const key = `${Math.round(x * 1e4)},${Math.round(y * 1e4)},${Math.round(z * 1e4)}`;
|
|
64
|
+
let v = index.get(key);
|
|
65
|
+
if (v === undefined) { v = xyz.length / 3; index.set(key, v); xyz.push(x, y, z); }
|
|
66
|
+
corner[i] = v;
|
|
67
|
+
}
|
|
68
|
+
const nV = xyz.length / 3;
|
|
69
|
+
if (!nV) return { regions: [], count: 0, model_min_z: 0 };
|
|
70
|
+
let minZ = Infinity;
|
|
71
|
+
for (let v = 0; v < nV; v++) minZ = Math.min(minZ, xyz[v * 3 + 2]);
|
|
72
|
+
// Neighbours, and each vertex's area-weighted normal z (downward-facing where negative).
|
|
73
|
+
const neighbours: number[][] = Array.from({ length: nV }, () => []);
|
|
74
|
+
const normalZ = new Float64Array(nV);
|
|
75
|
+
for (let t = 0; t < nTri; t++) {
|
|
76
|
+
const a = corner[t * 3], b = corner[t * 3 + 1], c = corner[t * 3 + 2];
|
|
77
|
+
if (a === b || b === c || a === c) continue;
|
|
78
|
+
const ux = xyz[b * 3] - xyz[a * 3], uy = xyz[b * 3 + 1] - xyz[a * 3 + 1];
|
|
79
|
+
const vx = xyz[c * 3] - xyz[a * 3], vy = xyz[c * 3 + 1] - xyz[a * 3 + 1];
|
|
80
|
+
const nz = ux * vy - uy * vx; // twice the area times the normal's z
|
|
81
|
+
for (const [p, q] of [[a, b], [b, c], [c, a]]) { neighbours[p].push(q); neighbours[q].push(p); }
|
|
82
|
+
normalZ[a] += nz; normalZ[b] += nz; normalZ[c] += nz;
|
|
83
|
+
}
|
|
84
|
+
// Union-find over vertices in rising z; each piece remembers its lowest vertex.
|
|
85
|
+
const order = Array.from({ length: nV }, (_, i) => i).sort((p, q) => xyz[p * 3 + 2] - xyz[q * 3 + 2] || p - q);
|
|
86
|
+
const parent = new Int32Array(nV).fill(-1);
|
|
87
|
+
const lowest = new Int32Array(nV);
|
|
88
|
+
const find = (v: number): number => { while (parent[v] !== v) { parent[v] = parent[parent[v]]; v = parent[v]; } return v; };
|
|
89
|
+
const z = (v: number) => xyz[v * 3 + 2];
|
|
90
|
+
const found: { v: number; depth: number }[] = [];
|
|
91
|
+
const consider = (root: number, depth: number) => {
|
|
92
|
+
const low = lowest[root];
|
|
93
|
+
if (z(low) - minZ > plate && depth >= minDepth && normalZ[low] < 0)
|
|
94
|
+
found.push({ v: low, depth });
|
|
95
|
+
};
|
|
96
|
+
for (const v of order) {
|
|
97
|
+
parent[v] = v; lowest[v] = v;
|
|
98
|
+
for (const n of neighbours[v]) {
|
|
99
|
+
if (parent[n] < 0) continue;
|
|
100
|
+
const a = find(v), b = find(n);
|
|
101
|
+
if (a === b) continue;
|
|
102
|
+
// The piece that started higher ends here: it hung down by the height climbed to reach this join.
|
|
103
|
+
const [keep, end] = z(lowest[a]) <= z(lowest[b]) ? [a, b] : [b, a];
|
|
104
|
+
consider(end, z(v) - z(lowest[end]));
|
|
105
|
+
parent[end] = keep;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
// Pieces that never joined a lower one: separate bodies; the one holding the lowest point sits on the plate.
|
|
109
|
+
const tops = new Map<number, number>();
|
|
110
|
+
for (let v = 0; v < nV; v++) { const r = find(v); tops.set(r, Math.max(tops.get(r) ?? -Infinity, z(v))); }
|
|
111
|
+
for (const [root, top] of tops) consider(root, top - z(lowest[root]));
|
|
112
|
+
/**
|
|
113
|
+
* The box of what hangs: the surface walked from the low point through every vertex below the height where it joins
|
|
114
|
+
* the rest, with each edge that crosses that height cut there. The same for any facet order (Codex review, #169).
|
|
115
|
+
*/
|
|
116
|
+
const hanging = (start: number, top: number) => {
|
|
117
|
+
const lo = [Infinity, Infinity, Infinity], hi = [-Infinity, -Infinity, -Infinity];
|
|
118
|
+
const add = (p: number[]) => { for (let k = 0; k < 3; k++) { lo[k] = Math.min(lo[k], p[k]); hi[k] = Math.max(hi[k], p[k]); } };
|
|
119
|
+
const seen = new Uint8Array(nV);
|
|
120
|
+
const stack = [start];
|
|
121
|
+
seen[start] = 1;
|
|
122
|
+
while (stack.length) {
|
|
123
|
+
const u = stack.pop()!;
|
|
124
|
+
const pu = [xyz[u * 3], xyz[u * 3 + 1], xyz[u * 3 + 2]];
|
|
125
|
+
add(pu);
|
|
126
|
+
for (const w of neighbours[u]) {
|
|
127
|
+
if (z(w) < top) { if (!seen[w]) { seen[w] = 1; stack.push(w); } continue; }
|
|
128
|
+
const f = (top - pu[2]) / (z(w) - pu[2] || 1);
|
|
129
|
+
add([pu[0] + (xyz[w * 3] - pu[0]) * f, pu[1] + (xyz[w * 3 + 1] - pu[1]) * f, top]);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
return { lo, hi };
|
|
133
|
+
};
|
|
134
|
+
// Merge low points within merge_mm of a deeper one; deepest first.
|
|
135
|
+
found.sort((p, q) => q.depth - p.depth);
|
|
136
|
+
const kept: typeof found = [];
|
|
137
|
+
for (const f of found) {
|
|
138
|
+
const near = kept.some(k => Math.hypot(xyz[k.v * 3] - xyz[f.v * 3], xyz[k.v * 3 + 1] - xyz[f.v * 3 + 1], z(k.v) - z(f.v)) <= merge);
|
|
139
|
+
if (!near) kept.push(f);
|
|
140
|
+
}
|
|
141
|
+
const r2 = (n: number) => Math.round(n * 100) / 100;
|
|
142
|
+
return {
|
|
143
|
+
regions: kept.slice(0, limit).map(({ v, depth }) => ({ v, depth, ...hanging(v, z(v) + depth) })).map(({ v, depth, lo: l, hi: h }) => ({
|
|
144
|
+
z: r2(z(v) - minZ), depth_mm: r2(depth),
|
|
145
|
+
box_mm: { min: [r2(l[0]), r2(l[1]), r2(l[2] - minZ)] as [number, number, number], max: [r2(h[0]), r2(h[1]), r2(h[2] - minZ)] as [number, number, number] },
|
|
146
|
+
})),
|
|
147
|
+
count: kept.length,
|
|
148
|
+
model_min_z: r2(minZ),
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** The slicer said a model has floating regions or small islands: a cosmetic warning this rule bounds. */
|
|
153
|
+
export function isFloatingWarning(message: string | undefined): boolean {
|
|
154
|
+
return !!message && /floating regions?|small islands?|isolated islands?/i.test(message);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
export const SLICE_WARNING_RULE = "A cosmetic warning (floating regions, small islands) gets one targeted fix and one re-slice, then stops: if it remains, report it in the result or slice with supports on. Do not rebuild and re-slice to chase it. A region that is a separate body in mid-air, or on a feature that carries load or makes a fit, is not cosmetic: fix that one properly.";
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* What slice_stl adds to a slice that worked but warned about floating regions: the rule above, and where the
|
|
161
|
+
* regions are when the input is an STL the slicer did not turn (orient, rotate). Never throws: a location it
|
|
162
|
+
* cannot find is left out, with why.
|
|
163
|
+
*/
|
|
164
|
+
export async function floatingWarningFacts(
|
|
165
|
+
report: { failed: boolean; message?: string } | undefined,
|
|
166
|
+
modelPath: string,
|
|
167
|
+
turned: boolean,
|
|
168
|
+
): Promise<Record<string, unknown>> {
|
|
169
|
+
if (!report || report.failed || !isFloatingWarning(report.message)) return {};
|
|
170
|
+
const base = { next: SLICE_WARNING_RULE };
|
|
171
|
+
if (!/\.stl$/i.test(modelPath)) return { ...base, floating_regions_unlocated: "Only an STL input is located; this was a 3MF." };
|
|
172
|
+
if (turned) return { ...base, floating_regions_unlocated: "The slicer turned or scaled the model (orient, rotate or scale), so the STL's own coordinates would mislead." };
|
|
173
|
+
try {
|
|
174
|
+
const stat = await fs.stat(modelPath);
|
|
175
|
+
if (stat.size > MAX_BYTES) return { ...base, floating_regions_unlocated: "The STL is too large to search." };
|
|
176
|
+
const located = floatingRegions(stlTriangles(await fs.readFile(modelPath)));
|
|
177
|
+
return {
|
|
178
|
+
...base,
|
|
179
|
+
floating_regions: {
|
|
180
|
+
...located,
|
|
181
|
+
frame: "Each region starts at z and hangs depth_mm below where it joins the rest; box_mm bounds what hangs. x and y are the STL's own millimetres; z is millimetres above its lowest point, which the slicer puts on the plate.",
|
|
182
|
+
},
|
|
183
|
+
};
|
|
184
|
+
} catch (error) {
|
|
185
|
+
return { ...base, floating_regions_unlocated: `Could not read the STL: ${error instanceof Error ? error.message : String(error)}` };
|
|
186
|
+
}
|
|
187
|
+
}
|
|
@@ -24,6 +24,7 @@
|
|
|
24
24
|
* fail loud rather than producing dangerous gcode for hardware we don't own.
|
|
25
25
|
*/
|
|
26
26
|
|
|
27
|
+
import { FilamentSlotsError } from "../refusal.js";
|
|
27
28
|
import fs from "node:fs/promises";
|
|
28
29
|
import { existsSync, realpathSync } from "node:fs";
|
|
29
30
|
import path from "node:path";
|
|
@@ -736,6 +737,8 @@ export async function flattenForCli(opts: FlattenOptions): Promise<FlattenedProf
|
|
|
736
737
|
normalizeForCli(processFlat, "process", opts.processLeaf);
|
|
737
738
|
filamentFlats.forEach((f, i) => normalizeForCli(f, "filament", opts.filamentLeaves[i]));
|
|
738
739
|
if (opts.filamentColours && opts.filamentColours.length !== filamentFlats.length) {
|
|
740
|
+
// More colours than slots is a design the loaded filaments can't print in its colours: said plainly (#858).
|
|
741
|
+
if (opts.filamentColours.length > filamentFlats.length) throw new FilamentSlotsError(opts.filamentColours.length, filamentFlats.length);
|
|
739
742
|
throw new Error(
|
|
740
743
|
`${opts.filamentColours.length} filament colours were supplied for ${filamentFlats.length} filament slots.`
|
|
741
744
|
);
|
package/src/tool-annotations.ts
CHANGED
|
@@ -83,6 +83,8 @@ export const TOOL_ANNOTATIONS: Record<string, ToolAnnotations> = {
|
|
|
83
83
|
slice_with_template: hints(false, true, false, true),
|
|
84
84
|
// New 3MF at a caller-chosen path; never overwrites, so a repeat fails and changes nothing.
|
|
85
85
|
counterpart_make_3mf: hints(false, false, true, false),
|
|
86
|
+
// A new folder of STLs each call, inside a caller-chosen folder; never overwrites.
|
|
87
|
+
counterpart_part_meshes: hints(false, false, false, false),
|
|
86
88
|
// Copies into the template registry, replacing a template of the same name.
|
|
87
89
|
save_template: hints(false, true, true, false),
|
|
88
90
|
// Replaces BAMBU_DEFAULT_CONNECTION_MODE/TYPE in .env and in this process.
|