threemf_tools.py 70 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646
  1. """3MF file parsing utilities for filament tracking.
  2. This module provides functions to parse Bambu Lab 3MF files and extract
  3. per-layer filament usage data from the embedded G-code. This enables
  4. accurate partial usage reporting for multi-material prints.
  5. """
  6. import hashlib
  7. import json
  8. import logging
  9. import math
  10. import re
  11. import zipfile
  12. from collections import OrderedDict
  13. from dataclasses import dataclass, field
  14. from pathlib import Path
  15. from threading import Lock
  16. # Parsing goes through defusedxml; the element type it hands back is the stdlib
  17. # one, and defusedxml does not re-export it, so annotations name it directly.
  18. from xml.etree.ElementTree import Element as XmlElement
  19. import defusedxml.ElementTree as ET
  20. logger = logging.getLogger(__name__)
  21. # Default filament properties
  22. DEFAULT_FILAMENT_DIAMETER = 1.75 # mm
  23. DEFAULT_FILAMENT_DENSITY = 1.24 # g/cm³ (PLA)
  24. def parse_gcode_layer_filament_usage(gcode_content: str) -> dict[int, dict[int, float]]:
  25. """Parse G-code to extract per-layer, per-filament cumulative extrusion in mm.
  26. This function tracks filament extrusion across layers and tool changes,
  27. building a cumulative usage map that can be used to calculate partial
  28. usage at any layer.
  29. Args:
  30. gcode_content: The raw G-code content as a string
  31. Returns:
  32. A nested dictionary mapping layer numbers to filament usage:
  33. {layer: {filament_id: cumulative_mm}, ...}
  34. Example:
  35. {0: {0: 125.5}, 1: {0: 250.0, 1: 50.0}, 2: {0: 375.0, 1: 150.0}}
  36. This shows:
  37. - Layer 0: filament 0 used 125.5mm cumulative
  38. - Layer 1: filament 0 used 250mm cumulative, filament 1 used 50mm
  39. - Layer 2: filament 0 used 375mm cumulative, filament 1 used 150mm
  40. G-code commands parsed:
  41. - M73 L<layer>: Layer change marker
  42. - M620 S<filament>: Filament/tool change (S255 = unload)
  43. - G0/G1/G2/G3 E<amount>: Extrusion moves
  44. """
  45. layer_filaments: dict[int, dict[int, float]] = {}
  46. current_layer = 0
  47. active_filament: int | None = None
  48. cumulative_extrusion: dict[int, float] = {} # filament_id -> total mm
  49. for line in gcode_content.splitlines():
  50. line = line.strip()
  51. if not line:
  52. continue
  53. # Handle comments - skip but check for layer markers
  54. if line.startswith(";"):
  55. # Some slicers use comment-based layer markers
  56. # e.g., "; CHANGE_LAYER" or ";LAYER_CHANGE"
  57. continue
  58. # Split line into command and inline comment
  59. if ";" in line:
  60. line = line.split(";")[0].strip()
  61. # Extract command and parameters
  62. parts = line.split()
  63. if not parts:
  64. continue
  65. cmd = parts[0].upper()
  66. # Layer change: M73 L<layer>
  67. # Bambu printers use M73 with L parameter for layer indication
  68. if cmd == "M73":
  69. for part in parts[1:]:
  70. part_upper = part.upper()
  71. if part_upper.startswith("L"):
  72. try:
  73. new_layer = int(part[1:])
  74. # Save current state before layer change
  75. if cumulative_extrusion:
  76. layer_filaments[current_layer] = cumulative_extrusion.copy()
  77. current_layer = new_layer
  78. except ValueError:
  79. pass # Skip G-code lines with unparseable layer numbers
  80. # Filament change: M620 S<filament>
  81. # Bambu uses M620 for AMS filament switching
  82. # S255 means full unload (no active filament)
  83. elif cmd == "M620":
  84. for part in parts[1:]:
  85. part_upper = part.upper()
  86. if part_upper.startswith("S"):
  87. filament_str = part[1:]
  88. if filament_str == "255":
  89. # Full unload - no active filament
  90. active_filament = None
  91. else:
  92. try:
  93. # Extract digits (e.g., "0A" -> 0, "1" -> 1)
  94. match = re.match(r"(\d+)", filament_str)
  95. if match:
  96. active_filament = int(match.group(1))
  97. except (ValueError, AttributeError):
  98. pass # Skip unparseable filament switch commands
  99. # Extrusion moves: G0/G1/G2/G3 with E parameter
  100. # Only G1 typically has extrusion, but check all for safety
  101. elif cmd in ("G0", "G1", "G2", "G3"):
  102. if active_filament is None:
  103. continue
  104. for part in parts[1:]:
  105. part_upper = part.upper()
  106. if part_upper.startswith("E"):
  107. try:
  108. extrusion = float(part[1:])
  109. # Only count positive extrusion (not retractions)
  110. if extrusion > 0:
  111. current = cumulative_extrusion.get(active_filament, 0)
  112. cumulative_extrusion[active_filament] = current + extrusion
  113. except ValueError:
  114. pass # Skip G-code lines with unparseable extrusion values
  115. # Save final layer state
  116. if cumulative_extrusion:
  117. layer_filaments[current_layer] = cumulative_extrusion.copy()
  118. return layer_filaments
  119. def mm_to_grams(
  120. length_mm: float,
  121. diameter_mm: float = DEFAULT_FILAMENT_DIAMETER,
  122. density_g_cm3: float = DEFAULT_FILAMENT_DENSITY,
  123. ) -> float:
  124. """Convert filament length in mm to weight in grams.
  125. Uses the formula: mass = volume × density
  126. where volume = π × r² × length
  127. Args:
  128. length_mm: Length of filament in millimeters
  129. diameter_mm: Filament diameter in millimeters (default: 1.75)
  130. density_g_cm3: Material density in g/cm³ (default: 1.24 for PLA)
  131. Returns:
  132. Weight in grams
  133. """
  134. radius_cm = (diameter_mm / 2) / 10 # Convert mm to cm
  135. length_cm = length_mm / 10 # Convert mm to cm
  136. volume_cm3 = math.pi * radius_cm * radius_cm * length_cm
  137. return volume_cm3 * density_g_cm3
  138. def extract_layer_filament_usage_from_3mf(
  139. file_path: Path, plate_id: int | None = None
  140. ) -> dict[int, dict[int, float]] | None:
  141. """Extract per-layer filament usage from a 3MF file's embedded G-code.
  142. Args:
  143. file_path: Path to the 3MF file
  144. plate_id: Plate to read. Required for multi-plate files — zip member
  145. order is whatever the slicer wrote, and Bambu Studio stores
  146. ``plate_2.gcode`` ahead of ``plate_1.gcode``, so the old
  147. "first member" behaviour read a different plate's layers than
  148. the one that printed. Returns None rather than silently falling
  149. back to another plate when the requested plate isn't in the
  150. file; callers degrade to linear scaling, which is bounded.
  151. Returns:
  152. Dictionary mapping layers to filament usage, or None if parsing fails.
  153. Format: {layer: {filament_id: cumulative_mm}, ...}
  154. """
  155. try:
  156. with zipfile.ZipFile(file_path, "r") as zf:
  157. names = zf.namelist()
  158. gcode_path = select_plate_gcode_name(names, plate_id)
  159. if gcode_path is None:
  160. # No plate asked for, or a file whose single G-code member
  161. # doesn't follow the plate_N naming convention (non-Bambu
  162. # slicers) — the lone member is unambiguous either way.
  163. gcode_files = [f for f in names if f.endswith(".gcode")]
  164. if plate_id is None or len(gcode_files) == 1:
  165. gcode_path = default_plate_gcode_name(names)
  166. if gcode_path is None:
  167. return None
  168. gcode_content = zf.read(gcode_path).decode("utf-8", errors="ignore")
  169. return parse_gcode_layer_filament_usage(gcode_content)
  170. except Exception:
  171. return None
  172. def get_cumulative_usage_at_layer(
  173. layer_usage: dict[int, dict[int, float]],
  174. target_layer: int,
  175. ) -> dict[int, float]:
  176. """Get cumulative filament usage (in mm) up to and including target_layer.
  177. Args:
  178. layer_usage: The output from parse_gcode_layer_filament_usage()
  179. target_layer: The layer number to get usage for
  180. Returns:
  181. Dictionary of {filament_id: cumulative_mm} for each filament used
  182. up to target_layer. Returns empty dict if no data available.
  183. """
  184. if not layer_usage:
  185. return {}
  186. # Find the highest recorded layer <= target_layer
  187. # (we store snapshots at layer changes, so we need the closest one)
  188. relevant_layers = [layer for layer in layer_usage if layer <= target_layer]
  189. if not relevant_layers:
  190. return {}
  191. max_layer = max(relevant_layers)
  192. return layer_usage.get(max_layer, {})
  193. def extract_filament_properties_from_3mf(file_path: Path) -> dict[int, dict]:
  194. """Extract filament properties (density, diameter, type) from 3MF metadata.
  195. Args:
  196. file_path: Path to the 3MF file
  197. Returns:
  198. Dictionary mapping filament IDs to their properties:
  199. {filament_id: {"diameter": 1.75, "density": 1.24, "type": "PLA"}, ...}
  200. Note: filament_id is 1-based (matches slot_id in slice_info.config)
  201. """
  202. properties: dict[int, dict] = {}
  203. try:
  204. with zipfile.ZipFile(file_path, "r") as zf:
  205. # Try slice_info.config first for filament types
  206. if "Metadata/slice_info.config" in zf.namelist():
  207. content = zf.read("Metadata/slice_info.config").decode()
  208. root = ET.fromstring(content)
  209. for f in root.findall(".//filament"):
  210. try:
  211. # id is 1-based in slice_info.config
  212. fid = int(f.get("id", 0))
  213. properties[fid] = {
  214. "type": f.get("type", "PLA"),
  215. "diameter": DEFAULT_FILAMENT_DIAMETER,
  216. "density": DEFAULT_FILAMENT_DENSITY,
  217. }
  218. except ValueError:
  219. pass # Skip filament entries with unparseable IDs
  220. # Try project_settings.config for density values
  221. if "Metadata/project_settings.config" in zf.namelist():
  222. content = zf.read("Metadata/project_settings.config").decode()
  223. try:
  224. data = json.loads(content)
  225. densities = data.get("filament_density", [])
  226. for i, density in enumerate(densities):
  227. # project_settings uses 0-based indexing, convert to 1-based
  228. fid = i + 1
  229. if fid not in properties:
  230. properties[fid] = {
  231. "type": "",
  232. "diameter": DEFAULT_FILAMENT_DIAMETER,
  233. }
  234. try:
  235. properties[fid]["density"] = float(density)
  236. except (ValueError, TypeError):
  237. properties[fid]["density"] = DEFAULT_FILAMENT_DENSITY
  238. except json.JSONDecodeError:
  239. pass # Skip malformed project_settings.config JSON
  240. except Exception:
  241. pass # Return whatever properties were collected before the error
  242. return properties
  243. def _first_settings_id(value: object) -> str | None:
  244. """A ``*_settings_id`` value is usually a string, occasionally a list (one
  245. entry per extruder). Return the first non-empty string, else None."""
  246. if isinstance(value, str):
  247. return value.strip() or None
  248. if isinstance(value, list):
  249. for item in value:
  250. if isinstance(item, str) and item.strip():
  251. return item.strip()
  252. return None
  253. def extract_embedded_presets_from_3mf(zf: zipfile.ZipFile) -> dict[str, str | None]:
  254. """Read the printer / process preset names a 3MF project was prepared with.
  255. BambuStudio / OrcaSlicer write the chosen preset names into
  256. ``Metadata/project_settings.config`` (``printer_settings_id`` and
  257. ``print_settings_id``). The SliceModal uses them to default its printer
  258. and process dropdowns to what the file was sliced for (#1325) instead of
  259. blindly taking the first listed preset.
  260. Returns ``{"printer": <name|None>, "process": <name|None>}``. Every failure
  261. mode (missing config, malformed JSON, unexpected shape) yields ``None``
  262. values so the modal falls back to its own defaults.
  263. """
  264. result: dict[str, str | None] = {"printer": None, "process": None}
  265. try:
  266. if "Metadata/project_settings.config" not in zf.namelist():
  267. return result
  268. data = json.loads(zf.read("Metadata/project_settings.config").decode())
  269. except (KeyError, ValueError, OSError):
  270. return result
  271. if not isinstance(data, dict):
  272. return result
  273. result["printer"] = _first_settings_id(data.get("printer_settings_id"))
  274. result["process"] = _first_settings_id(data.get("print_settings_id"))
  275. return result
  276. # Ceiling on the dense per-slot form below. Deliberately larger than the 32
  277. # entries a print command carries, so a legitimate file is never silently
  278. # truncated at the limit -- it is either usable or rejected outright.
  279. _MAX_DENSE_FILAMENT_SLOTS = 64
  280. def extract_slot_extruders_from_3mf(file_path: Path, plate_id: int | None = None) -> list[int] | None:
  281. """Per-slot extruder assignment as a dense list, or None (#2800).
  282. Same data as :func:`extract_nozzle_mapping_from_3mf`, reshaped for the
  283. dispatcher: index 0 is filament slot 1, and a slot this file does not
  284. print is ``-1``. Nozzle-rack printers (H2C) need it to build the physical
  285. ``nozzle_mapping`` the firmware expects — without one they fall back to
  286. picking a nozzle themselves, which can level with one hotend and print
  287. with another, several millimetres off the bed.
  288. ``plate_id`` scopes the answer to the plate actually being dispatched. A
  289. multi-plate 3MF carries one filament list per plate and they need not
  290. agree, so without it a slot can take its extruder from a plate this print
  291. is not going to run.
  292. Takes a path rather than an open archive because the dispatcher is
  293. handling the file, not the zip, and a broken file there must not take the
  294. print down: an unreadable or non-3MF path returns None, and the caller
  295. dispatches exactly as it did before this existed.
  296. """
  297. try:
  298. with zipfile.ZipFile(file_path) as zf:
  299. by_slot = extract_nozzle_mapping_from_3mf(zf, plate_id=plate_id)
  300. except (zipfile.BadZipFile, OSError) as exc:
  301. logger.warning("Failed to read nozzle mapping from %s: %s", file_path, exc)
  302. return None
  303. if not by_slot:
  304. return None
  305. # The slot IDs are whatever the file says, so the dense form has to be
  306. # bounded before it is built: a corrupt or hostile 3MF declaring
  307. # `filament id="50000000"` would otherwise allocate a fifty-million-entry
  308. # list here, on the dispatch path. Nothing above 32 is usable anyway --
  309. # that is the length of the array the printer is sent.
  310. highest_slot = max(by_slot)
  311. if highest_slot < 1 or highest_slot > _MAX_DENSE_FILAMENT_SLOTS:
  312. logger.warning(
  313. "Ignoring nozzle mapping from %s: highest filament slot %s is out of range",
  314. file_path,
  315. highest_slot,
  316. )
  317. return None
  318. return [by_slot.get(slot, -1) for slot in range(1, highest_slot + 1)]
  319. @dataclass(frozen=True)
  320. class RackGroup:
  321. """One filament group on a nozzle-rack plate, and what hotend it needs.
  322. A group is the slicer's *logical* nozzle. On an H2C the rack carriage hosts
  323. six of them, so several groups share one extruder index -- which is exactly
  324. the case ``extract_nozzle_mapping_from_3mf`` refuses to answer, because the
  325. physical rack position per group is the operator's choice and is stated
  326. nowhere in the file.
  327. """
  328. group_id: int
  329. on_rack: bool
  330. nozzle_diameter: str
  331. volume_type: str
  332. # Only a hint, for preferring a rack position already loaded with this
  333. # colour. Excluded from equality on purpose: two filaments may share a
  334. # group and differ in colour without the group being contradictory, and
  335. # the agreement check below must not reject that file.
  336. filament_color: str = field(default="", compare=False)
  337. @dataclass(frozen=True)
  338. class RackPlan:
  339. """Everything a rack dispatch needs from the 3MF, short of the choice itself.
  340. ``slot_groups`` is dense: index 0 is filament slot 1, and a slot the plate
  341. does not print is ``-1``, matching :func:`extract_slot_extruders_from_3mf`.
  342. ``groups`` is keyed by group id.
  343. """
  344. slot_groups: list[int]
  345. groups: dict[int, RackGroup]
  346. @property
  347. def rack_group_ids(self) -> list[int]:
  348. """Groups needing a rack position, lowest first, for stable assignment."""
  349. return sorted(gid for gid, group in self.groups.items() if group.on_rack)
  350. def group_dicts(self) -> dict[int, dict]:
  351. """The groups as plain dicts, the form the resolver and the API take.
  352. Keeps one definition of the shape rather than two that can drift: the
  353. dispatcher resolves against it and the print dialog renders from it.
  354. """
  355. return {
  356. gid: {
  357. "on_rack": group.on_rack,
  358. "nozzle_diameter": group.nozzle_diameter,
  359. "volume_type": group.volume_type,
  360. "filament_color": group.filament_color,
  361. }
  362. for gid, group in self.groups.items()
  363. }
  364. def extract_rack_plan_from_3mf(file_path: Path, plate_id: int | None = None) -> RackPlan | None:
  365. """What a nozzle-rack plate needs per group, or None (#1784).
  366. :func:`extract_nozzle_mapping_from_3mf` answers "which carriage" and
  367. withholds the whole mapping when a plate needs several hotends off one
  368. rack. This answers the question underneath it -- which groups exist, which
  369. of them are rack-bound, and what nozzle each one wants -- so the caller can
  370. pair it with a chosen rack position and build a mapping the other function
  371. cannot.
  372. Measured basis (maintainer's H2C, 2026-08-14): the same plate was sent
  373. twice with different rack picks and every member of the two 3MFs was
  374. identical bar float noise -- ``group_id`` values, the toolchange stream and
  375. the ``NOZZLE_CHANGE`` markers included. The pick lives only in the
  376. dispatched ``nozzle_mapping``, so nothing here can or should derive it.
  377. Returns None whenever the plate cannot be described completely: a partial
  378. plan would place some slots and leave others at "not printed", which is the
  379. contradiction the firmware rejects as HMS 0500-4047.
  380. Takes a path rather than an open archive for the same reason
  381. :func:`extract_slot_extruders_from_3mf` does -- the dispatcher is holding
  382. the file, and a broken one must not take the print down.
  383. """
  384. try:
  385. with zipfile.ZipFile(file_path) as zf:
  386. return _rack_plan(zf, plate_id=plate_id)
  387. except (zipfile.BadZipFile, OSError) as exc:
  388. logger.warning("Failed to read rack plan from %s: %s", file_path, exc)
  389. return None
  390. except Exception:
  391. logger.exception("Unreadable rack plan in %s", file_path)
  392. return None
  393. def _rack_plan(zf: zipfile.ZipFile, plate_id: int | None) -> RackPlan | None:
  394. """Body of :func:`extract_rack_plan_from_3mf`, on an already-open archive."""
  395. names = zf.namelist()
  396. if "Metadata/project_settings.config" not in names:
  397. return None
  398. if "Metadata/slice_info.config" not in names:
  399. return None
  400. data = json.loads(zf.read("Metadata/project_settings.config").decode())
  401. physical_extruder_map = data.get("physical_extruder_map")
  402. if not physical_extruder_map or len(physical_extruder_map) <= 1:
  403. return None
  404. # Which extruder index is the rack, taken from the file rather than a
  405. # constant: the rack is the carriage that can address more than one nozzle.
  406. # `extruder_max_nozzle_count` is ['1', '6'] on an H2C, and reading it here
  407. # means a future rack of a different size needs no change.
  408. rack_indices: set[int] = set()
  409. for index, count in enumerate(data.get("extruder_max_nozzle_count") or []):
  410. try:
  411. if int(count) > 1:
  412. rack_indices.add(index)
  413. except (TypeError, ValueError):
  414. return None
  415. if not rack_indices:
  416. return None
  417. si_root = ET.fromstring(zf.read("Metadata/slice_info.config").decode())
  418. plates = _plates_in_scope(si_root, plate_id)
  419. group_extruders = _group_extruder_indices(plates)
  420. if not group_extruders:
  421. return None
  422. filament_elems = [elem for plate in plates for elem in plate.findall(".//filament")]
  423. if not filament_elems:
  424. return None
  425. slot_groups: dict[int, int] = {}
  426. groups: dict[int, RackGroup] = {}
  427. for elem in filament_elems:
  428. group_id_str = elem.get("group_id")
  429. slot_id_str = elem.get("id")
  430. if group_id_str is None or not slot_id_str:
  431. # One ungrouped filament makes the plan partial, and a partial plan
  432. # dispatches the ungrouped slot as unprinted.
  433. return None
  434. try:
  435. group_id = int(group_id_str)
  436. slot_id = int(slot_id_str)
  437. except (TypeError, ValueError):
  438. return None
  439. extruder_index = group_extruders.get(group_id)
  440. if extruder_index is None or not 0 <= extruder_index < len(physical_extruder_map):
  441. return None
  442. # Two plates in scope may name the same slot; they must agree, or the
  443. # dispatched plate is ambiguous.
  444. if slot_groups.setdefault(slot_id, group_id) != group_id:
  445. return None
  446. group = RackGroup(
  447. group_id=group_id,
  448. on_rack=extruder_index in rack_indices,
  449. nozzle_diameter=(elem.get("nozzle_diameter") or "").strip(),
  450. volume_type=(elem.get("volume_type") or "").strip(),
  451. filament_color=(elem.get("color") or "").strip(),
  452. )
  453. # Filaments sharing a group must want the same hotend, or "the group is
  454. # one nozzle" is not true and no single position can serve them.
  455. if groups.setdefault(group_id, group) != group:
  456. return None
  457. highest_slot = max(slot_groups)
  458. if highest_slot < 1 or highest_slot > _MAX_DENSE_FILAMENT_SLOTS:
  459. return None
  460. return RackPlan(
  461. slot_groups=[slot_groups.get(slot, -1) for slot in range(1, highest_slot + 1)],
  462. groups=groups,
  463. )
  464. def _plates_in_scope(si_root: XmlElement, plate_id: int | None) -> list[XmlElement]:
  465. """The ``<plate>`` elements a lookup should read, narrowed to one if asked.
  466. A 3MF holds every plate in the project, each with its own filament list, and
  467. two plates may assign the same slot to different extruders. Falls back to
  468. every plate when no id is given or none matches, which is what this module
  469. did before plates were distinguished at all.
  470. """
  471. plates = si_root.findall(".//plate")
  472. if not plates:
  473. return [si_root]
  474. if plate_id is None:
  475. return plates
  476. for plate in plates:
  477. for metadata in plate.findall("metadata"):
  478. if metadata.get("key") != "index":
  479. continue
  480. try:
  481. if int(metadata.get("value") or "") == plate_id:
  482. return [plate]
  483. except (TypeError, ValueError):
  484. pass
  485. return plates
  486. def _group_extruder_indices(plates: list[XmlElement]) -> dict[int, int] | None:
  487. """Map each filament group to the slicer extruder index it prints on.
  488. ``slice_info.config`` states this directly, as ``<nozzle id="<group>"
  489. extruder_id="<1-based extruder>"/>``. Reading it matters on nozzle-rack
  490. printers, where the group id is *not* an extruder index: the H2C's rack
  491. carriage can host six hotends (``extruder_max_nozzle_count`` is ``['1',
  492. '6']``), so the slicer emits more groups than the machine has extruders and
  493. several groups share one carriage. A plate of the reporter's carried groups
  494. 0, 1 and 2 against a two-entry ``physical_extruder_map``.
  495. Returns None when the file states no table, or when two plates in scope
  496. disagree about a group — in which case the caller keeps treating the group
  497. id as the extruder index, which is what every H2D file in practice wants
  498. and what this module has always done.
  499. """
  500. table: dict[int, int] = {}
  501. for plate in plates:
  502. for nozzle in plate.findall(".//nozzle"):
  503. try:
  504. group_id = int(nozzle.get("id") or "")
  505. extruder_index = int(nozzle.get("extruder_id") or "") - 1
  506. except (TypeError, ValueError):
  507. return None
  508. if extruder_index < 0:
  509. return None
  510. if table.setdefault(group_id, extruder_index) != extruder_index:
  511. return None
  512. return table or None
  513. def extract_nozzle_mapping_from_3mf(zf: zipfile.ZipFile, plate_id: int | None = None) -> dict[int, int] | None:
  514. """Extract per-slot nozzle/extruder mapping from a 3MF file.
  515. On dual-nozzle printers (H2D, H2D Pro), each filament slot is assigned to a
  516. specific nozzle. The slicer may override user preferences when using "Auto For
  517. Flush" mode, so the actual assignment comes from slice_info.config group_id
  518. attributes, not from the user's filament_nozzle_map preference.
  519. Priority:
  520. 1. group_id on <filament> elements in slice_info.config (actual assignment),
  521. resolved through the file's own group-to-extruder table
  522. 2. filament_nozzle_map in project_settings.config (user preference fallback)
  523. Both are mapped through physical_extruder_map to get MQTT extruder IDs (0=right, 1=left).
  524. Returns None rather than a partial answer whenever a filament the plate
  525. prints cannot be placed. The gap does not stay a gap downstream: the dense
  526. form fills it with -1, which already means "slot not printed", and
  527. dispatching that against an ams_mapping that *does* name a tray for the slot
  528. is a contradiction the firmware rejects outright with HMS 0500-4047, "the
  529. available hotend quantity or model does not match the sliced file". Giving
  530. no mapping at all costs only the firmware's own nozzle pick.
  531. Args:
  532. zf: An open ZipFile of the 3MF archive
  533. plate_id: 1-based plate to read, or None for every plate in the file
  534. Returns:
  535. Dictionary mapping {slot_id: extruder_id} for dual-nozzle files,
  536. or None if single-nozzle, missing data, unplaceable, or parse error.
  537. """
  538. try:
  539. if "Metadata/project_settings.config" not in zf.namelist():
  540. return None
  541. content = zf.read("Metadata/project_settings.config").decode()
  542. data = json.loads(content)
  543. physical_extruder_map = data.get("physical_extruder_map")
  544. if not physical_extruder_map or len(physical_extruder_map) <= 1:
  545. return None # Single-nozzle printer
  546. # Check if only one extruder is active.
  547. # If so, we can skip the mapping and just assign all slots to that extruder.
  548. # extruder_nozzle_stats format: ["Standard#0|High Flow#0", "Standard#1"]
  549. # Each entry = one extruder. Format: <NozzleVolumeType>#<count>[|...]
  550. # #N is the count of physical nozzles of that type (0 = none installed).
  551. # Types: Standard, High Flow, Hybrid, TPU High Flow
  552. active_extruders = []
  553. for stats_str in data.get("extruder_nozzle_stats") or []:
  554. nozzle_counts = [n.partition("#")[2] for n in stats_str.split("|")]
  555. active_extruders.append(1 if any(c not in ("0", "") for c in nozzle_counts) else 0)
  556. # Parse slice_info once: needed by both the single-active shortcut
  557. # (to verify the slice is actually single-group, #1825) and Priority 1.
  558. si_root: XmlElement | None = None
  559. filament_elems: list[XmlElement] = []
  560. group_extruders: dict[int, int] | None = None
  561. distinct_group_ids: set[int] = set()
  562. if "Metadata/slice_info.config" in zf.namelist():
  563. si_content = zf.read("Metadata/slice_info.config").decode()
  564. si_root = ET.fromstring(si_content)
  565. plates = _plates_in_scope(si_root, plate_id)
  566. group_extruders = _group_extruder_indices(plates)
  567. filament_elems = [elem for plate in plates for elem in plate.findall(".//filament")]
  568. for filament_elem in filament_elems:
  569. gid = filament_elem.get("group_id")
  570. if gid is not None:
  571. try:
  572. distinct_group_ids.add(int(gid))
  573. except (ValueError, TypeError):
  574. pass
  575. # Two groups on one extruder means that extruder is a nozzle rack,
  576. # and the plate wants a *different* hotend from it per group. Which
  577. # physical rack slot each group takes is the slicer's own choice
  578. # against the rack's live contents and is stated nowhere in the
  579. # file -- on the plate that prompted this, both rack groups carry
  580. # identical nozzle_diameter and volume_type, and BambuStudio still
  581. # dispatched them to positions 16 and 18 (captured 2026-08-13
  582. # 17:20; that print completed). Nothing here can reproduce that
  583. # choice, and answering anyway is what printed in mid-air, so the
  584. # whole mapping is withheld and the firmware picks for itself.
  585. if group_extruders and len(set(group_extruders.values())) < len(group_extruders):
  586. logger.warning(
  587. "Ignoring nozzle mapping: groups %s share extruders %s, so the plate "
  588. "needs more than one nozzle from a rack and the physical positions "
  589. "are not derivable from the file",
  590. sorted(group_extruders),
  591. sorted(set(group_extruders.values())),
  592. )
  593. return None
  594. # Single-active shortcut: only safe when the slice actually uses one
  595. # group. extruder_nozzle_stats can under-report a second installed
  596. # nozzle when its volume-type differs from the profile's enumerated
  597. # types (HT-AMS / High-Flow asymmetry on H2D, #1825); without this
  598. # guard the shortcut collapses a real multi-extruder slice onto one
  599. # nozzle and the group_id mapping below is skipped.
  600. if sum(active_extruders) == 1 and len(distinct_group_ids) <= 1:
  601. nozzle_mapping: dict[int, int] = {}
  602. active_idx = active_extruders.index(1)
  603. target_extruder = int(physical_extruder_map[active_idx])
  604. for filament_elem in filament_elems:
  605. try:
  606. nozzle_mapping[int(filament_elem.get("id"))] = target_extruder
  607. except (ValueError, TypeError):
  608. pass
  609. return nozzle_mapping or None
  610. # Priority 1: Use group_id from slice_info filament elements.
  611. # This reflects the actual slicer assignment (respects "Auto For Flush").
  612. nozzle_mapping: dict[int, int] = {}
  613. ungrouped = 0
  614. for filament_elem in filament_elems:
  615. group_id_str = filament_elem.get("group_id")
  616. filament_id_str = filament_elem.get("id")
  617. if not filament_id_str:
  618. continue
  619. if group_id_str is None:
  620. # Counted rather than returned on: a file where *no* filament
  621. # carries a group falls through to Priority 2 as it always has.
  622. # Only a file that groups some and not others is unplaceable.
  623. ungrouped += 1
  624. continue
  625. try:
  626. group_id = int(group_id_str)
  627. slot_id = int(filament_id_str)
  628. except (ValueError, TypeError):
  629. logger.warning(
  630. "Ignoring nozzle mapping: unreadable filament id=%r group_id=%r",
  631. filament_id_str,
  632. group_id_str,
  633. )
  634. return None
  635. # The group id is an extruder index only where the file states no
  636. # table of its own — true of every H2D slice, not of an H2C one.
  637. extruder_index = group_id if group_extruders is None else group_extruders.get(group_id)
  638. if extruder_index is None or not 0 <= extruder_index < len(physical_extruder_map):
  639. logger.warning(
  640. "Ignoring nozzle mapping: filament slot %s is in group %s, which "
  641. "resolves to extruder %r outside physical_extruder_map %r",
  642. slot_id,
  643. group_id,
  644. extruder_index,
  645. physical_extruder_map,
  646. )
  647. return None
  648. nozzle_mapping[slot_id] = int(physical_extruder_map[extruder_index])
  649. if nozzle_mapping and ungrouped:
  650. logger.warning(
  651. "Ignoring nozzle mapping: %d filament(s) carry no group_id while %d do, "
  652. "so the ungrouped slots would dispatch as unprinted",
  653. ungrouped,
  654. len(nozzle_mapping),
  655. )
  656. return None
  657. if nozzle_mapping:
  658. return nozzle_mapping
  659. # Priority 2: Fall back to filament_nozzle_map (user preference).
  660. # This is correct when the user manually assigned nozzles, but may be
  661. # wrong when the slicer overrides via "Auto For Flush".
  662. filament_nozzle_map = data.get("filament_nozzle_map")
  663. if not filament_nozzle_map:
  664. return None
  665. for i, slicer_ext_str in enumerate(filament_nozzle_map):
  666. slot_id = i + 1
  667. try:
  668. slicer_ext = int(slicer_ext_str)
  669. if slicer_ext < len(physical_extruder_map):
  670. nozzle_mapping[slot_id] = int(physical_extruder_map[slicer_ext])
  671. except (ValueError, TypeError, IndexError):
  672. pass
  673. return nozzle_mapping if nozzle_mapping else None
  674. except Exception:
  675. return None
  676. @dataclass(frozen=True)
  677. class PlateMetadata:
  678. """Combined per-plate slice_info.config values from a single 3MF parse.
  679. Bundles the three fields the queue listing needs so a queue poll opens and
  680. parses each 3MF once instead of three times (#2573). ``filament_usage`` is
  681. the full per-filament list (other callers — usage tracking, Spoolman — need
  682. it); ``filament_used_grams`` is its ``used_g`` sum, precomputed here so the
  683. queue path doesn't re-sum on every hit.
  684. """
  685. print_time_seconds: int | None = None
  686. filament_usage: list[dict] = field(default_factory=list)
  687. bed_type: str | None = None
  688. filament_used_grams: float = 0.0
  689. _EMPTY_PLATE_METADATA = PlateMetadata()
  690. # Revision-keyed cache for parsed per-plate metadata. Queue polling re-lists the
  691. # same unchanged 3MFs every few seconds per connected client (#2573); without a
  692. # cache each row costs a ZIP open + XML parse. The key includes the file's
  693. # mtime_ns and size so a replaced or edited file transparently gets a fresh
  694. # entry — no manual invalidation needed. Bounded LRU + lock so it stays small
  695. # and is safe to touch from worker threads.
  696. _PLATE_METADATA_CACHE: "OrderedDict[tuple, PlateMetadata]" = OrderedDict()
  697. _PLATE_METADATA_CACHE_LOCK = Lock()
  698. _PLATE_METADATA_CACHE_MAX = 512
  699. def clear_plate_metadata_cache() -> None:
  700. """Drop all cached per-plate metadata (used by tests)."""
  701. with _PLATE_METADATA_CACHE_LOCK:
  702. _PLATE_METADATA_CACHE.clear()
  703. def _parse_plate_metadata_uncached(file_path: Path, plate_id: int | None) -> PlateMetadata:
  704. """Open the 3MF once and pull print time, filament usage and bed type.
  705. Replicates the per-field ``plate_id=None`` behaviour of the three legacy
  706. helpers exactly: usage collects every ``<filament>`` in the file, while
  707. print time and bed type come from the first ``<plate>``.
  708. """
  709. try:
  710. with zipfile.ZipFile(file_path, "r") as zf:
  711. if "Metadata/slice_info.config" not in zf.namelist():
  712. return _EMPTY_PLATE_METADATA
  713. content = zf.read("Metadata/slice_info.config").decode()
  714. root = ET.fromstring(content)
  715. except Exception as e:
  716. logger.warning("Failed to read plate metadata from %s: %s", file_path, e)
  717. return _EMPTY_PLATE_METADATA
  718. def _plate_index(plate_elem) -> int | None:
  719. for meta in plate_elem.findall("metadata"):
  720. if meta.get("key") == "index":
  721. try:
  722. return int(meta.get("value", "0"))
  723. except ValueError:
  724. return None
  725. return None
  726. def _collect_filaments(plate_elem) -> list[dict]:
  727. out: list[dict] = []
  728. for f in plate_elem.findall("filament"):
  729. filament_id = f.get("id")
  730. # Both the used_g float() and the id int() must stay inside the guard:
  731. # a non-numeric id or used_g is silently skipped (matches the legacy
  732. # helpers, which tolerated garbage rows rather than raising — a raise
  733. # here would 500 the whole queue listing).
  734. try:
  735. used_amount = float(f.get("used_g", "0"))
  736. if filament_id:
  737. out.append(
  738. {
  739. "slot_id": int(filament_id),
  740. "used_g": used_amount,
  741. "type": f.get("type", ""),
  742. "color": f.get("color", ""),
  743. }
  744. )
  745. except (ValueError, TypeError):
  746. continue
  747. return out
  748. print_time: int | None = None
  749. bed_type: str | None = None
  750. filament_usage: list[dict] = []
  751. matched_plate = None
  752. if plate_id is not None:
  753. for plate_elem in root.findall(".//plate"):
  754. if _plate_index(plate_elem) == plate_id:
  755. matched_plate = plate_elem
  756. break
  757. else:
  758. matched_plate = root.find(".//plate")
  759. if matched_plate is not None:
  760. for meta in matched_plate.findall("metadata"):
  761. key = meta.get("key")
  762. if key == "prediction" and print_time is None:
  763. try:
  764. print_time = int(meta.get("value", "0"))
  765. except ValueError:
  766. print_time = None
  767. elif key == "curr_bed_type" and meta.get("value"):
  768. bed_type = (meta.get("value") or "").strip()
  769. if plate_id is not None:
  770. if matched_plate is not None:
  771. filament_usage = _collect_filaments(matched_plate)
  772. else:
  773. # Legacy plate_id=None usage: every filament in the file, not just plate 1.
  774. for f in root.findall(".//filament"):
  775. filament_id = f.get("id")
  776. # int()/float() both guarded — a garbage id/used_g row is skipped, not raised.
  777. try:
  778. used_amount = float(f.get("used_g", "0"))
  779. if filament_id:
  780. filament_usage.append(
  781. {
  782. "slot_id": int(filament_id),
  783. "used_g": used_amount,
  784. "type": f.get("type", ""),
  785. "color": f.get("color", ""),
  786. }
  787. )
  788. except (ValueError, TypeError):
  789. continue
  790. return PlateMetadata(
  791. print_time_seconds=print_time,
  792. filament_usage=filament_usage,
  793. bed_type=bed_type,
  794. filament_used_grams=sum(f["used_g"] for f in filament_usage),
  795. )
  796. def extract_plate_metadata_from_3mf(file_path: Path, plate_id: int | None = None) -> PlateMetadata:
  797. """Return combined per-plate metadata, cached by file revision (#2573).
  798. The result is keyed by ``(path, plate_id, mtime_ns, size)`` so an unchanged
  799. file is parsed at most once; a replaced/edited file re-parses automatically.
  800. The returned ``PlateMetadata`` is shared and MUST be treated as read-only —
  801. callers that need a mutable filament list get a copy from the wrappers below.
  802. """
  803. file_path = Path(file_path)
  804. try:
  805. stat = file_path.stat()
  806. except OSError:
  807. # File missing/unreadable: parse (which will return empty) but don't
  808. # cache — the file may appear later and we don't want a sticky miss.
  809. return _parse_plate_metadata_uncached(file_path, plate_id)
  810. key = (str(file_path), plate_id, stat.st_mtime_ns, stat.st_size)
  811. with _PLATE_METADATA_CACHE_LOCK:
  812. cached = _PLATE_METADATA_CACHE.get(key)
  813. if cached is not None:
  814. _PLATE_METADATA_CACHE.move_to_end(key)
  815. return cached
  816. metadata = _parse_plate_metadata_uncached(file_path, plate_id)
  817. with _PLATE_METADATA_CACHE_LOCK:
  818. _PLATE_METADATA_CACHE[key] = metadata
  819. _PLATE_METADATA_CACHE.move_to_end(key)
  820. while len(_PLATE_METADATA_CACHE) > _PLATE_METADATA_CACHE_MAX:
  821. _PLATE_METADATA_CACHE.popitem(last=False)
  822. return metadata
  823. def extract_filament_usage_from_3mf(file_path: Path, plate_id: int | None = None) -> list[dict]:
  824. """Extract per-filament total usage from 3MF slice_info.config.
  825. This extracts the slicer-estimated total usage per filament slot,
  826. not the per-layer breakdown.
  827. Args:
  828. file_path: Path to the 3MF file
  829. plate_id: Optional plate index to filter for (for multi-plate files)
  830. Returns:
  831. List of filament usage dictionaries:
  832. [{"slot_id": 1, "used_g": 50.5, "type": "PLA", "color": "#FF0000"}, ...]
  833. """
  834. # Delegate to the cached combined parse (#2573). Return fresh dicts so callers
  835. # that mutate the list don't corrupt the shared cached PlateMetadata.
  836. return [dict(f) for f in extract_plate_metadata_from_3mf(file_path, plate_id).filament_usage]
  837. def extract_print_time_from_3mf(file_path: Path, plate_id: int | None = None) -> int | None:
  838. """Extract the slicer's predicted print time from a 3MF's slice_info.config.
  839. Multi-plate 3MFs carry one ``<plate><metadata key="prediction" .../></plate>``
  840. per plate. The archive-level `print_time_seconds` is the sum across all plates
  841. (see services/archive.py:200-264, #1593). For per-plate UI / notifications,
  842. callers re-read the 3MF and request the specific plate's value via this helper.
  843. Args:
  844. file_path: Path to the 3MF file
  845. plate_id: Plate index to filter for; if None, returns the first plate's
  846. ``prediction`` (matches the legacy single-plate read).
  847. Returns:
  848. Predicted print time in seconds, or None if not found / unparseable.
  849. """
  850. return extract_plate_metadata_from_3mf(file_path, plate_id).print_time_seconds
  851. def extract_bed_type_from_3mf(file_path: Path, plate_id: int | None = None) -> str | None:
  852. """Extract the build plate type (`curr_bed_type`) for a specific plate (#1281).
  853. ``archive.bed_type`` is captured at ingest time but is one value per archive
  854. (the first plate's `curr_bed_type` — see services/archive.py:235). For a
  855. multi-plate 3MF where different plates target different beds (e.g. a 40-plate
  856. file mixing PEI + Engineering), the archive-level value lies. When a queue
  857. item or print modal targets a specific plate, this re-reads the 3MF and
  858. returns that plate's actual bed type.
  859. Args:
  860. file_path: Path to the 3MF file
  861. plate_id: Plate index to filter for; if None, returns the first plate's
  862. ``curr_bed_type`` (matches the archive-level capture).
  863. Returns:
  864. Bed type string (e.g. "Textured PEI Plate"), or None if not found.
  865. """
  866. return extract_plate_metadata_from_3mf(file_path, plate_id).bed_type
  867. # Header values exposed as `{placeholder}` substitutions inside snippets.
  868. # Aliases let users write Prusa-style names (`{max_layer_z}`) that map onto
  869. # Bambu/Orca header keys (`max_z_height`).
  870. _HEADER_PLACEHOLDER_ALIASES = {
  871. "max_layer_z": "max_z_height",
  872. "max_print_height": "max_z_height",
  873. "total_layers": "total_layer_number",
  874. }
  875. _HEADER_KEY_RE = re.compile(r"^;\s*([^:]+?)\s*:\s*(.+?)\s*$")
  876. _PLACEHOLDER_RE = re.compile(r"\{([a-zA-Z_][a-zA-Z0-9_]*)\}")
  877. _START_GCODE_END_MARKER = "; MACHINE_START_GCODE_END"
  878. _EXECUTABLE_BLOCK_END_MARKER = "; EXECUTABLE_BLOCK_END"
  879. def _parse_3mf_gcode_header(content: str) -> dict[str, str]:
  880. """Parse the `; HEADER_BLOCK_START..END` block into a normalised dict.
  881. Keys are lowercased, ` [units]` suffixes stripped, and spaces converted
  882. to underscores so callers can look up `total_layer_number` regardless of
  883. whether the source line is `; total layer number: 80` or
  884. `; total filament length [mm] : 12155.34`.
  885. """
  886. header: dict[str, str] = {}
  887. in_header = False
  888. for raw_line in content.splitlines():
  889. line = raw_line.strip()
  890. if line == "; HEADER_BLOCK_START":
  891. in_header = True
  892. continue
  893. if line == "; HEADER_BLOCK_END":
  894. break
  895. if not in_header:
  896. continue
  897. m = _HEADER_KEY_RE.match(line)
  898. if not m:
  899. continue
  900. key, value = m.group(1), m.group(2)
  901. key = re.sub(r"\s*\[[^\]]*\]\s*$", "", key)
  902. key = key.strip().lower().replace(" ", "_")
  903. header[key] = value
  904. return header
  905. def _plate_number_of(name: str) -> int | None:
  906. """Plate index encoded in a ``…/plate_<n>.gcode`` member, or None.
  907. Parsed as an int rather than string-matched so a zero-padded
  908. ``plate_01.gcode`` resolves to the same 1 the plates endpoint reports.
  909. """
  910. marker = "plate_"
  911. idx = name.rfind(marker)
  912. if idx < 0 or not name.endswith(".gcode"):
  913. return None
  914. try:
  915. return int(name[idx + len(marker) : -len(".gcode")])
  916. except ValueError:
  917. return None
  918. def select_plate_gcode_name(names: list[str], plate_id: int | None) -> str | None:
  919. """The ``.gcode`` member for exactly ``plate_id``, or None if it isn't there.
  920. Returns None for a ``plate_id`` the file doesn't hold — callers that want a
  921. fallback compose this with ``default_plate_gcode_name``; callers serving a
  922. user's explicit plate choice want the None so they can 404 instead of
  923. quietly rendering a different plate.
  924. """
  925. if plate_id is None:
  926. return None
  927. for name in names:
  928. if name.endswith(".gcode") and _plate_number_of(name) == plate_id:
  929. return name
  930. return None
  931. def default_plate_gcode_name(names: list[str]) -> str | None:
  932. """The ``.gcode`` member to show when no plate was asked for.
  933. The lowest plate number, NOT the first member in the archive: zip order is
  934. whatever the slicer happened to write, and Bambu Studio does not write
  935. plates in order — a two-plate file measured here stores ``plate_2.gcode``
  936. ahead of ``plate_1.gcode``, so taking the first member opened plate 2. Files
  937. from slicers that don't use the plate naming convention keep the old
  938. first-member behaviour, since there is no numbering to sort by.
  939. """
  940. gcodes = [n for n in names if n.endswith(".gcode")]
  941. if not gcodes:
  942. return None
  943. numbered = [(num, n) for n in gcodes if (num := _plate_number_of(n)) is not None]
  944. if numbered:
  945. return min(numbered)[1]
  946. return gcodes[0]
  947. # The header block sits at the very top of the plate G-code. Read only that
  948. # much: a sliced plate is routinely tens of megabytes and `ZipFile.read()`
  949. # would inflate all of it to reach ~40 lines.
  950. _HEADER_READ_LIMIT_BYTES = 64 * 1024
  951. def extract_max_z_height_from_3mf(file_path: Path, plate_id: int | None = None) -> float | None:
  952. """Return the plate's ``max_z_height`` in mm, or None if not knowable.
  953. This is the Z the toolhead sat at for the final layer — the same value
  954. Bambu's own end G-code adds its bed-drop offset to (``G1 Z{max_layer_z +
  955. 100}``). #2547 uses it to put the plate back into camera framing before the
  956. finish photo, which is only safe because it is a height the printer was
  957. physically at seconds earlier.
  958. None means "don't know" and callers must treat it as such rather than
  959. substituting a default: the file may be unreadable, carry no plate G-code,
  960. or come from a slicer that writes no ``max_z_height`` header. Guessing a
  961. height here would command a Z move to somewhere the nozzle has never been.
  962. """
  963. try:
  964. with zipfile.ZipFile(file_path, "r") as zf:
  965. names = zf.namelist()
  966. target = select_plate_gcode_name(names, plate_id) or default_plate_gcode_name(names)
  967. if target is None:
  968. return None
  969. with zf.open(target, "r") as fh:
  970. head = fh.read(_HEADER_READ_LIMIT_BYTES)
  971. except (OSError, zipfile.BadZipFile, KeyError) as e:
  972. logger.debug("max_z_height: cannot read %s: %s", file_path, e)
  973. return None
  974. raw = _parse_3mf_gcode_header(head.decode("utf-8", errors="ignore")).get("max_z_height")
  975. if raw is None:
  976. return None
  977. try:
  978. value = float(raw)
  979. except ValueError:
  980. logger.debug("max_z_height: unusable value %r in %s", raw, file_path)
  981. return None
  982. # Zero or negative means the header key is present but meaningless. Passed
  983. # on as a height it would become a move *toward* the bed, so drop it.
  984. return value if value > 0 else None
  985. def _substitute_placeholders(snippet: str, header: dict[str, str]) -> str:
  986. """Replace `{var}` placeholders with header values, leaving unknowns intact."""
  987. def repl(m: re.Match) -> str:
  988. name = m.group(1)
  989. value = header.get(name)
  990. if value is None:
  991. alias = _HEADER_PLACEHOLDER_ALIASES.get(name)
  992. if alias is not None:
  993. value = header.get(alias)
  994. if value is None:
  995. logger.warning(
  996. "G-code injection: placeholder {%s} not found in 3MF header; leaving as-is",
  997. name,
  998. )
  999. return m.group(0)
  1000. return value
  1001. return _PLACEHOLDER_RE.sub(repl, snippet)
  1002. def _inject_start_at_marker(content: str, snippet: str) -> str:
  1003. """Insert snippet immediately before `; MACHINE_START_GCODE_END`.
  1004. The marker sits at the bottom of the printer's startup block — bed heat,
  1005. homing, and nozzle prime are already done, so injected snippets land in
  1006. the same place a slicer-side custom-start-gcode would. Falls back to
  1007. prepending if the marker isn't present (older files / non-Bambu slicers).
  1008. """
  1009. marker_idx = content.find(_START_GCODE_END_MARKER)
  1010. if marker_idx == -1:
  1011. logger.warning(
  1012. "G-code injection: '%s' not found, prepending start snippet to whole file",
  1013. _START_GCODE_END_MARKER,
  1014. )
  1015. return snippet.rstrip("\n") + "\n" + content
  1016. line_start = content.rfind("\n", 0, marker_idx)
  1017. line_start = 0 if line_start == -1 else line_start + 1
  1018. return content[:line_start] + snippet.rstrip("\n") + "\n" + content[line_start:]
  1019. def _inject_end_before_marker(content: str, snippet: str) -> str:
  1020. """Insert snippet immediately before `; EXECUTABLE_BLOCK_END`.
  1021. The end snippet must run *inside* the executable block. Bambu firmware
  1022. (verified on a P1S) does not execute G-code that sits after
  1023. `; EXECUTABLE_BLOCK_END`, so appending to the file end silently drops the
  1024. snippet — auto-eject / plate-clear moves never fire. Inserting before the
  1025. marker places the snippet after the printer's own machine-end sequence but
  1026. still within the executed block. Falls back to appending at the file end if
  1027. the marker isn't present.
  1028. """
  1029. marker_idx = content.find(_EXECUTABLE_BLOCK_END_MARKER)
  1030. if marker_idx == -1:
  1031. logger.warning(
  1032. "G-code injection: '%s' not found, appending end snippet to file end",
  1033. _EXECUTABLE_BLOCK_END_MARKER,
  1034. )
  1035. return content.rstrip("\n") + "\n" + snippet.rstrip("\n") + "\n"
  1036. line_start = content.rfind("\n", 0, marker_idx)
  1037. line_start = 0 if line_start == -1 else line_start + 1
  1038. return content[:line_start] + snippet.rstrip("\n") + "\n" + content[line_start:]
  1039. def inject_gcode_into_3mf(
  1040. source_path: Path,
  1041. plate_id: int,
  1042. start_gcode: str | None,
  1043. end_gcode: str | None,
  1044. ):
  1045. """Create a temp copy of a 3MF with G-code injected at start/end.
  1046. Snippets support `{placeholder}` substitution against values parsed from
  1047. the 3MF G-code header block (e.g. `{max_layer_z}` → `16.00`). Start
  1048. snippets are anchored to the `; MACHINE_START_GCODE_END` marker so they
  1049. run after the printer's own startup (#422). End snippets are inserted just
  1050. before `; EXECUTABLE_BLOCK_END` so they run inside the executable block —
  1051. Bambu firmware (P1S) ignores g-code placed after that marker.
  1052. The plate's `.gcode.md5` sidecar is recomputed so firmware that validates
  1053. it against the gcode (e.g. P1S) still accepts the modified file.
  1054. Args:
  1055. source_path: Path to the original 3MF file.
  1056. plate_id: Plate number (1-indexed) to inject into.
  1057. start_gcode: G-code to insert after printer startup, or None.
  1058. end_gcode: G-code to append, or None.
  1059. Returns:
  1060. Path to temp file with injected G-code, or None if injection failed.
  1061. Caller is responsible for cleaning up the temp file.
  1062. """
  1063. import tempfile
  1064. if not start_gcode and not end_gcode:
  1065. return None
  1066. try:
  1067. # Find the target gcode file inside the 3MF
  1068. with zipfile.ZipFile(source_path, "r") as zf:
  1069. # Plate-specific gcode first, else the lowest-numbered plate.
  1070. names = zf.namelist()
  1071. target_gcode = select_plate_gcode_name(names, plate_id) or default_plate_gcode_name(names)
  1072. if target_gcode is None:
  1073. return None
  1074. # Read and modify gcode content
  1075. gcode_content = zf.read(target_gcode).decode("utf-8", errors="ignore")
  1076. header = _parse_3mf_gcode_header(gcode_content)
  1077. if start_gcode:
  1078. resolved = _substitute_placeholders(start_gcode, header)
  1079. # Log the post-substitution snippet so the actually-injected G-code
  1080. # (placeholders like {max_layer_z} already resolved) is visible at DEBUG.
  1081. logger.debug("G-code injection [%s]: resolved START snippet:\n%s", target_gcode, resolved)
  1082. gcode_content = _inject_start_at_marker(gcode_content, resolved)
  1083. if end_gcode:
  1084. resolved = _substitute_placeholders(end_gcode, header)
  1085. logger.debug("G-code injection [%s]: resolved END snippet:\n%s", target_gcode, resolved)
  1086. gcode_content = _inject_end_before_marker(gcode_content, resolved)
  1087. # The printer validates the plate gcode against an embedded
  1088. # `<plate>.gcode.md5` sidecar (uppercase hex, no trailing newline).
  1089. # Rewriting the gcode without refreshing this hash makes firmware
  1090. # reject the file at load (P1S: HMS 0500-4003 "unable to parse"),
  1091. # so recompute it from the exact bytes we're about to write.
  1092. gcode_bytes = gcode_content.encode("utf-8")
  1093. md5_name = target_gcode + ".md5"
  1094. # Not a security hash — this reproduces Bambu's `.gcode.md5` sidecar
  1095. # format, so flag it as non-security for the linters (ruff S324 / bandit B324).
  1096. md5_value = hashlib.md5(gcode_bytes, usedforsecurity=False).hexdigest().upper().encode("ascii")
  1097. # Write modified 3MF to temp file
  1098. with tempfile.NamedTemporaryFile(delete=False, suffix=".3mf") as tmp:
  1099. tmp_path = Path(tmp.name)
  1100. with zipfile.ZipFile(tmp_path, "w", zipfile.ZIP_DEFLATED) as zf_write:
  1101. for item in zf.namelist():
  1102. info = zf.getinfo(item)
  1103. if item == target_gcode:
  1104. zf_write.writestr(info, gcode_bytes)
  1105. elif item == md5_name:
  1106. zf_write.writestr(info, md5_value)
  1107. else:
  1108. zf_write.writestr(info, zf.read(item))
  1109. return tmp_path
  1110. except Exception:
  1111. # Clean up temp file on error
  1112. if "tmp_path" in locals() and tmp_path.exists():
  1113. tmp_path.unlink(missing_ok=True)
  1114. return None
  1115. def extract_project_filaments_from_3mf(zf: zipfile.ZipFile) -> list[dict]:
  1116. """Project-wide AMS slot config from ``Metadata/project_settings.config``.
  1117. Returns one dict per configured AMS slot in slot order (1-indexed), with
  1118. ``type`` and ``color`` populated from the project's ``filament_type`` and
  1119. ``filament_colour`` arrays. ``used_grams`` / ``used_meters`` are 0 because
  1120. project_settings carries the configuration, not per-print usage — the
  1121. fields exist for shape compatibility with the slice_info-derived list.
  1122. The SliceModal needs this on **unsliced** project files: slice_info.config
  1123. is empty until Bambu Studio has actually sliced the project, but the user
  1124. can still pick filament profiles for a slice we're about to perform.
  1125. """
  1126. if "Metadata/project_settings.config" not in zf.namelist():
  1127. return []
  1128. try:
  1129. proj = json.loads(zf.read("Metadata/project_settings.config").decode())
  1130. except (ValueError, OSError):
  1131. return []
  1132. if not isinstance(proj, dict):
  1133. return []
  1134. types_arr = proj.get("filament_type") or []
  1135. colors_arr = proj.get("filament_colour") or []
  1136. slot_count = max(
  1137. len(types_arr) if isinstance(types_arr, list) else 0, len(colors_arr) if isinstance(colors_arr, list) else 0
  1138. )
  1139. out: list[dict] = []
  1140. for i in range(slot_count):
  1141. out.append(
  1142. {
  1143. "slot_id": i + 1,
  1144. "type": types_arr[i] if i < len(types_arr) and isinstance(types_arr[i], str) else "",
  1145. "color": colors_arr[i] if i < len(colors_arr) and isinstance(colors_arr[i], str) else "",
  1146. "used_grams": 0,
  1147. "used_meters": 0,
  1148. }
  1149. )
  1150. return out
  1151. def expand_to_project_slots(zf: zipfile.ZipFile, used: list[dict]) -> list[dict]:
  1152. """Widen a used-only filament list to one entry per project slot.
  1153. ``used`` is the slice_info-derived list: only the slots whose G-code
  1154. actually consumed filament, each carrying real usage figures. That is the
  1155. right answer for print-time AMS matching, and the wrong one for the slice
  1156. modal, because the list the modal builds is **positional** — index 0 is
  1157. slot 1 all the way down to the ``filament_N.json`` parts handed to the CLI.
  1158. A source whose only used slot is 4 therefore produced a single dropdown
  1159. whose pick the CLI bound to slot 1, leaving slot 4 — the one the model
  1160. prints with — on whatever the source had baked in (#2712).
  1161. Returns the project's slots in slot order, each flagged ``used_in_plate``.
  1162. Rows present in ``used`` are kept whole, so their usage figures, resolved
  1163. type/colour and ``tray_info_idx`` survive; the rest come from the project
  1164. configuration with zero usage. A used slot beyond the project's slot count
  1165. is appended rather than dropped — the caller asked for a superset, and
  1166. silently losing the one slot that prints would be the original bug again.
  1167. ``used`` is returned unchanged when the file carries no project settings
  1168. to widen against: a narrower-than-ideal list still prints correctly, an
  1169. invented one might not.
  1170. """
  1171. project = extract_project_filaments_from_3mf(zf)
  1172. if not project:
  1173. return used
  1174. by_slot = {f["slot_id"]: f for f in used}
  1175. out: list[dict] = []
  1176. for slot in project:
  1177. known = by_slot.pop(slot["slot_id"], None)
  1178. if known is not None:
  1179. known["used_in_plate"] = True
  1180. out.append(known)
  1181. else:
  1182. slot["used_in_plate"] = False
  1183. out.append(slot)
  1184. # Anything slice_info reported that the project doesn't declare.
  1185. for leftover in by_slot.values():
  1186. leftover["used_in_plate"] = True
  1187. out.append(leftover)
  1188. out.sort(key=lambda f: f["slot_id"])
  1189. return out
  1190. # BambuStudio serialises bool config options as string "1"/"0" in
  1191. # project_settings.config, but forks / older versions occasionally write real
  1192. # booleans or ints — accept anything that isn't unambiguously falsy. A missing
  1193. # key counts as off: a 3MF that never declares `enable_support` gives us no
  1194. # support intent to act on.
  1195. _SUPPORTS_DISABLED_VALUES = (False, 0, "0", "false", "False", "", None)
  1196. def supports_enabled_in_config(cfg: dict[str, object]) -> bool:
  1197. """Whether a 3MF's ``project_settings.config`` has supports switched on.
  1198. Shared by the callers that read support intent out of a source file so
  1199. they agree on what "on" means: the slot extractor below and the slice
  1200. route's process-preset support carry-over (#1881 / #2820).
  1201. """
  1202. return cfg.get("enable_support") not in _SUPPORTS_DISABLED_VALUES
  1203. def extract_support_filament_slots_from_3mf(zf: zipfile.ZipFile) -> set[int]:
  1204. """Slots referenced by the process settings for support material.
  1205. Supports aren't attached to object geometry — they're generated by
  1206. the slicer's process pass — so :func:`extract_plate_extruder_set_from_3mf`,
  1207. which walks per-object extruder metadata + paint_color triangles,
  1208. doesn't see them. Callers that need the complete set of slots a
  1209. plate print will exercise (e.g. the SliceModal's filament-
  1210. substitution logic) must union this in — otherwise a support-only
  1211. slot (typical PLA-model + PVA-support setup) looks "unused" and its
  1212. user-picked profile gets silently overwritten with slot 1's,
  1213. producing a single-material print (#1881).
  1214. Returns the empty set when supports are disabled, ``support_filament``
  1215. / ``support_interface_filament`` are 0 (== "same as model"), the
  1216. project has no embedded settings, or the file isn't a valid 3MF.
  1217. """
  1218. if "Metadata/project_settings.config" not in zf.namelist():
  1219. return set()
  1220. try:
  1221. cfg = json.loads(zf.read("Metadata/project_settings.config").decode("utf-8"))
  1222. except (json.JSONDecodeError, UnicodeDecodeError, OSError):
  1223. return set()
  1224. if not isinstance(cfg, dict):
  1225. return set()
  1226. if not supports_enabled_in_config(cfg):
  1227. return set()
  1228. out: set[int] = set()
  1229. for key in ("support_filament", "support_interface_filament"):
  1230. raw = cfg.get(key)
  1231. if raw is None:
  1232. continue
  1233. try:
  1234. slot = int(raw)
  1235. except (ValueError, TypeError):
  1236. continue
  1237. # Slot 0 means "same as model" — no dedicated slot to preserve.
  1238. if slot > 0:
  1239. out.add(slot)
  1240. return out
  1241. _PAINT_COLOR_ATTR_RE = re.compile(rb'paint_color="([0-9A-Fa-f]+)"')
  1242. # Painted-face quadtree leaves include both real filament assignments and
  1243. # tiny edit artifacts (single-leaf accidents from "tried a colour, undid,
  1244. # repainted with a different one"). The threshold's only job is dropping
  1245. # accidents — anything the user spent meaningful effort on must survive.
  1246. # 5% of an object's painted triangles is well below any 60/40 / 70/30 /
  1247. # 33/33/33 split a real two- or three-colour print would hit, so all
  1248. # intentional colours are kept; one-off single-leaf paints (typically
  1249. # 0.1-1.5% in observed projects) are filtered. Note that this fallback
  1250. # path runs ONLY when the preview-slice path can't reach the sidecar; in
  1251. # the normal flow the slicer's own pruning produces the canonical list and
  1252. # this threshold isn't reached.
  1253. _PAINT_NOISE_THRESHOLD = 0.05
  1254. def extract_plate_extruder_set_from_3mf(zf: zipfile.ZipFile, plate_id: int) -> set[int]:
  1255. """Extruder/AMS slot indices (1-indexed) used by objects on ``plate_id``.
  1256. Three sources are unioned because Bambu Studio splits per-object extruder
  1257. info across THREE places depending on how the user assigned colours:
  1258. 1. ``model_settings.config`` — top-level ``<metadata key="extruder">``
  1259. on each ``<object>`` (the "default extruder" for the whole object).
  1260. 2. ``model_settings.config`` — per-``<part>`` ``<metadata key="extruder">``
  1261. overrides (used when the user split an object into multiple parts
  1262. with distinct filaments).
  1263. 3. ``3D/Objects/object_*.model`` — ``paint_color`` attributes on
  1264. individual ``<triangle>`` elements (used when the user "painted" a
  1265. face with a different filament). The encoding is a hex string where
  1266. each nibble is a TriangleSelector tree node: ``0`` = unpainted leaf,
  1267. ``F`` = branch (4 children follow), ``1``..``E`` = leaf painted with
  1268. extruder N. We don't decode the tree — every leaf-paint nibble in
  1269. the string IS the extruder number, so a flat scan over hex chars
  1270. yields the correct set without recursive parsing.
  1271. Without (3) the painted-face data is invisible: model_settings says
  1272. every object on a multi-color plate uses extruder 1 by default but the
  1273. actual print uses 3, 4, 12 etc. via face paint, so the SliceModal would
  1274. render only one filament dropdown for what's clearly a multi-colour
  1275. print (#1150 follow-up).
  1276. """
  1277. if "Metadata/model_settings.config" not in zf.namelist():
  1278. return set()
  1279. try:
  1280. root = ET.fromstring(zf.read("Metadata/model_settings.config").decode())
  1281. except (ET.ParseError, OSError):
  1282. return set()
  1283. # Pass 1: object → set of extruders from XML metadata (sources 1 + 2)
  1284. # plus the per-object .model file path so we can later scan source 3.
  1285. object_extruders: dict[str, set[int]] = {}
  1286. object_model_paths: dict[str, list[str]] = {}
  1287. for obj_elem in root.findall(".//object"):
  1288. obj_id = obj_elem.get("id")
  1289. if not obj_id:
  1290. continue
  1291. extruders: set[int] = set()
  1292. top = obj_elem.find("metadata[@key='extruder']")
  1293. if top is not None:
  1294. try:
  1295. v = int(top.get("value", "0"))
  1296. if v > 0:
  1297. extruders.add(v)
  1298. except (ValueError, TypeError):
  1299. pass
  1300. for part_elem in obj_elem.findall(".//part"):
  1301. part_ext = part_elem.find("metadata[@key='extruder']")
  1302. if part_ext is None:
  1303. continue
  1304. try:
  1305. v = int(part_ext.get("value", "0"))
  1306. if v > 0:
  1307. extruders.add(v)
  1308. except (ValueError, TypeError):
  1309. pass
  1310. object_extruders[obj_id] = extruders
  1311. # Pass 2: 3dmodel.model maps each <object id="N"> to its component
  1312. # .model file path(s). Bambu wraps object IDs that match
  1313. # model_settings.config IDs around <components><component
  1314. # path="/3D/Objects/object_K.model" objectid="..." /></components>.
  1315. # Strip xmlns prefixes on attributes so ElementTree can find them
  1316. # without namespace gymnastics — `p:path` becomes `path` etc.
  1317. if "3D/3dmodel.model" in zf.namelist():
  1318. try:
  1319. raw = zf.read("3D/3dmodel.model").decode()
  1320. stripped = re.sub(r'xmlns:?\w*="[^"]*"', "", raw)
  1321. stripped = re.sub(r"<(/?)\w+:", r"<\1", stripped)
  1322. stripped = re.sub(r" \w+:(\w+=)", r" \1", stripped)
  1323. model_root = ET.fromstring(stripped)
  1324. for obj_elem in model_root.findall(".//object"):
  1325. oid = obj_elem.get("id")
  1326. if not oid:
  1327. continue
  1328. comps = obj_elem.find("components")
  1329. if comps is None:
  1330. continue
  1331. paths = []
  1332. for c in comps.findall("component"):
  1333. p = c.get("path")
  1334. if p:
  1335. paths.append(p.lstrip("/"))
  1336. if paths:
  1337. object_model_paths[oid] = paths
  1338. except (ET.ParseError, OSError):
  1339. pass # No 3dmodel — paint scan just won't apply
  1340. # Pass 3: scan paint_color attrs in each per-object .model file. Cache
  1341. # by file path because two objects often share the same component tree.
  1342. paint_cache: dict[str, set[int]] = {}
  1343. def _scan_paint(path: str) -> set[int]:
  1344. if path in paint_cache:
  1345. return paint_cache[path]
  1346. out: set[int] = set()
  1347. if path not in zf.namelist():
  1348. paint_cache[path] = out
  1349. return out
  1350. try:
  1351. data = zf.read(path)
  1352. except OSError:
  1353. paint_cache[path] = out
  1354. return out
  1355. # Per-extruder triangle coverage. Each painted triangle may have
  1356. # multiple leaf nibbles (the quadtree subdivides the face into
  1357. # painted regions); we count one triangle per unique extruder per
  1358. # match so the resulting fraction is "what share of painted
  1359. # triangles include at least one leaf with extruder N". Noise from
  1360. # one-off edit artifacts is filtered out at the threshold below.
  1361. extruder_triangles: dict[int, int] = {}
  1362. total_painted = 0
  1363. for match in _PAINT_COLOR_ATTR_RE.finditer(data):
  1364. total_painted += 1
  1365. seen: set[int] = set()
  1366. for ch in match.group(1):
  1367. # Hex digit → 4-bit value. 0 = unpainted leaf, F = branch
  1368. # (decoded recursively but children are encoded inline, so
  1369. # we'll see them on later iterations). 1-E = leaf painted
  1370. # with extruder N.
  1371. if ch in b"123456789":
  1372. seen.add(ch - 0x30)
  1373. elif ch in b"ABCDEabcde":
  1374. seen.add((ch & 0x4F) - 0x37)
  1375. for e in seen:
  1376. extruder_triangles[e] = extruder_triangles.get(e, 0) + 1
  1377. if total_painted > 0:
  1378. cutoff = max(1, int(total_painted * _PAINT_NOISE_THRESHOLD))
  1379. for ext, count in extruder_triangles.items():
  1380. if count >= cutoff:
  1381. out.add(ext)
  1382. paint_cache[path] = out
  1383. return out
  1384. # Walk plates — collect extruders for objects on the requested plate.
  1385. used: set[int] = set()
  1386. for plate_elem in root.findall(".//plate"):
  1387. plater_id = None
  1388. for meta in plate_elem.findall("metadata"):
  1389. if meta.get("key") == "plater_id":
  1390. try:
  1391. plater_id = int(meta.get("value", ""))
  1392. except (ValueError, TypeError):
  1393. pass
  1394. break
  1395. if plater_id != plate_id:
  1396. continue
  1397. for inst in plate_elem.findall("model_instance"):
  1398. for inst_meta in inst.findall("metadata"):
  1399. if inst_meta.get("key") != "object_id":
  1400. continue
  1401. obj_id = inst_meta.get("value")
  1402. if not obj_id:
  1403. continue
  1404. used.update(object_extruders.get(obj_id, set()))
  1405. for path in object_model_paths.get(obj_id, []):
  1406. used.update(_scan_paint(path))
  1407. break
  1408. return used