bambu-printer-mcp 1.1.72 → 1.1.73

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.
@@ -36,3 +36,9 @@ export declare function trayColour(rawStatus: any, tray: number): string | undef
36
36
  * Filament-map nozzle 1 (left) is cloud nozzle 1 and 2 (right) is 0 (CloudTaskNozzleId).
37
37
  */
38
38
  export declare function studioAmsMappingInfo(filaments: ProjectFilament[], mapping: number[], colourOfTray: (tray: number) => string | undefined): Array<Record<string, unknown>>;
39
+ /**
40
+ * A project-level ams_mapping as Bambu Studio sends it: the caller's tray for each filament the selected plate prints,
41
+ * -1 for every project filament it doesn't (SelectMachineDialog::get_ams_mapping_result, SelectMachine.cpp:1463-1500,
42
+ * maps only the plate's own filaments). A tray for an unused filament is never sent to the printer.
43
+ */
44
+ export declare function studioAmsMapping(mapping: number[], usedPositions: number[]): number[];
@@ -125,3 +125,12 @@ export function studioAmsMappingInfo(filaments, mapping, colourOfTray) {
125
125
  };
126
126
  });
127
127
  }
128
+ /**
129
+ * A project-level ams_mapping as Bambu Studio sends it: the caller's tray for each filament the selected plate prints,
130
+ * -1 for every project filament it doesn't (SelectMachineDialog::get_ams_mapping_result, SelectMachine.cpp:1463-1500,
131
+ * maps only the plate's own filaments). A tray for an unused filament is never sent to the printer.
132
+ */
133
+ export function studioAmsMapping(mapping, usedPositions) {
134
+ const used = new Set(usedPositions);
135
+ return mapping.map((tray, position) => used.has(position) ? tray : -1);
136
+ }
@@ -1,3 +1,4 @@
1
+ import { type PlateFilament } from "./plate-filaments.js";
1
2
  export interface ModelPlate {
2
3
  /** Zero-based, as inspect_print_file's plate_index; slice_stl's slice_plate is index + 1. */
3
4
  index: number;
@@ -14,6 +15,12 @@ export interface ModelPlate {
14
15
  }[];
15
16
  /** The file already holds this plate's G-code. */
16
17
  sliced: boolean;
18
+ /**
19
+ * The project filaments this plate prints with, and only those (counterpart/1): what a client asks the person to
20
+ * choose spools for. From the slice when the file holds one (plate_N.json filament_ids), otherwise worked out as
21
+ * Bambu Studio does for the objects on this plate (see plate-filaments.ts). Filaments of other plates never appear.
22
+ */
23
+ filaments: PlateFilament[];
17
24
  /** The plate's own preview from the file (Metadata/plate_N.png), when asked for and present. */
18
25
  thumbnail_png_base64?: string;
19
26
  }
@@ -23,6 +30,11 @@ export interface ModelPlates {
23
30
  title?: string;
24
31
  designer?: string;
25
32
  licence?: string;
33
+ /**
34
+ * Every filament the project declares (project_settings.config), used on a plate or not, from 1: slice_stl takes one
35
+ * load_filaments profile per declared filament. Empty for a 3MF that declares none.
36
+ */
37
+ project_filaments: PlateFilament[];
26
38
  }
27
39
  export declare function listModelPlates(filePath: string, options?: {
28
40
  thumbnails?: boolean;
@@ -8,6 +8,7 @@
8
8
  * is one plate. Only bounded metadata is read; nothing is extracted or run.
9
9
  */
10
10
  import { readSafe3mfArchive } from "../safety/archive.js";
11
+ import { plateFilaments } from "./plate-filaments.js";
11
12
  /** For the settings and plate files; the model file can be large and is only scanned. */
12
13
  const MAX_METADATA_BYTES = 8 * 1024 * 1024;
13
14
  const MAX_THUMBNAIL_BYTES = 2 * 1024 * 1024;
@@ -34,7 +35,7 @@ export async function listModelPlates(filePath, options = {}) {
34
35
  throw new Error("That file is not a 3MF model.");
35
36
  // An element named `tag`, plain or with a namespace prefix (<item …>, <p:item …>).
36
37
  const has = (tag) => !!modelBytes && [" ", ">", "/", "\n", "\r", "\t"].some(end => modelBytes.includes(`<${tag}${end}`) || modelBytes.includes(`:${tag}${end}`));
37
- const result = { plate_count: 0, plates: [] };
38
+ const result = { plate_count: 0, plates: [], project_filaments: [] };
38
39
  const metadata = new Map([...head.matchAll(/<metadata\s+name="([^"]+)"[^>]*>([^<]*)<\/metadata>/g)].map(match => [match[1], words(match[2])]));
39
40
  if (metadata.get("Title"))
40
41
  result.title = metadata.get("Title");
@@ -48,6 +49,7 @@ export async function listModelPlates(filePath, options = {}) {
48
49
  return [match[1], words(name?.[1] ?? "")];
49
50
  }));
50
51
  const plates = new Map();
52
+ const layouts = new Map();
51
53
  // A plate number out of range is skipped, as a slicer would not show it.
52
54
  const valid = (number) => Number.isSafeInteger(number) && number >= 1 && number <= MAX_PLATES;
53
55
  for (const match of settings.matchAll(/<plate\b[^>]*>([\s\S]*?)<\/plate>/g)) {
@@ -64,7 +66,13 @@ export async function listModelPlates(filePath, options = {}) {
64
66
  return object !== undefined && Number.isSafeInteger(identify) && identify > 0
65
67
  ? [{ identify_id: identify, name: objects.get(object) ?? "" }] : [];
66
68
  }).slice(0, MAX_INSTANCES_PER_PLATE);
67
- plates.set(number, { index: number - 1, name: words(name?.[1] ?? "") || `Plate ${number}`, sliced: false, instances,
69
+ layouts.set(number, { number, objectIds: [...match[1].matchAll(/<metadata\s+key="object_id"\s+value="(\d+)"/g)].map(item => item[1]),
70
+ instances: [...match[1].matchAll(/<model_instance>([\s\S]*?)<\/model_instance>/g)].flatMap(instance => {
71
+ const objectId = /<metadata\s+key="object_id"\s+value="(\d+)"/.exec(instance[1])?.[1];
72
+ const instanceId = Number(/<metadata\s+key="instance_id"\s+value="(\d+)"/.exec(instance[1])?.[1] ?? 0);
73
+ return objectId ? [{ objectId, instanceId }] : [];
74
+ }) });
75
+ plates.set(number, { index: number - 1, name: words(name?.[1] ?? "") || `Plate ${number}`, sliced: false, instances, filaments: [],
68
76
  objects: [...match[1].matchAll(/<metadata\s+key="object_id"\s+value="(\d+)"/g)].flatMap(item => objects.get(item[1]) ? [objects.get(item[1])] : []) });
69
77
  }
70
78
  for (const name of Object.keys(zip.files)) {
@@ -74,12 +82,17 @@ export async function listModelPlates(filePath, options = {}) {
74
82
  const number = Number(match[1]);
75
83
  if (!valid(number))
76
84
  continue;
77
- const plate = plates.get(number) ?? { index: number - 1, name: `Plate ${number}`, objects: [], instances: [], sliced: false };
85
+ const plate = plates.get(number) ?? { index: number - 1, name: `Plate ${number}`, objects: [], instances: [], sliced: false, filaments: [] };
86
+ const layout = layouts.get(number) ?? { number, objectIds: [] };
87
+ layouts.set(number, layout);
78
88
  if (match[2] === "gcode")
79
89
  plate.sliced = true;
80
90
  else {
81
91
  try {
82
92
  const value = JSON.parse(await text(name));
93
+ // Studio's record of the filaments this plate's slice uses (0-based project positions).
94
+ if (Array.isArray(value.filament_ids))
95
+ layout.slicedFilamentIds = value.filament_ids.filter((id) => Number.isInteger(id) && id >= 0 && id < 64);
83
96
  if (Array.isArray(value.bbox_objects))
84
97
  plate.objects = value.bbox_objects
85
98
  .flatMap(object => typeof object.name === "string" && object.name !== "wipe_tower" ? [words(object.name)] : []).slice(0, 200);
@@ -90,8 +103,11 @@ export async function listModelPlates(filePath, options = {}) {
90
103
  }
91
104
  result.plates = [...plates.values()].sort((a, b) => a.index - b.index);
92
105
  // A standard single-build 3MF has no Bambu plate metadata: it is one plate.
93
- if (!result.plates.length)
94
- result.plates.push({ index: 0, name: "Plate 1", objects: [], instances: [], sliced: false });
106
+ if (!result.plates.length) {
107
+ result.plates.push({ index: 0, name: "Plate 1", objects: [], instances: [], sliced: false, filaments: [] });
108
+ // Without plates every object is on the one plate.
109
+ layouts.set(1, { number: 1, objectIds: [...settings.matchAll(/<object\b[^>]*\bid="(\d+)"/g)].map(match => match[1]) });
110
+ }
95
111
  const geometry = has("item") && (has("mesh") || has("component"));
96
112
  if (!geometry) {
97
113
  // A sliced-only file (previews and G-code, no model): only its sliced plates can print.
@@ -99,6 +115,14 @@ export async function listModelPlates(filePath, options = {}) {
99
115
  if (!result.plates.length)
100
116
  throw new Error("This 3MF has previews and settings but no model or printable plate.");
101
117
  }
118
+ // A slice's G-code without its plate_N.json gives no filament list: the derivation stands.
119
+ // A model file too large to read whole: its resources come first and its build items last (a plain 3MF).
120
+ const modelText = !modelBytes ? "" : modelBytes.length <= 64 * 1024 * 1024 ? modelBytes.toString("utf8")
121
+ : `${head}${modelBytes.subarray(-1024 * 1024).toString("utf8")}`;
122
+ const filaments = await plateFilaments(zip, settings, modelText, result.plates.map(plate => layouts.get(plate.index + 1) ?? { number: plate.index + 1, objectIds: [] }));
123
+ for (const plate of result.plates)
124
+ plate.filaments = filaments.plates.get(plate.index + 1) ?? [];
125
+ result.project_filaments = filaments.project;
102
126
  if (options.thumbnails)
103
127
  for (const plate of result.plates) {
104
128
  const file = zip.file(`Metadata/plate_${plate.index + 1}.png`);
@@ -0,0 +1,80 @@
1
+ /**
2
+ * The project filaments each plate of a Bambu Studio / OrcaSlicer 3MF prints with, worked out the way Bambu Studio
3
+ * does it (v02.08.02.61), so a client asks the person to choose spools only for the filaments that plate uses.
4
+ *
5
+ * - A sliced plate: Studio's own record, Metadata/plate_N.json `filament_ids` (0-based), written from the slice.
6
+ * - An unsliced plate: PartPlate::get_extruders_under_cli (src/slic3r/GUI/PartPlate.cpp:1298-1420) over the objects
7
+ * with an instance on the plate (model_settings.config <model_instance>; an instance with printable="0" in the
8
+ * 3dmodel.model build is skipped, PartPlate.cpp:1321):
9
+ * - each volume's ModelVolume::get_extruders (src/libslic3r/Model.cpp:3357-3412): negative parts, support blockers
10
+ * and enforcers print nothing; the volume's painted states (mmu_segmentation, `paint_color`); the volume's own
11
+ * extruder (ModelVolume::extruder_id, Model.cpp:3295-3306: the part's, else the object's, else 1) unless paint
12
+ * covers every facet of a model part; and the volume's wall/solid/sparse infill filaments, else the object's;
13
+ * - the object's layer-range extruders (Metadata/layer_config_ranges.xml, by 1-based model object index);
14
+ * - the object's feature filaments when separate_filaments_for_features is on;
15
+ * - the support and support-interface filaments when the object (or the project) prints support or a raft;
16
+ * - the plate's tool changes (Metadata/custom_gcode_per_layer.xml, CustomGCode::ToolChange = 2,
17
+ * PartPlate.cpp:1263-1274).
18
+ * Painting is decoded as FacetsAnnotation::set_triangle_from_string (Model.cpp:4631-4650) and
19
+ * TriangleSelector::deserialize (src/libslic3r/TriangleSelector.cpp:2111-2139) read it; this is a reimplementation
20
+ * from that documented behaviour, not Studio's code.
21
+ *
22
+ * Only bounded metadata and mesh text are read; nothing is extracted or run.
23
+ */
24
+ import type JSZip from "jszip";
25
+ export interface PlateFilament {
26
+ /** 1-based project filament number: slice_stl's load_filaments/filament_colours position, print_3mf's ams_mapping index + 1. */
27
+ index: number;
28
+ /** As the project declares it (project_settings.config filament_colour), #RRGGBB. */
29
+ colour?: string;
30
+ /** project_settings.config filament_type. */
31
+ material?: string;
32
+ /** project_settings.config filament_ids (Bambu's filament id, e.g. GFA00). */
33
+ filament_id?: string;
34
+ /** The first part (else object) on this plate that prints with it; absent for support, painting or tool changes only. */
35
+ name?: string;
36
+ }
37
+ type Settings = Map<string, string>;
38
+ interface Part {
39
+ id: string;
40
+ subtype: string;
41
+ name: string;
42
+ settings: Settings;
43
+ }
44
+ interface ObjectEntry {
45
+ id: string;
46
+ name: string;
47
+ settings: Settings;
48
+ parts: Part[];
49
+ }
50
+ /** model_settings.config objects with their own settings and parts (parts never nest). */
51
+ export declare function readModelObjects(settings: string): ObjectEntry[];
52
+ /**
53
+ * The filament states a painted facet string holds (0 is "the volume's own filament"). Studio's string is hex,
54
+ * read last character first, each digit four bits low bit first, so the nibbles are the digits in reverse order.
55
+ * Each node is one nibble: two low bits are the split-side count (children = sides + 1); a leaf's state is the high
56
+ * two bits, or, when both are set, 3 + the next nibble + 15 for every preceding 0b1111 nibble.
57
+ */
58
+ export declare function paintedStates(paint: string): number[];
59
+ export interface PlateLayout {
60
+ /** 1-based plate number. */
61
+ number: number;
62
+ /** model_settings.config object ids with an instance on this plate, in plate order. */
63
+ objectIds: string[];
64
+ /** Each copy on the plate: its object and that object's instance_id (model_settings.config <model_instance>). */
65
+ instances?: {
66
+ objectId: string;
67
+ instanceId: number;
68
+ }[];
69
+ /** Metadata/plate_N.json filament_ids (0-based) when the file holds this plate's slice. */
70
+ slicedFilamentIds?: number[];
71
+ }
72
+ /**
73
+ * The filaments each plate prints with, keyed by plate number. `settings` is model_settings.config, `model` the root
74
+ * 3D/3dmodel.model text.
75
+ */
76
+ export declare function plateFilaments(zip: JSZip, settings: string, model: string, plates: PlateLayout[]): Promise<{
77
+ plates: Map<number, PlateFilament[]>;
78
+ project: PlateFilament[];
79
+ }>;
80
+ export {};
@@ -0,0 +1,325 @@
1
+ const MAX_TEXT_BYTES = 8 * 1024 * 1024;
2
+ const MAX_MESH_BYTES = 64 * 1024 * 1024;
3
+ const MAX_MESH_TOTAL = 256 * 1024 * 1024;
4
+ const MAX_FILAMENT = 64;
5
+ const words = (value) => value
6
+ .replace(/&(?:amp|lt|gt|quot|apos);/g, entity => ({ "&amp;": "&", "&lt;": "<", "&gt;": ">", "&quot;": "\"", "&apos;": "'" }[entity]))
7
+ .replace(/[\u0000-\u001f\u007f]/g, " ").trim().slice(0, 256);
8
+ const metadataOf = (block) => new Map([...block.matchAll(/<metadata\s+key="([^"]+)"\s+value="([^"]*)"\s*\/?>/g)].map(match => [match[1], match[2]]));
9
+ /** model_settings.config objects with their own settings and parts (parts never nest). */
10
+ export function readModelObjects(settings) {
11
+ return [...settings.matchAll(/<object\b[^>]*\bid="(\d+)"[^>]*>([\s\S]*?)<\/object>/g)].map(match => {
12
+ const parts = [...match[2].matchAll(/<part\b([^>]*)>([\s\S]*?)<\/part>/g)].map(part => {
13
+ const own = metadataOf(part[2]);
14
+ return { id: /\bid="(\d+)"/.exec(part[1])?.[1] ?? "", subtype: /\bsubtype="([^"]+)"/.exec(part[1])?.[1] ?? "normal_part", name: words(own.get("name") ?? ""), settings: own };
15
+ });
16
+ const own = metadataOf(match[2].replace(/<part\b[^>]*>[\s\S]*?<\/part>/g, ""));
17
+ return { id: match[1], name: words(own.get("name") ?? ""), settings: own, parts };
18
+ });
19
+ }
20
+ /** An integer setting (Studio stores "0"/"1"/"3" strings; a project list keeps its first value). */
21
+ function intOf(value) {
22
+ const first = Array.isArray(value) ? value[0] : value;
23
+ if (typeof first === "number" && Number.isInteger(first))
24
+ return first;
25
+ if (typeof first !== "string" || !/^\s*-?\d+\s*$/.test(first))
26
+ return undefined;
27
+ return Number(first);
28
+ }
29
+ function boolOf(value) {
30
+ const first = Array.isArray(value) ? value[0] : value;
31
+ if (typeof first === "boolean")
32
+ return first;
33
+ if (typeof first !== "string")
34
+ return undefined;
35
+ if (/^(?:1|true)$/i.test(first.trim()))
36
+ return true;
37
+ if (/^(?:0|false)$/i.test(first.trim()))
38
+ return false;
39
+ return undefined;
40
+ }
41
+ /**
42
+ * The filament states a painted facet string holds (0 is "the volume's own filament"). Studio's string is hex,
43
+ * read last character first, each digit four bits low bit first, so the nibbles are the digits in reverse order.
44
+ * Each node is one nibble: two low bits are the split-side count (children = sides + 1); a leaf's state is the high
45
+ * two bits, or, when both are set, 3 + the next nibble + 15 for every preceding 0b1111 nibble.
46
+ */
47
+ export function paintedStates(paint) {
48
+ const nibbles = [];
49
+ for (let i = paint.length - 1; i >= 0; i--) {
50
+ const digit = Number.parseInt(paint[i], 16);
51
+ if (Number.isNaN(digit))
52
+ return [];
53
+ nibbles.push(digit);
54
+ }
55
+ const states = [];
56
+ let at = 0, pending = 1;
57
+ const next = () => (at < nibbles.length ? nibbles[at++] : undefined);
58
+ while (pending > 0) {
59
+ const code = next();
60
+ if (code === undefined)
61
+ break;
62
+ pending -= 1;
63
+ const sides = code & 0b11;
64
+ if (sides) {
65
+ pending += sides + 1;
66
+ continue;
67
+ }
68
+ if ((code & 0b1100) === 0b1100) {
69
+ let more = 0, value = next();
70
+ while (value === 0b1111) {
71
+ more += 1;
72
+ value = next();
73
+ }
74
+ if (value === undefined)
75
+ break;
76
+ states.push(value + 15 * more + 3);
77
+ }
78
+ else
79
+ states.push(code >> 2);
80
+ }
81
+ return states;
82
+ }
83
+ /**
84
+ * Per component file and sub-object id, the painting of that mesh. Only files that contain painting are read in full.
85
+ */
86
+ async function readPainting(zip, paths) {
87
+ const result = new Map();
88
+ let total = 0;
89
+ for (const path of paths) {
90
+ const file = zip.file(path);
91
+ if (!file)
92
+ continue;
93
+ // A mesh past the read budget is taken as unpainted (its part's own filament), never a failed listing.
94
+ const size = file._data?.uncompressedSize;
95
+ if (size !== undefined && (size > MAX_MESH_BYTES || total + size > MAX_MESH_TOTAL))
96
+ continue;
97
+ const bytes = await file.async("nodebuffer");
98
+ if (bytes.length > MAX_MESH_BYTES || (total += bytes.length) > MAX_MESH_TOTAL)
99
+ continue;
100
+ if (!bytes.includes("paint_color=\""))
101
+ continue;
102
+ const text = bytes.toString("utf8");
103
+ for (const object of text.matchAll(/<object\b[^>]*\bid="(\d+)"[^>]*>([\s\S]*?)<\/object>/g)) {
104
+ const paint = { states: new Set(), ownFilament: false };
105
+ for (const triangle of object[2].matchAll(/<triangle\b([^>]*)\/?>/g)) {
106
+ const value = /\bpaint_color="([0-9A-Fa-f]*)"/.exec(triangle[1])?.[1];
107
+ if (!value) {
108
+ paint.ownFilament = true;
109
+ continue;
110
+ }
111
+ for (const state of paintedStates(value)) {
112
+ if (state === 0)
113
+ paint.ownFilament = true;
114
+ else
115
+ paint.states.add(state);
116
+ }
117
+ }
118
+ result.set(`${path}#${object[1]}`, paint);
119
+ }
120
+ }
121
+ return result;
122
+ }
123
+ function projectFilaments(config) {
124
+ const list = (key) => Array.isArray(config[key]) ? config[key].map(String) : [];
125
+ return { colours: list("filament_colour"), materials: list("filament_type"), ids: list("filament_ids"), config };
126
+ }
127
+ function describe(index, project, name) {
128
+ const colour = /^#?([0-9a-fA-F]{6})(?:[0-9a-fA-F]{2})?$/.exec(project.colours[index - 1]?.trim() ?? "");
129
+ const material = project.materials[index - 1]?.trim().replace(/[\u0000-\u001f\u007f]/g, " ").slice(0, 64);
130
+ const filamentId = project.ids[index - 1]?.trim().replace(/[\u0000-\u001f\u007f]/g, " ").slice(0, 64);
131
+ return { index, ...(colour ? { colour: `#${colour[1].toUpperCase()}` } : {}), ...(material ? { material } : {}),
132
+ ...(filamentId ? { filament_id: filamentId } : {}), ...(name ? { name } : {}) };
133
+ }
134
+ /**
135
+ * The filaments each plate prints with, keyed by plate number. `settings` is model_settings.config, `model` the root
136
+ * 3D/3dmodel.model text.
137
+ */
138
+ export async function plateFilaments(zip, settings, model, plates) {
139
+ const text = async (name) => {
140
+ const file = zip.file(name);
141
+ if (!file)
142
+ return "";
143
+ const bytes = await file.async("nodebuffer");
144
+ if (bytes.length > MAX_TEXT_BYTES)
145
+ throw new Error(`${name} is too large to read.`);
146
+ return bytes.toString("utf8");
147
+ };
148
+ let config = {};
149
+ try {
150
+ const parsed = JSON.parse(await text("Metadata/project_settings.config") || "{}");
151
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed))
152
+ config = parsed;
153
+ }
154
+ catch { /* a project without readable settings declares no filaments */ }
155
+ const project = projectFilaments(config);
156
+ const declared = Math.min(MAX_FILAMENT, Math.max(project.colours.length, project.materials.length, project.ids.length));
157
+ const valid = (index) => index !== undefined && Number.isInteger(index) && index >= 1 && index <= MAX_FILAMENT && (!declared || index <= declared);
158
+ const objects = new Map(readModelObjects(settings).map(object => [object.id, object]));
159
+ // Root objects' components: which sub-object mesh in which file each part is (part id = component objectid).
160
+ const components = new Map();
161
+ for (const object of model.matchAll(/<(?:\w+:)?object\b[^>]*\bid="(\d+)"[^>]*>([\s\S]*?)<\/(?:\w+:)?object>/g)) {
162
+ const parts = new Map();
163
+ for (const component of object[2].matchAll(/<(?:\w+:)?component\b([^>]*)\/?>/g)) {
164
+ const path = /\b(?:\w+:)?path="\/?([^"]+)"/.exec(component[1])?.[1];
165
+ const id = /\bobjectid="(\d+)"/.exec(component[1])?.[1];
166
+ // Studio keys a component by (path, objectid); one without p:path names a mesh object in the root model
167
+ // itself, keyed by the root's empty path (bbs_3mf.cpp:4131-4148, 3891).
168
+ if (id)
169
+ parts.set(id, path || "3D/3dmodel.model");
170
+ }
171
+ if (parts.size)
172
+ components.set(object[1], parts);
173
+ }
174
+ // Model object order (1-based in layer_config_ranges.xml): the build items' order, as Studio creates the objects.
175
+ const buildItems = [...model.matchAll(/<(?:\w+:)?item\b([^>]*)\/?>/g)].map(item => item[1]);
176
+ const order = [...new Set(buildItems.flatMap(item => /\bobjectid="(\d+)"/.exec(item)?.[1] ?? []))];
177
+ // Each build item adds its object's next instance, with its own printable flag (bbs_3mf.cpp:4183-4185, 4375-4380);
178
+ // a plate names its copies by object_id and instance_id (bbs_3mf.cpp:4717-4719), and the CLI skips each copy that
179
+ // isn't printable (PartPlate.cpp:1311-1322).
180
+ const printableItems = new Map();
181
+ for (const item of buildItems) {
182
+ const id = /\bobjectid="(\d+)"/.exec(item)?.[1];
183
+ if (id)
184
+ printableItems.set(id, [...(printableItems.get(id) ?? []), !/\bprintable="(?:0|false)"/.test(item)]);
185
+ }
186
+ const printableCopy = (objectId, instanceId) => {
187
+ const flags = printableItems.get(objectId);
188
+ if (!flags)
189
+ return true;
190
+ return instanceId === undefined ? flags.some(Boolean) : flags[instanceId] !== false;
191
+ };
192
+ const rangeExtruders = new Map();
193
+ const ranges = await text("Metadata/layer_config_ranges.xml");
194
+ for (const object of ranges.matchAll(/<object\b[^>]*\bid="(\d+)"[^>]*>([\s\S]*?)<\/object>/g)) {
195
+ const objectId = order[Number(object[1]) - 1];
196
+ if (!objectId)
197
+ continue;
198
+ // A range's extruder sets all three feature filaments; a range's own feature filament overrides one
199
+ // (apply_to_print_region_config and resolve_filament_value, PrintObject.cpp:3069-3079, 3134-3137).
200
+ rangeExtruders.set(objectId, [...object[2].matchAll(/<option\s+opt_key="(?:extruder|wall_filament|sparse_infill_filament|solid_infill_filament)"\s*>\s*(\d+)\s*<\/option>/g)].map(match => Number(match[1])).filter(id => id > 0));
201
+ }
202
+ const toolChanges = new Map();
203
+ const custom = await text("Metadata/custom_gcode_per_layer.xml");
204
+ for (const plate of custom.matchAll(/<plate>([\s\S]*?)<\/plate>/g)) {
205
+ const id = Number(/<plate_info\b[^>]*\bid="(\d+)"/.exec(plate[1])?.[1]);
206
+ if (!Number.isInteger(id))
207
+ continue;
208
+ toolChanges.set(id, [...plate[1].matchAll(/<layer\b([^>]*)\/?>/g)]
209
+ .filter(layer => /\btype="2"/.test(layer[1]))
210
+ .map(layer => Number(/\bextruder="(\d+)"/.exec(layer[1])?.[1])));
211
+ }
212
+ // Painting only matters for parts on a plate that is not sliced yet.
213
+ const paintPaths = new Set();
214
+ for (const plate of plates)
215
+ if (!plate.slicedFilamentIds)
216
+ for (const objectId of plate.objectIds)
217
+ for (const path of components.get(objectId)?.values() ?? [])
218
+ paintPaths.add(path);
219
+ const painting = await readPainting(zip, paintPaths);
220
+ const global = (key) => intOf(config[key]) ?? 0;
221
+ const FEATURES = ["wall_filament", "sparse_infill_filament", "solid_infill_filament"];
222
+ const result = new Map();
223
+ for (const plate of plates) {
224
+ const used = new Map();
225
+ const add = (index, name) => {
226
+ if (!valid(index))
227
+ return;
228
+ if (!used.has(index) || (!used.get(index) && name))
229
+ used.set(index, name || undefined);
230
+ };
231
+ // An object counts once on a plate when any of its copies there prints.
232
+ const printing = plate.instances?.length
233
+ ? [...new Set(plate.instances.filter(copy => printableCopy(copy.objectId, copy.instanceId)).map(copy => copy.objectId))]
234
+ : plate.objectIds.filter(objectId => printableCopy(objectId));
235
+ for (const objectId of printing) {
236
+ const object = objects.get(objectId);
237
+ if (!object)
238
+ continue;
239
+ const objectInt = (key) => intOf(object.settings.get(key));
240
+ const parts = object.parts.length ? object.parts : [{ id: "", subtype: "normal_part", name: "", settings: new Map() }];
241
+ for (const part of parts) {
242
+ if (["negative_part", "support_blocker", "support_enforcer"].includes(part.subtype))
243
+ continue;
244
+ const partInt = (key) => intOf(part.settings.get(key));
245
+ // What the slicer prints the part with (region_config_from_model_volume, PrintObject.cpp:3105-3150): the
246
+ // project's feature filaments, replaced by the object's and then the part's extruder when one is set
247
+ // (non-zero), then by a feature filament the part, else the object, sets above 0.
248
+ const extruderSet = (partInt("extruder") ?? 0) > 0 || (objectInt("extruder") ?? 0) > 0;
249
+ const ownExtruder = partInt("extruder") || objectInt("extruder") || 1;
250
+ const label = part.name || object.name;
251
+ const path = components.get(objectId)?.get(part.id);
252
+ const paint = path ? painting.get(`${path}#${part.id}`) : undefined;
253
+ for (const state of paint?.states ?? [])
254
+ if (part.subtype === "normal_part")
255
+ add(state, label);
256
+ // A modifier's own filament counts whatever its paint (Model.cpp:3384-3390).
257
+ if (part.subtype !== "normal_part" || !paint || paint.ownFilament) {
258
+ if (extruderSet)
259
+ add(ownExtruder, label);
260
+ // Neither the part nor its object names an extruder: the project's feature filaments print it (each
261
+ // above 0; a project without them prints with filament 1, ModelVolume::extruder_id's default).
262
+ else
263
+ for (const key of FEATURES)
264
+ add(global(key) > 0 ? global(key) : 1, label);
265
+ }
266
+ for (const key of ["wall_filament", "solid_infill_filament", "sparse_infill_filament"]) {
267
+ const own = partInt(key);
268
+ if (own !== undefined) {
269
+ if (own > 0)
270
+ add(own, label);
271
+ }
272
+ else if ((objectInt(key) ?? 0) > 0)
273
+ add(objectInt(key), label);
274
+ }
275
+ // separate_filaments_for_features gates these only in Studio's plate list (PartPlate.cpp:1338-1381): it isn't
276
+ // a slicer setting in 02.08.02.61 (libslic3r never reads it), and the slice applies the part's or object's
277
+ // feature filaments whatever it says (PrintObject.cpp:3124-3150), as the loop above does.
278
+ }
279
+ for (const extruder of rangeExtruders.get(objectId) ?? [])
280
+ add(extruder, object.name);
281
+ // Support and raft as the slice resolves them: each setting the object's own, else the project's, one key at a
282
+ // time (PrintObject::object_config_from_model_object, PrintObject.cpp:3052-3063). Studio's plate list resolves
283
+ // the pair together (PartPlate.cpp:1383-1393), which drops support an object with only a raft override prints.
284
+ const setting = (key) => object.settings.has(key) ? object.settings.get(key) : config[key];
285
+ const support = (boolOf(setting("enable_support")) ?? false) || (intOf(setting("raft_layers")) ?? 0) > 0;
286
+ if (support) {
287
+ // 0 is "default": the support prints with the object's own filament (Print.cpp:490-501).
288
+ add(intOf(setting("support_interface_filament")) || undefined);
289
+ add(intOf(setting("support_filament")) || undefined);
290
+ }
291
+ }
292
+ for (const extruder of toolChanges.get(plate.number) ?? [])
293
+ add(extruder);
294
+ // Objects the settings don't describe (a plain 3MF) name no extruder: the project's feature filaments print them,
295
+ // else filament 1 (ModelVolume::extruder_id's default).
296
+ if (!used.size && (plate.objectIds.some(id => !objects.has(id)) || (!objects.size && buildItems.length)))
297
+ for (const key of FEATURES)
298
+ add(global(key) > 0 ? global(key) : 1);
299
+ // A mixed filament slot prints as its component filaments (PartPlate.cpp:1437-1449, expand_mixed_filaments in
300
+ // FilamentMixer.cpp:460-478; components are 1-based, comma-separated, FilamentMixer.cpp:165-180).
301
+ const mixed = Array.isArray(config.filament_is_mixed) ? config.filament_is_mixed.map(value => boolOf(value) === true) : [];
302
+ const mixedComponents = Array.isArray(config.filament_mixed_components) ? config.filament_mixed_components.map(String) : [];
303
+ if (mixed.some(Boolean))
304
+ for (const [index, name] of [...used]) {
305
+ if (!mixed[index - 1] || index - 1 >= mixedComponents.length)
306
+ continue;
307
+ used.delete(index);
308
+ for (const part of mixedComponents[index - 1].split(",")) {
309
+ const component = /^\s*\d+\s*$/.test(part) ? Number(part) : 0;
310
+ if (component >= 1)
311
+ add(component, name);
312
+ }
313
+ }
314
+ if (plate.slicedFilamentIds) {
315
+ // The slice is Studio's own answer: it replaces the derivation, keeping names the derivation found.
316
+ const names = new Map(used);
317
+ used.clear();
318
+ for (const id of plate.slicedFilamentIds)
319
+ add(id + 1, names.get(id + 1));
320
+ }
321
+ result.set(plate.number, [...used.entries()].sort((a, b) => a[0] - b[0]).map(([index, name]) => describe(index, project, name)));
322
+ }
323
+ // Every filament the project declares, used on a plate or not: slice_stl takes one profile per declared filament.
324
+ return { plates: result, project: Array.from({ length: declared }, (_, i) => describe(i + 1, project)) };
325
+ }
package/dist/index.js CHANGED
@@ -30,7 +30,7 @@ import { importFileViaBambuConnect } from "./bambu-connect.js";
30
30
  import { BlenderMcpBridge } from "./blender-mcp-bridge.js";
31
31
  import { FUSION_EXPORT_OUTPUT_SCHEMA, FUSION_MCP_DEFAULT_ARGS, FUSION_MCP_PIN, FUSION_NEW_DESIGN_OUTPUT_SCHEMA, FUSION_STATUS_OUTPUT_SCHEMA, FusionMcpBridge, addinAddress } from "./fusion-mcp-bridge.js";
32
32
  import { BLENDER_SETUP_OUTPUT_SCHEMA, BlenderAddonSetup, FUSION_ADDIN_REPOSITORY, FUSION_SETUP_OUTPUT_SCHEMA, FusionAddinSetup, defaultSetupSystem, parseAddonHandshake } from "./design-app-setup.js";
33
- import { bridgeAmsMapping2Entry, bridgeAmsMappingValue, externalTrayForNozzle, hasAmsMappingInput, normalizeAmsMappingObject, normalizeBridgeAmsTrayValue, studioAmsMappingInfo, trayColour } from "./ams-mapping.js";
33
+ import { bridgeAmsMapping2Entry, bridgeAmsMappingValue, externalTrayForNozzle, hasAmsMappingInput, normalizeAmsMappingObject, normalizeBridgeAmsTrayValue, studioAmsMapping, studioAmsMappingInfo, trayColour } from "./ams-mapping.js";
34
34
  import { analyze3MFAmsRequirements, analyze3MFPlateObjects, analyzeCollarCharm3MF, extractBambuTemplateSettings, getCollarCharmRolePolicy, hasBambuProjectSettings, hasSlicerSettingsFile, parse3MF, withExtractedSettingsCleanup } from './3mf_parser.js';
35
35
  import { BambuImplementation, assertDirectPrintSupported, checkedFile, defaultResumeStateDir } from "./printers/bambu.js";
36
36
  import { resolveStudioPrintOptions, usedNozzleCount } from "./studio-print-options.js";
@@ -1429,7 +1429,8 @@ class BambuPrinterMCPServer {
1429
1429
  const resumeFile = await checkedFile(inspection, snapshot);
1430
1430
  // The options Bambu Studio's Send dialog would send; explicit ones win.
1431
1431
  const studio = resolveStudioPrintOptions(printModel, callerPrintOptions(args), { usedNozzles: usedNozzleCount(inspection) });
1432
- let mapping = finalAmsMapping?.slice();
1432
+ // Bambu Studio maps only the plate's own filaments; every other project filament is -1 (SelectMachine.cpp:1463-1500).
1433
+ let mapping = finalAmsMapping ? studioAmsMapping(finalAmsMapping, inspection.usedFilamentPositions) : undefined;
1433
1434
  if (finalAmsSlots) {
1434
1435
  if (finalAmsSlots.length !== inspection.usedFilamentPositions.length)
1435
1436
  throw new Error("ams_slots must supply exactly one physical tray per used filament.");
@@ -2057,7 +2058,7 @@ class BambuPrinterMCPServer {
2057
2058
  },
2058
2059
  {
2059
2060
  name: "list_3mf_plates",
2060
- description: "List a Bambu Studio or OrcaSlicer 3MF's plates as its designer laid them out, before slicing: plate_count, and for each plate its index (from 0; slice_stl's slice_plate is index + 1, inspect_print_file's plate_index is index), name, the objects on it, each object copy's identify_id (instances: the ids slice_stl's skip_objects takes) and whether the file already holds its G-code (sliced). A plain 3MF without plate metadata is one plate. include_thumbnails adds each plate's own preview from the file (thumbnail_png_base64). Read-only.",
2061
+ description: "List a Bambu Studio or OrcaSlicer 3MF's plates as its designer laid them out, before slicing: plate_count, and for each plate its index (from 0; slice_stl's slice_plate is index + 1, inspect_print_file's plate_index is index), name, the objects on it, each object copy's identify_id (instances: the ids slice_stl's skip_objects takes) whether the file already holds its G-code (sliced), and filaments: the project filaments that plate prints with and only those (index from 1 = slice_stl's load_filaments/filament_colours position and print_3mf's ams_mapping position + 1; colour, material, filament_id, and the first part using it), from the slice when there is one, otherwise worked out as Bambu Studio does from the plate's parts, painting, support, layer ranges and tool changes. project_filaments lists every filament the project declares, used or not (slice_stl takes one load_filaments profile per declared filament). A plain 3MF without plate metadata is one plate. include_thumbnails adds each plate's own preview from the file (thumbnail_png_base64). Read-only.",
2061
2062
  inputSchema: {
2062
2063
  type: "object",
2063
2064
  properties: {
@@ -2862,7 +2863,7 @@ class BambuPrinterMCPServer {
2862
2863
  use_ams: { type: "boolean", description: "Whether to use the AMS (default: auto-detect from 3MF)" },
2863
2864
  ams_mapping: {
2864
2865
  type: "array",
2865
- description: "Project-level AMS mapping array. Position = project filament index, value = absolute AMS tray (0-3=AMS 0, 4-7=AMS 1, 8-11=AMS 2, 128+=AMS-HT, 254=external, -1=unused). On dual-nozzle printers (H2D, H2D Pro, H2C, X2D) 254 is the LEFT/deputy nozzle external spool and 255 the RIGHT/main nozzle external spool, matching Bambu Studio's virtual tray ids; the gcode header's filament_map (1=left, 2=right) says which nozzle each filament was sliced for. Prefer ams_slots unless you know the project-level layout.",
2866
+ description: "Project-level AMS mapping array. Position = project filament index, value = absolute AMS tray. Positions the selected plate does not print are sent as -1, as Bambu Studio sends them, whatever is passed there (0-3=AMS 0, 4-7=AMS 1, 8-11=AMS 2, 128+=AMS-HT, 254=external, -1=unused). On dual-nozzle printers (H2D, H2D Pro, H2C, X2D) 254 is the LEFT/deputy nozzle external spool and 255 the RIGHT/main nozzle external spool, matching Bambu Studio's virtual tray ids; the gcode header's filament_map (1=left, 2=right) says which nozzle each filament was sliced for. Prefer ams_slots unless you know the project-level layout.",
2866
2867
  items: { type: "number" }
2867
2868
  },
2868
2869
  ams_slots: {
@@ -14,7 +14,7 @@ import { Readable } from "node:stream";
14
14
  import { readSafe3mfArchive } from "../safety/archive.js";
15
15
  import { inspectPrintFile } from "../safety/print-file.js";
16
16
  import { isDualNozzleModel, normalizeModel, validateTemperature } from "../safety/limits.js";
17
- import { bridgeAmsMapping2Entry, bridgeAmsMappingValue, externalTrayForNozzle, describeAmsTrayRange } from "../ams-mapping.js";
17
+ import { bridgeAmsMapping2Entry, bridgeAmsMappingValue, externalTrayForNozzle, describeAmsTrayRange, studioAmsMapping } from "../ams-mapping.js";
18
18
  import { describeHmsKey, hiddenHmsKeys, hiddenHmsNotices, reportedHmsKey, unchippedNozzles, validatePrinterState, manualHeatingRequirements } from "../safety/printer-state.js";
19
19
  import { withPrinterOperation, withPrintSnapshot, uniquePrintName, normalizedRemotePath, cancelPendingPrinterOperations } from "../safety/artifact.js";
20
20
  import { RTSP_CAMERA_MODELS, TCP_CAMERA_MODELS } from "./camera-models.js";
@@ -1016,7 +1016,9 @@ export class BambuImplementation {
1016
1016
  if (options.amsMapping && options.amsMapping.length > 0) {
1017
1017
  for (const v of options.amsMapping)
1018
1018
  validateTrayValue(v, "ams_mapping");
1019
- baseMapping = options.amsMapping.slice();
1019
+ // Bambu Studio sends a tray only for the filaments the plate prints and -1 for every other project filament
1020
+ // (SelectMachineDialog::get_ams_mapping_result, SelectMachine.cpp:1463-1500): so does this route.
1021
+ baseMapping = studioAmsMapping(options.amsMapping, inspection.usedFilamentPositions);
1020
1022
  }
1021
1023
  else if (options.amsSlots && options.amsSlots.length > 0) {
1022
1024
  for (const v of options.amsSlots)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bambu-printer-mcp",
3
- "version": "1.1.72",
3
+ "version": "1.1.73",
4
4
  "description": "MCP server for Bambu Lab 3D printers with STL manipulation, slicing, and print management",
5
5
  "main": "dist/index.js",
6
6
  "repository": {
@@ -132,3 +132,13 @@ export function studioAmsMappingInfo(filaments: ProjectFilament[], mapping: numb
132
132
  };
133
133
  });
134
134
  }
135
+
136
+ /**
137
+ * A project-level ams_mapping as Bambu Studio sends it: the caller's tray for each filament the selected plate prints,
138
+ * -1 for every project filament it doesn't (SelectMachineDialog::get_ams_mapping_result, SelectMachine.cpp:1463-1500,
139
+ * maps only the plate's own filaments). A tray for an unused filament is never sent to the printer.
140
+ */
141
+ export function studioAmsMapping(mapping: number[], usedPositions: number[]): number[] {
142
+ const used = new Set(usedPositions);
143
+ return mapping.map((tray, position) => used.has(position) ? tray : -1);
144
+ }
@@ -8,6 +8,7 @@
8
8
  * is one plate. Only bounded metadata is read; nothing is extracted or run.
9
9
  */
10
10
  import { readSafe3mfArchive } from "../safety/archive.js";
11
+ import { plateFilaments, type PlateFilament, type PlateLayout } from "./plate-filaments.js";
11
12
 
12
13
  export interface ModelPlate {
13
14
  /** Zero-based, as inspect_print_file's plate_index; slice_stl's slice_plate is index + 1. */
@@ -22,6 +23,12 @@ export interface ModelPlate {
22
23
  instances: { identify_id: number; name: string }[];
23
24
  /** The file already holds this plate's G-code. */
24
25
  sliced: boolean;
26
+ /**
27
+ * The project filaments this plate prints with, and only those (counterpart/1): what a client asks the person to
28
+ * choose spools for. From the slice when the file holds one (plate_N.json filament_ids), otherwise worked out as
29
+ * Bambu Studio does for the objects on this plate (see plate-filaments.ts). Filaments of other plates never appear.
30
+ */
31
+ filaments: PlateFilament[];
25
32
  /** The plate's own preview from the file (Metadata/plate_N.png), when asked for and present. */
26
33
  thumbnail_png_base64?: string;
27
34
  }
@@ -31,6 +38,11 @@ export interface ModelPlates {
31
38
  title?: string;
32
39
  designer?: string;
33
40
  licence?: string;
41
+ /**
42
+ * Every filament the project declares (project_settings.config), used on a plate or not, from 1: slice_stl takes one
43
+ * load_filaments profile per declared filament. Empty for a 3MF that declares none.
44
+ */
45
+ project_filaments: PlateFilament[];
34
46
  }
35
47
 
36
48
  /** For the settings and plate files; the model file can be large and is only scanned. */
@@ -58,7 +70,7 @@ export async function listModelPlates(filePath: string, options: { thumbnails?:
58
70
  if (!/<(?:\w+:)?model\b/.test(head)) throw new Error("That file is not a 3MF model.");
59
71
  // An element named `tag`, plain or with a namespace prefix (<item …>, <p:item …>).
60
72
  const has = (tag: string) => !!modelBytes && [" ", ">", "/", "\n", "\r", "\t"].some(end => modelBytes.includes(`<${tag}${end}`) || modelBytes.includes(`:${tag}${end}`));
61
- const result: ModelPlates = { plate_count: 0, plates: [] };
73
+ const result: ModelPlates = { plate_count: 0, plates: [], project_filaments: [] };
62
74
  const metadata = new Map([...head.matchAll(/<metadata\s+name="([^"]+)"[^>]*>([^<]*)<\/metadata>/g)].map(match => [match[1], words(match[2])]));
63
75
  if (metadata.get("Title")) result.title = metadata.get("Title");
64
76
  if (metadata.get("Designer")) result.designer = metadata.get("Designer");
@@ -70,6 +82,7 @@ export async function listModelPlates(filePath: string, options: { thumbnails?:
70
82
  return [match[1], words(name?.[1] ?? "")];
71
83
  }));
72
84
  const plates = new Map<number, ModelPlate>();
85
+ const layouts = new Map<number, PlateLayout>();
73
86
  // A plate number out of range is skipped, as a slicer would not show it.
74
87
  const valid = (number: number) => Number.isSafeInteger(number) && number >= 1 && number <= MAX_PLATES;
75
88
  for (const match of settings.matchAll(/<plate\b[^>]*>([\s\S]*?)<\/plate>/g)) {
@@ -84,7 +97,13 @@ export async function listModelPlates(filePath: string, options: { thumbnails?:
84
97
  return object !== undefined && Number.isSafeInteger(identify) && identify > 0
85
98
  ? [{ identify_id: identify, name: objects.get(object) ?? "" }] : [];
86
99
  }).slice(0, MAX_INSTANCES_PER_PLATE);
87
- plates.set(number, { index: number - 1, name: words(name?.[1] ?? "") || `Plate ${number}`, sliced: false, instances,
100
+ layouts.set(number, { number, objectIds: [...match[1].matchAll(/<metadata\s+key="object_id"\s+value="(\d+)"/g)].map(item => item[1]),
101
+ instances: [...match[1].matchAll(/<model_instance>([\s\S]*?)<\/model_instance>/g)].flatMap(instance => {
102
+ const objectId = /<metadata\s+key="object_id"\s+value="(\d+)"/.exec(instance[1])?.[1];
103
+ const instanceId = Number(/<metadata\s+key="instance_id"\s+value="(\d+)"/.exec(instance[1])?.[1] ?? 0);
104
+ return objectId ? [{ objectId, instanceId }] : [];
105
+ }) });
106
+ plates.set(number, { index: number - 1, name: words(name?.[1] ?? "") || `Plate ${number}`, sliced: false, instances, filaments: [],
88
107
  objects: [...match[1].matchAll(/<metadata\s+key="object_id"\s+value="(\d+)"/g)].flatMap(item => objects.get(item[1]) ? [objects.get(item[1])!] : []) });
89
108
  }
90
109
  for (const name of Object.keys(zip.files)) {
@@ -92,11 +111,15 @@ export async function listModelPlates(filePath: string, options: { thumbnails?:
92
111
  if (!match) continue;
93
112
  const number = Number(match[1]);
94
113
  if (!valid(number)) continue;
95
- const plate = plates.get(number) ?? { index: number - 1, name: `Plate ${number}`, objects: [], instances: [], sliced: false };
114
+ const plate = plates.get(number) ?? { index: number - 1, name: `Plate ${number}`, objects: [], instances: [], sliced: false, filaments: [] };
115
+ const layout = layouts.get(number) ?? { number, objectIds: [] };
116
+ layouts.set(number, layout);
96
117
  if (match[2] === "gcode") plate.sliced = true;
97
118
  else {
98
119
  try {
99
- const value = JSON.parse(await text(name)) as { bbox_objects?: { name?: unknown }[] };
120
+ const value = JSON.parse(await text(name)) as { bbox_objects?: { name?: unknown }[]; filament_ids?: unknown };
121
+ // Studio's record of the filaments this plate's slice uses (0-based project positions).
122
+ if (Array.isArray(value.filament_ids)) layout.slicedFilamentIds = value.filament_ids.filter((id): id is number => Number.isInteger(id) && id >= 0 && id < 64);
100
123
  if (Array.isArray(value.bbox_objects)) plate.objects = value.bbox_objects
101
124
  .flatMap(object => typeof object.name === "string" && object.name !== "wipe_tower" ? [words(object.name)] : []).slice(0, 200);
102
125
  } catch { /* the plate keeps the objects model_settings lists */ }
@@ -105,13 +128,25 @@ export async function listModelPlates(filePath: string, options: { thumbnails?:
105
128
  }
106
129
  result.plates = [...plates.values()].sort((a, b) => a.index - b.index);
107
130
  // A standard single-build 3MF has no Bambu plate metadata: it is one plate.
108
- if (!result.plates.length) result.plates.push({ index: 0, name: "Plate 1", objects: [], instances: [], sliced: false });
131
+ if (!result.plates.length) {
132
+ result.plates.push({ index: 0, name: "Plate 1", objects: [], instances: [], sliced: false, filaments: [] });
133
+ // Without plates every object is on the one plate.
134
+ layouts.set(1, { number: 1, objectIds: [...settings.matchAll(/<object\b[^>]*\bid="(\d+)"/g)].map(match => match[1]) });
135
+ }
109
136
  const geometry = has("item") && (has("mesh") || has("component"));
110
137
  if (!geometry) {
111
138
  // A sliced-only file (previews and G-code, no model): only its sliced plates can print.
112
139
  result.plates = result.plates.filter(plate => plate.sliced);
113
140
  if (!result.plates.length) throw new Error("This 3MF has previews and settings but no model or printable plate.");
114
141
  }
142
+ // A slice's G-code without its plate_N.json gives no filament list: the derivation stands.
143
+ // A model file too large to read whole: its resources come first and its build items last (a plain 3MF).
144
+ const modelText = !modelBytes ? "" : modelBytes.length <= 64 * 1024 * 1024 ? modelBytes.toString("utf8")
145
+ : `${head}${modelBytes.subarray(-1024 * 1024).toString("utf8")}`;
146
+ const filaments = await plateFilaments(zip, settings, modelText,
147
+ result.plates.map(plate => layouts.get(plate.index + 1) ?? { number: plate.index + 1, objectIds: [] }));
148
+ for (const plate of result.plates) plate.filaments = filaments.plates.get(plate.index + 1) ?? [];
149
+ result.project_filaments = filaments.project;
115
150
  if (options.thumbnails) for (const plate of result.plates) {
116
151
  const file = zip.file(`Metadata/plate_${plate.index + 1}.png`);
117
152
  if (!file) continue;
@@ -0,0 +1,338 @@
1
+ /**
2
+ * The project filaments each plate of a Bambu Studio / OrcaSlicer 3MF prints with, worked out the way Bambu Studio
3
+ * does it (v02.08.02.61), so a client asks the person to choose spools only for the filaments that plate uses.
4
+ *
5
+ * - A sliced plate: Studio's own record, Metadata/plate_N.json `filament_ids` (0-based), written from the slice.
6
+ * - An unsliced plate: PartPlate::get_extruders_under_cli (src/slic3r/GUI/PartPlate.cpp:1298-1420) over the objects
7
+ * with an instance on the plate (model_settings.config <model_instance>; an instance with printable="0" in the
8
+ * 3dmodel.model build is skipped, PartPlate.cpp:1321):
9
+ * - each volume's ModelVolume::get_extruders (src/libslic3r/Model.cpp:3357-3412): negative parts, support blockers
10
+ * and enforcers print nothing; the volume's painted states (mmu_segmentation, `paint_color`); the volume's own
11
+ * extruder (ModelVolume::extruder_id, Model.cpp:3295-3306: the part's, else the object's, else 1) unless paint
12
+ * covers every facet of a model part; and the volume's wall/solid/sparse infill filaments, else the object's;
13
+ * - the object's layer-range extruders (Metadata/layer_config_ranges.xml, by 1-based model object index);
14
+ * - the object's feature filaments when separate_filaments_for_features is on;
15
+ * - the support and support-interface filaments when the object (or the project) prints support or a raft;
16
+ * - the plate's tool changes (Metadata/custom_gcode_per_layer.xml, CustomGCode::ToolChange = 2,
17
+ * PartPlate.cpp:1263-1274).
18
+ * Painting is decoded as FacetsAnnotation::set_triangle_from_string (Model.cpp:4631-4650) and
19
+ * TriangleSelector::deserialize (src/libslic3r/TriangleSelector.cpp:2111-2139) read it; this is a reimplementation
20
+ * from that documented behaviour, not Studio's code.
21
+ *
22
+ * Only bounded metadata and mesh text are read; nothing is extracted or run.
23
+ */
24
+ import type JSZip from "jszip";
25
+
26
+ export interface PlateFilament {
27
+ /** 1-based project filament number: slice_stl's load_filaments/filament_colours position, print_3mf's ams_mapping index + 1. */
28
+ index: number;
29
+ /** As the project declares it (project_settings.config filament_colour), #RRGGBB. */
30
+ colour?: string;
31
+ /** project_settings.config filament_type. */
32
+ material?: string;
33
+ /** project_settings.config filament_ids (Bambu's filament id, e.g. GFA00). */
34
+ filament_id?: string;
35
+ /** The first part (else object) on this plate that prints with it; absent for support, painting or tool changes only. */
36
+ name?: string;
37
+ }
38
+
39
+ const MAX_TEXT_BYTES = 8 * 1024 * 1024;
40
+ const MAX_MESH_BYTES = 64 * 1024 * 1024;
41
+ const MAX_MESH_TOTAL = 256 * 1024 * 1024;
42
+ const MAX_FILAMENT = 64;
43
+
44
+ const words = (value: string) => value
45
+ .replace(/&(?:amp|lt|gt|quot|apos);/g, entity => ({ "&amp;": "&", "&lt;": "<", "&gt;": ">", "&quot;": "\"", "&apos;": "'" }[entity]!))
46
+ .replace(/[\u0000-\u001f\u007f]/g, " ").trim().slice(0, 256);
47
+
48
+ type Settings = Map<string, string>;
49
+ interface Part { id: string; subtype: string; name: string; settings: Settings }
50
+ interface ObjectEntry { id: string; name: string; settings: Settings; parts: Part[] }
51
+
52
+ const metadataOf = (block: string): Settings => new Map([...block.matchAll(/<metadata\s+key="([^"]+)"\s+value="([^"]*)"\s*\/?>/g)].map(match => [match[1], match[2]]));
53
+
54
+ /** model_settings.config objects with their own settings and parts (parts never nest). */
55
+ export function readModelObjects(settings: string): ObjectEntry[] {
56
+ return [...settings.matchAll(/<object\b[^>]*\bid="(\d+)"[^>]*>([\s\S]*?)<\/object>/g)].map(match => {
57
+ const parts = [...match[2].matchAll(/<part\b([^>]*)>([\s\S]*?)<\/part>/g)].map(part => {
58
+ const own = metadataOf(part[2]);
59
+ return { id: /\bid="(\d+)"/.exec(part[1])?.[1] ?? "", subtype: /\bsubtype="([^"]+)"/.exec(part[1])?.[1] ?? "normal_part", name: words(own.get("name") ?? ""), settings: own };
60
+ });
61
+ const own = metadataOf(match[2].replace(/<part\b[^>]*>[\s\S]*?<\/part>/g, ""));
62
+ return { id: match[1], name: words(own.get("name") ?? ""), settings: own, parts };
63
+ });
64
+ }
65
+
66
+ /** An integer setting (Studio stores "0"/"1"/"3" strings; a project list keeps its first value). */
67
+ function intOf(value: unknown): number | undefined {
68
+ const first = Array.isArray(value) ? value[0] : value;
69
+ if (typeof first === "number" && Number.isInteger(first)) return first;
70
+ if (typeof first !== "string" || !/^\s*-?\d+\s*$/.test(first)) return undefined;
71
+ return Number(first);
72
+ }
73
+ function boolOf(value: unknown): boolean | undefined {
74
+ const first = Array.isArray(value) ? value[0] : value;
75
+ if (typeof first === "boolean") return first;
76
+ if (typeof first !== "string") return undefined;
77
+ if (/^(?:1|true)$/i.test(first.trim())) return true;
78
+ if (/^(?:0|false)$/i.test(first.trim())) return false;
79
+ return undefined;
80
+ }
81
+
82
+ /**
83
+ * The filament states a painted facet string holds (0 is "the volume's own filament"). Studio's string is hex,
84
+ * read last character first, each digit four bits low bit first, so the nibbles are the digits in reverse order.
85
+ * Each node is one nibble: two low bits are the split-side count (children = sides + 1); a leaf's state is the high
86
+ * two bits, or, when both are set, 3 + the next nibble + 15 for every preceding 0b1111 nibble.
87
+ */
88
+ export function paintedStates(paint: string): number[] {
89
+ const nibbles: number[] = [];
90
+ for (let i = paint.length - 1; i >= 0; i--) {
91
+ const digit = Number.parseInt(paint[i], 16);
92
+ if (Number.isNaN(digit)) return [];
93
+ nibbles.push(digit);
94
+ }
95
+ const states: number[] = [];
96
+ let at = 0, pending = 1;
97
+ const next = () => (at < nibbles.length ? nibbles[at++] : undefined);
98
+ while (pending > 0) {
99
+ const code = next();
100
+ if (code === undefined) break;
101
+ pending -= 1;
102
+ const sides = code & 0b11;
103
+ if (sides) { pending += sides + 1; continue; }
104
+ if ((code & 0b1100) === 0b1100) {
105
+ let more = 0, value = next();
106
+ while (value === 0b1111) { more += 1; value = next(); }
107
+ if (value === undefined) break;
108
+ states.push(value + 15 * more + 3);
109
+ } else states.push(code >> 2);
110
+ }
111
+ return states;
112
+ }
113
+
114
+ /** What a mesh's painting says: the painted filament states, and whether any facet keeps the volume's own filament. */
115
+ interface MeshPaint { states: Set<number>; ownFilament: boolean }
116
+
117
+ /**
118
+ * Per component file and sub-object id, the painting of that mesh. Only files that contain painting are read in full.
119
+ */
120
+ async function readPainting(zip: JSZip, paths: Set<string>): Promise<Map<string, MeshPaint>> {
121
+ const result = new Map<string, MeshPaint>();
122
+ let total = 0;
123
+ for (const path of paths) {
124
+ const file = zip.file(path);
125
+ if (!file) continue;
126
+ // A mesh past the read budget is taken as unpainted (its part's own filament), never a failed listing.
127
+ const size = (file as unknown as { _data?: { uncompressedSize?: number } })._data?.uncompressedSize;
128
+ if (size !== undefined && (size > MAX_MESH_BYTES || total + size > MAX_MESH_TOTAL)) continue;
129
+ const bytes = await file.async("nodebuffer");
130
+ if (bytes.length > MAX_MESH_BYTES || (total += bytes.length) > MAX_MESH_TOTAL) continue;
131
+ if (!bytes.includes("paint_color=\"")) continue;
132
+ const text = bytes.toString("utf8");
133
+ for (const object of text.matchAll(/<object\b[^>]*\bid="(\d+)"[^>]*>([\s\S]*?)<\/object>/g)) {
134
+ const paint: MeshPaint = { states: new Set(), ownFilament: false };
135
+ for (const triangle of object[2].matchAll(/<triangle\b([^>]*)\/?>/g)) {
136
+ const value = /\bpaint_color="([0-9A-Fa-f]*)"/.exec(triangle[1])?.[1];
137
+ if (!value) { paint.ownFilament = true; continue; }
138
+ for (const state of paintedStates(value)) {
139
+ if (state === 0) paint.ownFilament = true;
140
+ else paint.states.add(state);
141
+ }
142
+ }
143
+ result.set(`${path}#${object[1]}`, paint);
144
+ }
145
+ }
146
+ return result;
147
+ }
148
+
149
+ interface ProjectFilaments { colours: string[]; materials: string[]; ids: string[]; config: Record<string, unknown> }
150
+
151
+ function projectFilaments(config: Record<string, unknown>): ProjectFilaments {
152
+ const list = (key: string): string[] => Array.isArray(config[key]) ? (config[key] as unknown[]).map(String) : [];
153
+ return { colours: list("filament_colour"), materials: list("filament_type"), ids: list("filament_ids"), config };
154
+ }
155
+
156
+ function describe(index: number, project: ProjectFilaments, name?: string): PlateFilament {
157
+ const colour = /^#?([0-9a-fA-F]{6})(?:[0-9a-fA-F]{2})?$/.exec(project.colours[index - 1]?.trim() ?? "");
158
+ const material = project.materials[index - 1]?.trim().replace(/[\u0000-\u001f\u007f]/g, " ").slice(0, 64);
159
+ const filamentId = project.ids[index - 1]?.trim().replace(/[\u0000-\u001f\u007f]/g, " ").slice(0, 64);
160
+ return { index, ...(colour ? { colour: `#${colour[1].toUpperCase()}` } : {}), ...(material ? { material } : {}),
161
+ ...(filamentId ? { filament_id: filamentId } : {}), ...(name ? { name } : {}) };
162
+ }
163
+
164
+ export interface PlateLayout {
165
+ /** 1-based plate number. */
166
+ number: number;
167
+ /** model_settings.config object ids with an instance on this plate, in plate order. */
168
+ objectIds: string[];
169
+ /** Each copy on the plate: its object and that object's instance_id (model_settings.config <model_instance>). */
170
+ instances?: { objectId: string; instanceId: number }[];
171
+ /** Metadata/plate_N.json filament_ids (0-based) when the file holds this plate's slice. */
172
+ slicedFilamentIds?: number[];
173
+ }
174
+
175
+ /**
176
+ * The filaments each plate prints with, keyed by plate number. `settings` is model_settings.config, `model` the root
177
+ * 3D/3dmodel.model text.
178
+ */
179
+ export async function plateFilaments(zip: JSZip, settings: string, model: string, plates: PlateLayout[]): Promise<{ plates: Map<number, PlateFilament[]>; project: PlateFilament[] }> {
180
+ const text = async (name: string) => {
181
+ const file = zip.file(name);
182
+ if (!file) return "";
183
+ const bytes = await file.async("nodebuffer");
184
+ if (bytes.length > MAX_TEXT_BYTES) throw new Error(`${name} is too large to read.`);
185
+ return bytes.toString("utf8");
186
+ };
187
+ let config: Record<string, unknown> = {};
188
+ try {
189
+ const parsed = JSON.parse(await text("Metadata/project_settings.config") || "{}") as unknown;
190
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) config = parsed as Record<string, unknown>;
191
+ } catch { /* a project without readable settings declares no filaments */ }
192
+ const project = projectFilaments(config);
193
+ const declared = Math.min(MAX_FILAMENT, Math.max(project.colours.length, project.materials.length, project.ids.length));
194
+ const valid = (index: number | undefined): index is number => index !== undefined && Number.isInteger(index) && index >= 1 && index <= MAX_FILAMENT && (!declared || index <= declared);
195
+
196
+ const objects = new Map(readModelObjects(settings).map(object => [object.id, object]));
197
+ // Root objects' components: which sub-object mesh in which file each part is (part id = component objectid).
198
+ const components = new Map<string, Map<string, string>>();
199
+ for (const object of model.matchAll(/<(?:\w+:)?object\b[^>]*\bid="(\d+)"[^>]*>([\s\S]*?)<\/(?:\w+:)?object>/g)) {
200
+ const parts = new Map<string, string>();
201
+ for (const component of object[2].matchAll(/<(?:\w+:)?component\b([^>]*)\/?>/g)) {
202
+ const path = /\b(?:\w+:)?path="\/?([^"]+)"/.exec(component[1])?.[1];
203
+ const id = /\bobjectid="(\d+)"/.exec(component[1])?.[1];
204
+ // Studio keys a component by (path, objectid); one without p:path names a mesh object in the root model
205
+ // itself, keyed by the root's empty path (bbs_3mf.cpp:4131-4148, 3891).
206
+ if (id) parts.set(id, path || "3D/3dmodel.model");
207
+ }
208
+ if (parts.size) components.set(object[1], parts);
209
+ }
210
+ // Model object order (1-based in layer_config_ranges.xml): the build items' order, as Studio creates the objects.
211
+ const buildItems = [...model.matchAll(/<(?:\w+:)?item\b([^>]*)\/?>/g)].map(item => item[1]);
212
+ const order = [...new Set(buildItems.flatMap(item => /\bobjectid="(\d+)"/.exec(item)?.[1] ?? []))];
213
+ // Each build item adds its object's next instance, with its own printable flag (bbs_3mf.cpp:4183-4185, 4375-4380);
214
+ // a plate names its copies by object_id and instance_id (bbs_3mf.cpp:4717-4719), and the CLI skips each copy that
215
+ // isn't printable (PartPlate.cpp:1311-1322).
216
+ const printableItems = new Map<string, boolean[]>();
217
+ for (const item of buildItems) {
218
+ const id = /\bobjectid="(\d+)"/.exec(item)?.[1];
219
+ if (id) printableItems.set(id, [...(printableItems.get(id) ?? []), !/\bprintable="(?:0|false)"/.test(item)]);
220
+ }
221
+ const printableCopy = (objectId: string, instanceId?: number) => {
222
+ const flags = printableItems.get(objectId);
223
+ if (!flags) return true;
224
+ return instanceId === undefined ? flags.some(Boolean) : flags[instanceId] !== false;
225
+ };
226
+
227
+
228
+ const rangeExtruders = new Map<string, number[]>();
229
+ const ranges = await text("Metadata/layer_config_ranges.xml");
230
+ for (const object of ranges.matchAll(/<object\b[^>]*\bid="(\d+)"[^>]*>([\s\S]*?)<\/object>/g)) {
231
+ const objectId = order[Number(object[1]) - 1];
232
+ if (!objectId) continue;
233
+ // A range's extruder sets all three feature filaments; a range's own feature filament overrides one
234
+ // (apply_to_print_region_config and resolve_filament_value, PrintObject.cpp:3069-3079, 3134-3137).
235
+ rangeExtruders.set(objectId, [...object[2].matchAll(/<option\s+opt_key="(?:extruder|wall_filament|sparse_infill_filament|solid_infill_filament)"\s*>\s*(\d+)\s*<\/option>/g)].map(match => Number(match[1])).filter(id => id > 0));
236
+ }
237
+ const toolChanges = new Map<number, number[]>();
238
+ const custom = await text("Metadata/custom_gcode_per_layer.xml");
239
+ for (const plate of custom.matchAll(/<plate>([\s\S]*?)<\/plate>/g)) {
240
+ const id = Number(/<plate_info\b[^>]*\bid="(\d+)"/.exec(plate[1])?.[1]);
241
+ if (!Number.isInteger(id)) continue;
242
+ toolChanges.set(id, [...plate[1].matchAll(/<layer\b([^>]*)\/?>/g)]
243
+ .filter(layer => /\btype="2"/.test(layer[1]))
244
+ .map(layer => Number(/\bextruder="(\d+)"/.exec(layer[1])?.[1])));
245
+ }
246
+
247
+ // Painting only matters for parts on a plate that is not sliced yet.
248
+ const paintPaths = new Set<string>();
249
+ for (const plate of plates) if (!plate.slicedFilamentIds) for (const objectId of plate.objectIds)
250
+ for (const path of components.get(objectId)?.values() ?? []) paintPaths.add(path);
251
+ const painting = await readPainting(zip, paintPaths);
252
+
253
+ const global = (key: string) => intOf(config[key]) ?? 0;
254
+ const FEATURES = ["wall_filament", "sparse_infill_filament", "solid_infill_filament"] as const;
255
+ const result = new Map<number, PlateFilament[]>();
256
+ for (const plate of plates) {
257
+ const used = new Map<number, string | undefined>();
258
+ const add = (index: number | undefined, name?: string) => {
259
+ if (!valid(index)) return;
260
+ if (!used.has(index) || (!used.get(index) && name)) used.set(index, name || undefined);
261
+ };
262
+ // An object counts once on a plate when any of its copies there prints.
263
+ const printing = plate.instances?.length
264
+ ? [...new Set(plate.instances.filter(copy => printableCopy(copy.objectId, copy.instanceId)).map(copy => copy.objectId))]
265
+ : plate.objectIds.filter(objectId => printableCopy(objectId));
266
+ for (const objectId of printing) {
267
+ const object = objects.get(objectId);
268
+ if (!object) continue;
269
+ const objectInt = (key: string) => intOf(object.settings.get(key));
270
+ const parts = object.parts.length ? object.parts : [{ id: "", subtype: "normal_part", name: "", settings: new Map() as Settings }];
271
+ for (const part of parts) {
272
+ if (["negative_part", "support_blocker", "support_enforcer"].includes(part.subtype)) continue;
273
+ const partInt = (key: string) => intOf(part.settings.get(key));
274
+ // What the slicer prints the part with (region_config_from_model_volume, PrintObject.cpp:3105-3150): the
275
+ // project's feature filaments, replaced by the object's and then the part's extruder when one is set
276
+ // (non-zero), then by a feature filament the part, else the object, sets above 0.
277
+ const extruderSet = (partInt("extruder") ?? 0) > 0 || (objectInt("extruder") ?? 0) > 0;
278
+ const ownExtruder = partInt("extruder") || objectInt("extruder") || 1;
279
+ const label = part.name || object.name;
280
+ const path = components.get(objectId)?.get(part.id);
281
+ const paint = path ? painting.get(`${path}#${part.id}`) : undefined;
282
+ for (const state of paint?.states ?? []) if (part.subtype === "normal_part") add(state, label);
283
+ // A modifier's own filament counts whatever its paint (Model.cpp:3384-3390).
284
+ if (part.subtype !== "normal_part" || !paint || paint.ownFilament) {
285
+ if (extruderSet) add(ownExtruder, label);
286
+ // Neither the part nor its object names an extruder: the project's feature filaments print it (each
287
+ // above 0; a project without them prints with filament 1, ModelVolume::extruder_id's default).
288
+ else for (const key of FEATURES) add(global(key) > 0 ? global(key) : 1, label);
289
+ }
290
+ for (const key of ["wall_filament", "solid_infill_filament", "sparse_infill_filament"]) {
291
+ const own = partInt(key);
292
+ if (own !== undefined) { if (own > 0) add(own, label); }
293
+ else if ((objectInt(key) ?? 0) > 0) add(objectInt(key), label);
294
+ }
295
+ // separate_filaments_for_features gates these only in Studio's plate list (PartPlate.cpp:1338-1381): it isn't
296
+ // a slicer setting in 02.08.02.61 (libslic3r never reads it), and the slice applies the part's or object's
297
+ // feature filaments whatever it says (PrintObject.cpp:3124-3150), as the loop above does.
298
+ }
299
+ for (const extruder of rangeExtruders.get(objectId) ?? []) add(extruder, object.name);
300
+ // Support and raft as the slice resolves them: each setting the object's own, else the project's, one key at a
301
+ // time (PrintObject::object_config_from_model_object, PrintObject.cpp:3052-3063). Studio's plate list resolves
302
+ // the pair together (PartPlate.cpp:1383-1393), which drops support an object with only a raft override prints.
303
+ const setting = (key: string) => object.settings.has(key) ? object.settings.get(key) : config[key];
304
+ const support = (boolOf(setting("enable_support")) ?? false) || (intOf(setting("raft_layers")) ?? 0) > 0;
305
+ if (support) {
306
+ // 0 is "default": the support prints with the object's own filament (Print.cpp:490-501).
307
+ add(intOf(setting("support_interface_filament")) || undefined);
308
+ add(intOf(setting("support_filament")) || undefined);
309
+ }
310
+ }
311
+ for (const extruder of toolChanges.get(plate.number) ?? []) add(extruder);
312
+ // Objects the settings don't describe (a plain 3MF) name no extruder: the project's feature filaments print them,
313
+ // else filament 1 (ModelVolume::extruder_id's default).
314
+ if (!used.size && (plate.objectIds.some(id => !objects.has(id)) || (!objects.size && buildItems.length)))
315
+ for (const key of FEATURES) add(global(key) > 0 ? global(key) : 1);
316
+ // A mixed filament slot prints as its component filaments (PartPlate.cpp:1437-1449, expand_mixed_filaments in
317
+ // FilamentMixer.cpp:460-478; components are 1-based, comma-separated, FilamentMixer.cpp:165-180).
318
+ const mixed = Array.isArray(config.filament_is_mixed) ? (config.filament_is_mixed as unknown[]).map(value => boolOf(value) === true) : [];
319
+ const mixedComponents = Array.isArray(config.filament_mixed_components) ? (config.filament_mixed_components as unknown[]).map(String) : [];
320
+ if (mixed.some(Boolean)) for (const [index, name] of [...used]) {
321
+ if (!mixed[index - 1] || index - 1 >= mixedComponents.length) continue;
322
+ used.delete(index);
323
+ for (const part of mixedComponents[index - 1].split(",")) {
324
+ const component = /^\s*\d+\s*$/.test(part) ? Number(part) : 0;
325
+ if (component >= 1) add(component, name);
326
+ }
327
+ }
328
+ if (plate.slicedFilamentIds) {
329
+ // The slice is Studio's own answer: it replaces the derivation, keeping names the derivation found.
330
+ const names = new Map(used);
331
+ used.clear();
332
+ for (const id of plate.slicedFilamentIds) add(id + 1, names.get(id + 1));
333
+ }
334
+ result.set(plate.number, [...used.entries()].sort((a, b) => a[0] - b[0]).map(([index, name]) => describe(index, project, name)));
335
+ }
336
+ // Every filament the project declares, used on a plate or not: slice_stl takes one profile per declared filament.
337
+ return { plates: result, project: Array.from({ length: declared }, (_, i) => describe(i + 1, project)) };
338
+ }
package/src/index.ts CHANGED
@@ -60,7 +60,7 @@ import { importFileViaBambuConnect } from "./bambu-connect.js";
60
60
  import { BlenderMcpBridge } from "./blender-mcp-bridge.js";
61
61
  import { FUSION_EXPORT_OUTPUT_SCHEMA, FUSION_MCP_DEFAULT_ARGS, FUSION_MCP_PIN, FUSION_NEW_DESIGN_OUTPUT_SCHEMA, FUSION_STATUS_OUTPUT_SCHEMA, FusionMcpBridge, addinAddress } from "./fusion-mcp-bridge.js";
62
62
  import { BLENDER_SETUP_OUTPUT_SCHEMA, BlenderAddonSetup, FUSION_ADDIN_REPOSITORY, FUSION_SETUP_OUTPUT_SCHEMA, FusionAddinSetup, defaultSetupSystem, parseAddonHandshake, type BlenderAddonHandshake } from "./design-app-setup.js";
63
- import { bridgeAmsMapping2Entry, bridgeAmsMappingValue, externalTrayForNozzle, hasAmsMappingInput, normalizeAmsMappingObject, normalizeBridgeAmsTrayValue, studioAmsMappingInfo, trayColour } from "./ams-mapping.js";
63
+ import { bridgeAmsMapping2Entry, bridgeAmsMappingValue, externalTrayForNozzle, hasAmsMappingInput, normalizeAmsMappingObject, normalizeBridgeAmsTrayValue, studioAmsMapping, studioAmsMappingInfo, trayColour } from "./ams-mapping.js";
64
64
  import { analyze3MFAmsRequirements, analyze3MFPlateObjects, analyzeCollarCharm3MF, extractBambuTemplateSettings, getCollarCharmRolePolicy, hasBambuProjectSettings, hasSlicerSettingsFile, parse3MF, withExtractedSettingsCleanup } from './3mf_parser.js';
65
65
  import type { ThreeMFAmsRequirements } from "./types.js";
66
66
  import { BambuImplementation, assertDirectPrintSupported, checkedFile, defaultResumeStateDir } from "./printers/bambu.js";
@@ -1829,7 +1829,8 @@ class BambuPrinterMCPServer {
1829
1829
  const resumeFile = await checkedFile(inspection, snapshot);
1830
1830
  // The options Bambu Studio's Send dialog would send; explicit ones win.
1831
1831
  const studio = resolveStudioPrintOptions(printModel, callerPrintOptions(args), { usedNozzles: usedNozzleCount(inspection) });
1832
- let mapping = finalAmsMapping?.slice();
1832
+ // Bambu Studio maps only the plate's own filaments; every other project filament is -1 (SelectMachine.cpp:1463-1500).
1833
+ let mapping = finalAmsMapping ? studioAmsMapping(finalAmsMapping, inspection.usedFilamentPositions) : undefined;
1833
1834
  if (finalAmsSlots) {
1834
1835
  if (finalAmsSlots.length !== inspection.usedFilamentPositions.length) throw new Error("ams_slots must supply exactly one physical tray per used filament.");
1835
1836
  mapping = Array(inspection.materials.length).fill(-1);
@@ -2568,7 +2569,7 @@ class BambuPrinterMCPServer {
2568
2569
  },
2569
2570
  {
2570
2571
  name: "list_3mf_plates",
2571
- description: "List a Bambu Studio or OrcaSlicer 3MF's plates as its designer laid them out, before slicing: plate_count, and for each plate its index (from 0; slice_stl's slice_plate is index + 1, inspect_print_file's plate_index is index), name, the objects on it, each object copy's identify_id (instances: the ids slice_stl's skip_objects takes) and whether the file already holds its G-code (sliced). A plain 3MF without plate metadata is one plate. include_thumbnails adds each plate's own preview from the file (thumbnail_png_base64). Read-only.",
2572
+ description: "List a Bambu Studio or OrcaSlicer 3MF's plates as its designer laid them out, before slicing: plate_count, and for each plate its index (from 0; slice_stl's slice_plate is index + 1, inspect_print_file's plate_index is index), name, the objects on it, each object copy's identify_id (instances: the ids slice_stl's skip_objects takes) whether the file already holds its G-code (sliced), and filaments: the project filaments that plate prints with and only those (index from 1 = slice_stl's load_filaments/filament_colours position and print_3mf's ams_mapping position + 1; colour, material, filament_id, and the first part using it), from the slice when there is one, otherwise worked out as Bambu Studio does from the plate's parts, painting, support, layer ranges and tool changes. project_filaments lists every filament the project declares, used or not (slice_stl takes one load_filaments profile per declared filament). A plain 3MF without plate metadata is one plate. include_thumbnails adds each plate's own preview from the file (thumbnail_png_base64). Read-only.",
2572
2573
  inputSchema: {
2573
2574
  type: "object",
2574
2575
  properties: {
@@ -3373,7 +3374,7 @@ class BambuPrinterMCPServer {
3373
3374
  use_ams: { type: "boolean", description: "Whether to use the AMS (default: auto-detect from 3MF)" },
3374
3375
  ams_mapping: {
3375
3376
  type: "array",
3376
- description: "Project-level AMS mapping array. Position = project filament index, value = absolute AMS tray (0-3=AMS 0, 4-7=AMS 1, 8-11=AMS 2, 128+=AMS-HT, 254=external, -1=unused). On dual-nozzle printers (H2D, H2D Pro, H2C, X2D) 254 is the LEFT/deputy nozzle external spool and 255 the RIGHT/main nozzle external spool, matching Bambu Studio's virtual tray ids; the gcode header's filament_map (1=left, 2=right) says which nozzle each filament was sliced for. Prefer ams_slots unless you know the project-level layout.",
3377
+ description: "Project-level AMS mapping array. Position = project filament index, value = absolute AMS tray. Positions the selected plate does not print are sent as -1, as Bambu Studio sends them, whatever is passed there (0-3=AMS 0, 4-7=AMS 1, 8-11=AMS 2, 128+=AMS-HT, 254=external, -1=unused). On dual-nozzle printers (H2D, H2D Pro, H2C, X2D) 254 is the LEFT/deputy nozzle external spool and 255 the RIGHT/main nozzle external spool, matching Bambu Studio's virtual tray ids; the gcode header's filament_map (1=left, 2=right) says which nozzle each filament was sliced for. Prefer ams_slots unless you know the project-level layout.",
3377
3378
  items: { type: "number" }
3378
3379
  },
3379
3380
  ams_slots: {
@@ -14,7 +14,7 @@ import { Readable } from "node:stream";
14
14
  import { readSafe3mfArchive } from "../safety/archive.js";
15
15
  import { inspectPrintFile, type PrintFileInspection } from "../safety/print-file.js";
16
16
  import { isDualNozzleModel, normalizeModel, validateTemperature } from "../safety/limits.js";
17
- import { bridgeAmsMapping2Entry, bridgeAmsMappingValue, externalTrayForNozzle, describeAmsTrayRange } from "../ams-mapping.js";
17
+ import { bridgeAmsMapping2Entry, bridgeAmsMappingValue, externalTrayForNozzle, describeAmsTrayRange, studioAmsMapping } from "../ams-mapping.js";
18
18
  import { describeHmsKey, hiddenHmsKeys, hiddenHmsNotices, reportedHmsKey, unchippedNozzles, validatePrinterState, manualHeatingRequirements, type PrinterStateRequirements } from "../safety/printer-state.js";
19
19
  import { withPrinterOperation, withPrintSnapshot, uniquePrintName, normalizedRemotePath, cancelPendingPrinterOperations } from "../safety/artifact.js";
20
20
  import { RTSP_CAMERA_MODELS, TCP_CAMERA_MODELS } from "./camera-models.js";
@@ -1175,7 +1175,9 @@ export class BambuImplementation {
1175
1175
  let baseMapping: number[];
1176
1176
  if (options.amsMapping && options.amsMapping.length > 0) {
1177
1177
  for (const v of options.amsMapping) validateTrayValue(v, "ams_mapping");
1178
- baseMapping = options.amsMapping.slice();
1178
+ // Bambu Studio sends a tray only for the filaments the plate prints and -1 for every other project filament
1179
+ // (SelectMachineDialog::get_ams_mapping_result, SelectMachine.cpp:1463-1500): so does this route.
1180
+ baseMapping = studioAmsMapping(options.amsMapping, inspection.usedFilamentPositions);
1179
1181
  } else if (options.amsSlots && options.amsSlots.length > 0) {
1180
1182
  for (const v of options.amsSlots) validateTrayValue(v, "amsSlots");
1181
1183
  const positions = projectMetadata.usedFilamentPositions;