threemf_tools.py 85 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983
  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 (relative E; retractions
  44. are subtracted, so each layer holds the net length fed)
  45. """
  46. layer_filaments: dict[int, dict[int, float]] = {}
  47. current_layer = 0
  48. active_filament: int | None = None
  49. cumulative_extrusion: dict[int, float] = {} # filament_id -> total mm
  50. for line in gcode_content.splitlines():
  51. line = line.strip()
  52. if not line:
  53. continue
  54. # Handle comments - skip but check for layer markers
  55. if line.startswith(";"):
  56. # Some slicers use comment-based layer markers
  57. # e.g., "; CHANGE_LAYER" or ";LAYER_CHANGE"
  58. continue
  59. # Split line into command and inline comment
  60. if ";" in line:
  61. line = line.split(";")[0].strip()
  62. # Extract command and parameters
  63. parts = line.split()
  64. if not parts:
  65. continue
  66. cmd = parts[0].upper()
  67. # Layer change: M73 L<layer>
  68. # Bambu printers use M73 with L parameter for layer indication
  69. if cmd == "M73":
  70. for part in parts[1:]:
  71. part_upper = part.upper()
  72. if part_upper.startswith("L"):
  73. try:
  74. new_layer = int(part[1:])
  75. # Save current state before layer change
  76. if cumulative_extrusion:
  77. layer_filaments[current_layer] = _snapshot(cumulative_extrusion)
  78. current_layer = new_layer
  79. except ValueError:
  80. pass # Skip G-code lines with unparseable layer numbers
  81. # Filament change: M620 S<filament>
  82. # Bambu uses M620 for AMS filament switching
  83. # S255 means full unload (no active filament)
  84. elif cmd == "M620":
  85. for part in parts[1:]:
  86. part_upper = part.upper()
  87. if part_upper.startswith("S"):
  88. filament_str = part[1:]
  89. if filament_str == "255":
  90. # Full unload - no active filament
  91. active_filament = None
  92. else:
  93. try:
  94. # Extract digits (e.g., "0A" -> 0, "1" -> 1)
  95. match = re.match(r"(\d+)", filament_str)
  96. if match:
  97. active_filament = int(match.group(1))
  98. except (ValueError, AttributeError):
  99. pass # Skip unparseable filament switch commands
  100. # Extrusion moves: G0/G1/G2/G3 with E parameter
  101. # Only G1 typically has extrusion, but check all for safety
  102. elif cmd in ("G0", "G1", "G2", "G3"):
  103. if active_filament is None:
  104. continue
  105. for part in parts[1:]:
  106. part_upper = part.upper()
  107. if part_upper.startswith("E"):
  108. try:
  109. extrusion = float(part[1:])
  110. # Net sum, retractions included (#3317). Bambu G-code is
  111. # relative (M83): every retract is followed by an
  112. # un-retract of the same length, so counting only the
  113. # positive half added each pair to the total and put a
  114. # print 1.1-1.7x above the slicer's weight.
  115. current = cumulative_extrusion.get(active_filament, 0)
  116. cumulative_extrusion[active_filament] = current + extrusion
  117. except ValueError:
  118. pass # Skip G-code lines with unparseable extrusion values
  119. # Save final layer state
  120. if cumulative_extrusion:
  121. layer_filaments[current_layer] = _snapshot(cumulative_extrusion)
  122. return layer_filaments
  123. def _snapshot(cumulative_extrusion: dict[int, float]) -> dict[int, float]:
  124. """Copy the running totals for one layer, never below zero.
  125. A filament retracted before it has extruded anything would otherwise read
  126. as negative usage at that layer.
  127. """
  128. return {filament: max(mm, 0.0) for filament, mm in cumulative_extrusion.items()}
  129. def mm_to_grams(
  130. length_mm: float,
  131. diameter_mm: float = DEFAULT_FILAMENT_DIAMETER,
  132. density_g_cm3: float = DEFAULT_FILAMENT_DENSITY,
  133. ) -> float:
  134. """Convert filament length in mm to weight in grams.
  135. Uses the formula: mass = volume × density
  136. where volume = π × r² × length
  137. Args:
  138. length_mm: Length of filament in millimeters
  139. diameter_mm: Filament diameter in millimeters (default: 1.75)
  140. density_g_cm3: Material density in g/cm³ (default: 1.24 for PLA)
  141. Returns:
  142. Weight in grams
  143. """
  144. radius_cm = (diameter_mm / 2) / 10 # Convert mm to cm
  145. length_cm = length_mm / 10 # Convert mm to cm
  146. volume_cm3 = math.pi * radius_cm * radius_cm * length_cm
  147. return volume_cm3 * density_g_cm3
  148. def extract_layer_filament_usage_from_3mf(
  149. file_path: Path, plate_id: int | None = None
  150. ) -> dict[int, dict[int, float]] | None:
  151. """Extract per-layer filament usage from a 3MF file's embedded G-code.
  152. Args:
  153. file_path: Path to the 3MF file
  154. plate_id: Plate to read. Required for multi-plate files — zip member
  155. order is whatever the slicer wrote, and Bambu Studio stores
  156. ``plate_2.gcode`` ahead of ``plate_1.gcode``, so the old
  157. "first member" behaviour read a different plate's layers than
  158. the one that printed. Returns None rather than silently falling
  159. back to another plate when the requested plate isn't in the
  160. file; callers degrade to linear scaling, which is bounded.
  161. Returns:
  162. Dictionary mapping layers to filament usage, or None if parsing fails.
  163. Format: {layer: {filament_id: cumulative_mm}, ...}
  164. """
  165. try:
  166. with zipfile.ZipFile(file_path, "r") as zf:
  167. names = zf.namelist()
  168. gcode_path = select_plate_gcode_name(names, plate_id)
  169. if gcode_path is None:
  170. # No plate asked for, or a file whose single G-code member
  171. # doesn't follow the plate_N naming convention (non-Bambu
  172. # slicers) — the lone member is unambiguous either way.
  173. gcode_files = [f for f in names if f.endswith(".gcode")]
  174. if plate_id is None or len(gcode_files) == 1:
  175. gcode_path = default_plate_gcode_name(names)
  176. if gcode_path is None:
  177. return None
  178. gcode_content = zf.read(gcode_path).decode("utf-8", errors="ignore")
  179. return parse_gcode_layer_filament_usage(gcode_content)
  180. except Exception:
  181. return None
  182. def get_cumulative_usage_at_layer(
  183. layer_usage: dict[int, dict[int, float]],
  184. target_layer: int,
  185. ) -> dict[int, float]:
  186. """Get cumulative filament usage (in mm) up to and including target_layer.
  187. Args:
  188. layer_usage: The output from parse_gcode_layer_filament_usage()
  189. target_layer: The layer number to get usage for
  190. Returns:
  191. Dictionary of {filament_id: cumulative_mm} for each filament used
  192. up to target_layer. Returns empty dict if no data available.
  193. """
  194. if not layer_usage:
  195. return {}
  196. # Find the highest recorded layer <= target_layer
  197. # (we store snapshots at layer changes, so we need the closest one)
  198. relevant_layers = [layer for layer in layer_usage if layer <= target_layer]
  199. if not relevant_layers:
  200. return {}
  201. max_layer = max(relevant_layers)
  202. return layer_usage.get(max_layer, {})
  203. def extract_filament_properties_from_3mf(file_path: Path) -> dict[int, dict]:
  204. """Extract filament properties (density, diameter, type) from 3MF metadata.
  205. Args:
  206. file_path: Path to the 3MF file
  207. Returns:
  208. Dictionary mapping filament IDs to their properties:
  209. {filament_id: {"diameter": 1.75, "density": 1.24, "type": "PLA"}, ...}
  210. Note: filament_id is 1-based (matches slot_id in slice_info.config)
  211. """
  212. properties: dict[int, dict] = {}
  213. try:
  214. with zipfile.ZipFile(file_path, "r") as zf:
  215. # Try slice_info.config first for filament types
  216. if "Metadata/slice_info.config" in zf.namelist():
  217. content = zf.read("Metadata/slice_info.config").decode()
  218. root = ET.fromstring(content)
  219. for f in root.findall(".//filament"):
  220. try:
  221. # id is 1-based in slice_info.config
  222. fid = int(f.get("id", 0))
  223. properties[fid] = {
  224. "type": f.get("type", "PLA"),
  225. "diameter": DEFAULT_FILAMENT_DIAMETER,
  226. "density": DEFAULT_FILAMENT_DENSITY,
  227. }
  228. except ValueError:
  229. pass # Skip filament entries with unparseable IDs
  230. # Try project_settings.config for density values
  231. if "Metadata/project_settings.config" in zf.namelist():
  232. content = zf.read("Metadata/project_settings.config").decode()
  233. try:
  234. data = json.loads(content)
  235. densities = data.get("filament_density", [])
  236. for i, density in enumerate(densities):
  237. # project_settings uses 0-based indexing, convert to 1-based
  238. fid = i + 1
  239. if fid not in properties:
  240. properties[fid] = {
  241. "type": "",
  242. "diameter": DEFAULT_FILAMENT_DIAMETER,
  243. }
  244. try:
  245. properties[fid]["density"] = float(density)
  246. except (ValueError, TypeError):
  247. properties[fid]["density"] = DEFAULT_FILAMENT_DENSITY
  248. except json.JSONDecodeError:
  249. pass # Skip malformed project_settings.config JSON
  250. except Exception:
  251. pass # Return whatever properties were collected before the error
  252. return properties
  253. def _first_settings_id(value: object) -> str | None:
  254. """A ``*_settings_id`` value is usually a string, occasionally a list (one
  255. entry per extruder). Return the first non-empty string, else None."""
  256. if isinstance(value, str):
  257. return value.strip() or None
  258. if isinstance(value, list):
  259. for item in value:
  260. if isinstance(item, str) and item.strip():
  261. return item.strip()
  262. return None
  263. def extract_embedded_presets_from_3mf(zf: zipfile.ZipFile) -> dict[str, str | None]:
  264. """Read the printer / process preset names a 3MF project was prepared with.
  265. BambuStudio / OrcaSlicer write the chosen preset names into
  266. ``Metadata/project_settings.config`` (``printer_settings_id`` and
  267. ``print_settings_id``). The SliceModal uses them to default its printer
  268. and process dropdowns to what the file was sliced for (#1325) instead of
  269. blindly taking the first listed preset.
  270. Returns ``{"printer": <name|None>, "process": <name|None>}``. Every failure
  271. mode (missing config, malformed JSON, unexpected shape) yields ``None``
  272. values so the modal falls back to its own defaults.
  273. """
  274. result: dict[str, str | None] = {"printer": None, "process": None}
  275. try:
  276. if "Metadata/project_settings.config" not in zf.namelist():
  277. return result
  278. data = json.loads(zf.read("Metadata/project_settings.config").decode())
  279. except (KeyError, ValueError, OSError):
  280. return result
  281. if not isinstance(data, dict):
  282. return result
  283. result["printer"] = _first_settings_id(data.get("printer_settings_id"))
  284. result["process"] = _first_settings_id(data.get("print_settings_id"))
  285. return result
  286. # Ceiling on the dense per-slot form below. Deliberately larger than the 32
  287. # entries a print command carries, so a legitimate file is never silently
  288. # truncated at the limit -- it is either usable or rejected outright.
  289. _MAX_DENSE_FILAMENT_SLOTS = 64
  290. def extract_slot_extruders_from_3mf(file_path: Path, plate_id: int | None = None) -> list[int] | None:
  291. """Per-slot extruder assignment as a dense list, or None (#2800).
  292. Same data as :func:`extract_nozzle_mapping_from_3mf`, reshaped for the
  293. dispatcher: index 0 is filament slot 1, and a slot this file does not
  294. print is ``-1``. Nozzle-rack printers (H2C) need it to build the physical
  295. ``nozzle_mapping`` the firmware expects — without one they fall back to
  296. picking a nozzle themselves, which can level with one hotend and print
  297. with another, several millimetres off the bed.
  298. ``plate_id`` scopes the answer to the plate actually being dispatched. A
  299. multi-plate 3MF carries one filament list per plate and they need not
  300. agree, so without it a slot can take its extruder from a plate this print
  301. is not going to run.
  302. Takes a path rather than an open archive because the dispatcher is
  303. handling the file, not the zip, and a broken file there must not take the
  304. print down: an unreadable or non-3MF path returns None, and the caller
  305. dispatches exactly as it did before this existed.
  306. """
  307. try:
  308. with zipfile.ZipFile(file_path) as zf:
  309. by_slot = extract_nozzle_mapping_from_3mf(zf, plate_id=plate_id)
  310. except (zipfile.BadZipFile, OSError) as exc:
  311. logger.warning("Failed to read nozzle mapping from %s: %s", file_path, exc)
  312. return None
  313. if not by_slot:
  314. return None
  315. # The slot IDs are whatever the file says, so the dense form has to be
  316. # bounded before it is built: a corrupt or hostile 3MF declaring
  317. # `filament id="50000000"` would otherwise allocate a fifty-million-entry
  318. # list here, on the dispatch path. Nothing above 32 is usable anyway --
  319. # that is the length of the array the printer is sent.
  320. highest_slot = max(by_slot)
  321. if highest_slot < 1 or highest_slot > _MAX_DENSE_FILAMENT_SLOTS:
  322. logger.warning(
  323. "Ignoring nozzle mapping from %s: highest filament slot %s is out of range",
  324. file_path,
  325. highest_slot,
  326. )
  327. return None
  328. return [by_slot.get(slot, -1) for slot in range(1, highest_slot + 1)]
  329. @dataclass(frozen=True)
  330. class RackGroup:
  331. """One filament group on a nozzle-rack plate, and what hotend it needs.
  332. A group is the slicer's *logical* nozzle. On an H2C the rack carriage hosts
  333. six of them, so several groups share one extruder index -- which is exactly
  334. the case ``extract_nozzle_mapping_from_3mf`` refuses to answer, because the
  335. physical rack position per group is the operator's choice and is stated
  336. nowhere in the file.
  337. """
  338. group_id: int
  339. on_rack: bool
  340. nozzle_diameter: str
  341. volume_type: str
  342. # Only a hint, for preferring a rack position already loaded with this
  343. # colour. Excluded from equality on purpose: two filaments may share a
  344. # group and differ in colour without the group being contradictory, and
  345. # the agreement check below must not reject that file.
  346. filament_color: str = field(default="", compare=False)
  347. @dataclass(frozen=True)
  348. class RackPlan:
  349. """Everything a rack dispatch needs from the 3MF, short of the choice itself.
  350. ``slot_groups`` is dense: index 0 is filament slot 1, and a slot the plate
  351. does not print is ``-1``, matching :func:`extract_slot_extruders_from_3mf`.
  352. ``groups`` is keyed by group id.
  353. """
  354. slot_groups: list[int]
  355. groups: dict[int, RackGroup]
  356. @property
  357. def rack_group_ids(self) -> list[int]:
  358. """Groups needing a rack position, lowest first, for stable assignment."""
  359. return sorted(gid for gid, group in self.groups.items() if group.on_rack)
  360. def group_dicts(self) -> dict[int, dict]:
  361. """The groups as plain dicts, the form the resolver and the API take.
  362. Keeps one definition of the shape rather than two that can drift: the
  363. dispatcher resolves against it and the print dialog renders from it.
  364. """
  365. return {
  366. gid: {
  367. "on_rack": group.on_rack,
  368. "nozzle_diameter": group.nozzle_diameter,
  369. "volume_type": group.volume_type,
  370. "filament_color": group.filament_color,
  371. }
  372. for gid, group in self.groups.items()
  373. }
  374. def extract_rack_plan_from_3mf(file_path: Path, plate_id: int | None = None) -> RackPlan | None:
  375. """What a nozzle-rack plate needs per group, or None (#1784).
  376. :func:`extract_nozzle_mapping_from_3mf` answers "which carriage" and
  377. withholds the whole mapping when a plate needs several hotends off one
  378. rack. This answers the question underneath it -- which groups exist, which
  379. of them are rack-bound, and what nozzle each one wants -- so the caller can
  380. pair it with a chosen rack position and build a mapping the other function
  381. cannot.
  382. Measured basis (maintainer's H2C, 2026-08-14): the same plate was sent
  383. twice with different rack picks and every member of the two 3MFs was
  384. identical bar float noise -- ``group_id`` values, the toolchange stream and
  385. the ``NOZZLE_CHANGE`` markers included. The pick lives only in the
  386. dispatched ``nozzle_mapping``, so nothing here can or should derive it.
  387. Returns None whenever the plate cannot be described completely: a partial
  388. plan would place some slots and leave others at "not printed", which is the
  389. contradiction the firmware rejects as HMS 0500-4047.
  390. Takes a path rather than an open archive for the same reason
  391. :func:`extract_slot_extruders_from_3mf` does -- the dispatcher is holding
  392. the file, and a broken one must not take the print down.
  393. """
  394. try:
  395. with zipfile.ZipFile(file_path) as zf:
  396. return _rack_plan(zf, plate_id=plate_id)
  397. except (zipfile.BadZipFile, OSError) as exc:
  398. logger.warning("Failed to read rack plan from %s: %s", file_path, exc)
  399. return None
  400. except Exception:
  401. logger.exception("Unreadable rack plan in %s", file_path)
  402. return None
  403. def _rack_plan(zf: zipfile.ZipFile, plate_id: int | None) -> RackPlan | None:
  404. """Body of :func:`extract_rack_plan_from_3mf`, on an already-open archive."""
  405. names = zf.namelist()
  406. if "Metadata/project_settings.config" not in names:
  407. return None
  408. if "Metadata/slice_info.config" not in names:
  409. return None
  410. data = json.loads(zf.read("Metadata/project_settings.config").decode())
  411. physical_extruder_map = data.get("physical_extruder_map")
  412. if not physical_extruder_map or len(physical_extruder_map) <= 1:
  413. return None
  414. # Which extruder index is the rack, taken from the file rather than a
  415. # constant: the rack is the carriage that can address more than one nozzle.
  416. # `extruder_max_nozzle_count` is ['1', '6'] on an H2C, and reading it here
  417. # means a future rack of a different size needs no change.
  418. rack_indices: set[int] = set()
  419. for index, count in enumerate(data.get("extruder_max_nozzle_count") or []):
  420. try:
  421. if int(count) > 1:
  422. rack_indices.add(index)
  423. except (TypeError, ValueError):
  424. return None
  425. if not rack_indices:
  426. return None
  427. si_root = ET.fromstring(zf.read("Metadata/slice_info.config").decode())
  428. plates = _plates_in_scope(si_root, plate_id)
  429. group_extruders = _group_extruder_indices(plates)
  430. if not group_extruders:
  431. return None
  432. filament_elems = [elem for plate in plates for elem in plate.findall(".//filament")]
  433. if not filament_elems:
  434. return None
  435. slot_groups: dict[int, int] = {}
  436. groups: dict[int, RackGroup] = {}
  437. for elem in filament_elems:
  438. group_id_str = elem.get("group_id")
  439. slot_id_str = elem.get("id")
  440. if group_id_str is None or not slot_id_str:
  441. # One ungrouped filament makes the plan partial, and a partial plan
  442. # dispatches the ungrouped slot as unprinted.
  443. return None
  444. try:
  445. group_id = int(group_id_str)
  446. slot_id = int(slot_id_str)
  447. except (TypeError, ValueError):
  448. return None
  449. extruder_index = group_extruders.get(group_id)
  450. if extruder_index is None or not 0 <= extruder_index < len(physical_extruder_map):
  451. return None
  452. # Two plates in scope may name the same slot; they must agree, or the
  453. # dispatched plate is ambiguous.
  454. if slot_groups.setdefault(slot_id, group_id) != group_id:
  455. return None
  456. group = RackGroup(
  457. group_id=group_id,
  458. on_rack=extruder_index in rack_indices,
  459. nozzle_diameter=(elem.get("nozzle_diameter") or "").strip(),
  460. volume_type=(elem.get("volume_type") or "").strip(),
  461. filament_color=(elem.get("color") or "").strip(),
  462. )
  463. # Filaments sharing a group must want the same hotend, or "the group is
  464. # one nozzle" is not true and no single position can serve them.
  465. if groups.setdefault(group_id, group) != group:
  466. return None
  467. highest_slot = max(slot_groups)
  468. if highest_slot < 1 or highest_slot > _MAX_DENSE_FILAMENT_SLOTS:
  469. return None
  470. return RackPlan(
  471. slot_groups=[slot_groups.get(slot, -1) for slot in range(1, highest_slot + 1)],
  472. groups=groups,
  473. )
  474. def _plates_in_scope(si_root: XmlElement, plate_id: int | None) -> list[XmlElement]:
  475. """The ``<plate>`` elements a lookup should read, narrowed to one if asked.
  476. A 3MF holds every plate in the project, each with its own filament list, and
  477. two plates may assign the same slot to different extruders. Falls back to
  478. every plate when no id is given or none matches, which is what this module
  479. did before plates were distinguished at all.
  480. """
  481. plates = si_root.findall(".//plate")
  482. if not plates:
  483. return [si_root]
  484. if plate_id is None:
  485. return plates
  486. for plate in plates:
  487. for metadata in plate.findall("metadata"):
  488. if metadata.get("key") != "index":
  489. continue
  490. try:
  491. if int(metadata.get("value") or "") == plate_id:
  492. return [plate]
  493. except (TypeError, ValueError):
  494. pass
  495. return plates
  496. def _group_extruder_indices(plates: list[XmlElement]) -> dict[int, int] | None:
  497. """Map each filament group to the slicer extruder index it prints on.
  498. ``slice_info.config`` states this directly, as ``<nozzle id="<group>"
  499. extruder_id="<1-based extruder>"/>``. Reading it matters on nozzle-rack
  500. printers, where the group id is *not* an extruder index: the H2C's rack
  501. carriage can host six hotends (``extruder_max_nozzle_count`` is ``['1',
  502. '6']``), so the slicer emits more groups than the machine has extruders and
  503. several groups share one carriage. A plate of the reporter's carried groups
  504. 0, 1 and 2 against a two-entry ``physical_extruder_map``.
  505. Returns None when the file states no table, or when two plates in scope
  506. disagree about a group — in which case the caller keeps treating the group
  507. id as the extruder index, which is what every H2D file in practice wants
  508. and what this module has always done.
  509. """
  510. table: dict[int, int] = {}
  511. for plate in plates:
  512. for nozzle in plate.findall(".//nozzle"):
  513. try:
  514. group_id = int(nozzle.get("id") or "")
  515. extruder_index = int(nozzle.get("extruder_id") or "") - 1
  516. except (TypeError, ValueError):
  517. return None
  518. if extruder_index < 0:
  519. return None
  520. if table.setdefault(group_id, extruder_index) != extruder_index:
  521. return None
  522. return table or None
  523. def extract_nozzle_mapping_from_3mf(zf: zipfile.ZipFile, plate_id: int | None = None) -> dict[int, int] | None:
  524. """Extract per-slot nozzle/extruder mapping from a 3MF file.
  525. On dual-nozzle printers (H2D, H2D Pro), each filament slot is assigned to a
  526. specific nozzle. The slicer may override user preferences when using "Auto For
  527. Flush" mode, so the actual assignment comes from slice_info.config group_id
  528. attributes, not from the user's filament_nozzle_map preference.
  529. Priority:
  530. 1. group_id on <filament> elements in slice_info.config (actual assignment),
  531. resolved through the file's own group-to-extruder table
  532. 2. filament_nozzle_map in project_settings.config (user preference fallback)
  533. Both are mapped through physical_extruder_map to get MQTT extruder IDs (0=right, 1=left).
  534. Returns None rather than a partial answer whenever a filament the plate
  535. prints cannot be placed. The gap does not stay a gap downstream: the dense
  536. form fills it with -1, which already means "slot not printed", and
  537. dispatching that against an ams_mapping that *does* name a tray for the slot
  538. is a contradiction the firmware rejects outright with HMS 0500-4047, "the
  539. available hotend quantity or model does not match the sliced file". Giving
  540. no mapping at all costs only the firmware's own nozzle pick.
  541. Args:
  542. zf: An open ZipFile of the 3MF archive
  543. plate_id: 1-based plate to read, or None for every plate in the file
  544. Returns:
  545. Dictionary mapping {slot_id: extruder_id} for dual-nozzle files,
  546. or None if single-nozzle, missing data, unplaceable, or parse error.
  547. """
  548. try:
  549. if "Metadata/project_settings.config" not in zf.namelist():
  550. return None
  551. content = zf.read("Metadata/project_settings.config").decode()
  552. data = json.loads(content)
  553. physical_extruder_map = data.get("physical_extruder_map")
  554. if not physical_extruder_map or len(physical_extruder_map) <= 1:
  555. return None # Single-nozzle printer
  556. # Check if only one extruder is active.
  557. # If so, we can skip the mapping and just assign all slots to that extruder.
  558. # extruder_nozzle_stats format: ["Standard#0|High Flow#0", "Standard#1"]
  559. # Each entry = one extruder. Format: <NozzleVolumeType>#<count>[|...]
  560. # #N is the count of physical nozzles of that type (0 = none installed).
  561. # Types: Standard, High Flow, Hybrid, TPU High Flow
  562. active_extruders = []
  563. for stats_str in data.get("extruder_nozzle_stats") or []:
  564. nozzle_counts = [n.partition("#")[2] for n in stats_str.split("|")]
  565. active_extruders.append(1 if any(c not in ("0", "") for c in nozzle_counts) else 0)
  566. # Parse slice_info once: needed by both the single-active shortcut
  567. # (to verify the slice is actually single-group, #1825) and Priority 1.
  568. si_root: XmlElement | None = None
  569. filament_elems: list[XmlElement] = []
  570. group_extruders: dict[int, int] | None = None
  571. distinct_group_ids: set[int] = set()
  572. if "Metadata/slice_info.config" in zf.namelist():
  573. si_content = zf.read("Metadata/slice_info.config").decode()
  574. si_root = ET.fromstring(si_content)
  575. plates = _plates_in_scope(si_root, plate_id)
  576. group_extruders = _group_extruder_indices(plates)
  577. filament_elems = [elem for plate in plates for elem in plate.findall(".//filament")]
  578. for filament_elem in filament_elems:
  579. gid = filament_elem.get("group_id")
  580. if gid is not None:
  581. try:
  582. distinct_group_ids.add(int(gid))
  583. except (ValueError, TypeError):
  584. pass
  585. # Two groups on one extruder means that extruder is a nozzle rack,
  586. # and the plate wants a *different* hotend from it per group. Which
  587. # physical rack slot each group takes is the slicer's own choice
  588. # against the rack's live contents and is stated nowhere in the
  589. # file -- on the plate that prompted this, both rack groups carry
  590. # identical nozzle_diameter and volume_type, and BambuStudio still
  591. # dispatched them to positions 16 and 18 (captured 2026-08-13
  592. # 17:20; that print completed). Nothing here can reproduce that
  593. # choice, and answering anyway is what printed in mid-air, so the
  594. # whole mapping is withheld and the firmware picks for itself.
  595. if group_extruders and len(set(group_extruders.values())) < len(group_extruders):
  596. logger.warning(
  597. "Ignoring nozzle mapping: groups %s share extruders %s, so the plate "
  598. "needs more than one nozzle from a rack and the physical positions "
  599. "are not derivable from the file",
  600. sorted(group_extruders),
  601. sorted(set(group_extruders.values())),
  602. )
  603. return None
  604. # Single-active shortcut: only safe when the slice actually uses one
  605. # group. extruder_nozzle_stats can under-report a second installed
  606. # nozzle when its volume-type differs from the profile's enumerated
  607. # types (HT-AMS / High-Flow asymmetry on H2D, #1825); without this
  608. # guard the shortcut collapses a real multi-extruder slice onto one
  609. # nozzle and the group_id mapping below is skipped.
  610. if sum(active_extruders) == 1 and len(distinct_group_ids) <= 1:
  611. nozzle_mapping: dict[int, int] = {}
  612. active_idx = active_extruders.index(1)
  613. target_extruder = int(physical_extruder_map[active_idx])
  614. for filament_elem in filament_elems:
  615. try:
  616. nozzle_mapping[int(filament_elem.get("id"))] = target_extruder
  617. except (ValueError, TypeError):
  618. pass
  619. return nozzle_mapping or None
  620. # Priority 1: Use group_id from slice_info filament elements.
  621. # This reflects the actual slicer assignment (respects "Auto For Flush").
  622. nozzle_mapping: dict[int, int] = {}
  623. ungrouped = 0
  624. for filament_elem in filament_elems:
  625. group_id_str = filament_elem.get("group_id")
  626. filament_id_str = filament_elem.get("id")
  627. if not filament_id_str:
  628. continue
  629. if group_id_str is None:
  630. # Counted rather than returned on: a file where *no* filament
  631. # carries a group falls through to Priority 2 as it always has.
  632. # Only a file that groups some and not others is unplaceable.
  633. ungrouped += 1
  634. continue
  635. try:
  636. group_id = int(group_id_str)
  637. slot_id = int(filament_id_str)
  638. except (ValueError, TypeError):
  639. logger.warning(
  640. "Ignoring nozzle mapping: unreadable filament id=%r group_id=%r",
  641. filament_id_str,
  642. group_id_str,
  643. )
  644. return None
  645. # The group id is an extruder index only where the file states no
  646. # table of its own — true of every H2D slice, not of an H2C one.
  647. extruder_index = group_id if group_extruders is None else group_extruders.get(group_id)
  648. if extruder_index is None or not 0 <= extruder_index < len(physical_extruder_map):
  649. logger.warning(
  650. "Ignoring nozzle mapping: filament slot %s is in group %s, which "
  651. "resolves to extruder %r outside physical_extruder_map %r",
  652. slot_id,
  653. group_id,
  654. extruder_index,
  655. physical_extruder_map,
  656. )
  657. return None
  658. nozzle_mapping[slot_id] = int(physical_extruder_map[extruder_index])
  659. if nozzle_mapping and ungrouped:
  660. logger.warning(
  661. "Ignoring nozzle mapping: %d filament(s) carry no group_id while %d do, "
  662. "so the ungrouped slots would dispatch as unprinted",
  663. ungrouped,
  664. len(nozzle_mapping),
  665. )
  666. return None
  667. if nozzle_mapping:
  668. return nozzle_mapping
  669. # Priority 2: Fall back to filament_nozzle_map (user preference).
  670. # This is correct when the user manually assigned nozzles, but may be
  671. # wrong when the slicer overrides via "Auto For Flush".
  672. filament_nozzle_map = data.get("filament_nozzle_map")
  673. if not filament_nozzle_map:
  674. return None
  675. for i, slicer_ext_str in enumerate(filament_nozzle_map):
  676. slot_id = i + 1
  677. try:
  678. slicer_ext = int(slicer_ext_str)
  679. if slicer_ext < len(physical_extruder_map):
  680. nozzle_mapping[slot_id] = int(physical_extruder_map[slicer_ext])
  681. except (ValueError, TypeError, IndexError):
  682. pass
  683. return nozzle_mapping if nozzle_mapping else None
  684. except Exception:
  685. return None
  686. @dataclass(frozen=True)
  687. class PlateMetadata:
  688. """Combined per-plate slice_info.config values from a single 3MF parse.
  689. Bundles the three fields the queue listing needs so a queue poll opens and
  690. parses each 3MF once instead of three times (#2573). ``filament_usage`` is
  691. the full per-filament list (other callers — usage tracking, Spoolman — need
  692. it); ``filament_used_grams`` is its ``used_g`` sum, precomputed here so the
  693. queue path doesn't re-sum on every hit.
  694. """
  695. print_time_seconds: int | None = None
  696. filament_usage: list[dict] = field(default_factory=list)
  697. bed_type: str | None = None
  698. filament_used_grams: float = 0.0
  699. _EMPTY_PLATE_METADATA = PlateMetadata()
  700. # Revision-keyed cache for parsed per-plate metadata. Queue polling re-lists the
  701. # same unchanged 3MFs every few seconds per connected client (#2573); without a
  702. # cache each row costs a ZIP open + XML parse. The key includes the file's
  703. # mtime_ns and size so a replaced or edited file transparently gets a fresh
  704. # entry — no manual invalidation needed. Bounded LRU + lock so it stays small
  705. # and is safe to touch from worker threads.
  706. _PLATE_METADATA_CACHE: "OrderedDict[tuple, PlateMetadata]" = OrderedDict()
  707. _PLATE_METADATA_CACHE_LOCK = Lock()
  708. _PLATE_METADATA_CACHE_MAX = 512
  709. def clear_plate_metadata_cache() -> None:
  710. """Drop all cached per-plate metadata (used by tests)."""
  711. with _PLATE_METADATA_CACHE_LOCK:
  712. _PLATE_METADATA_CACHE.clear()
  713. def _parse_plate_metadata_uncached(file_path: Path, plate_id: int | None) -> PlateMetadata:
  714. """Open the 3MF once and pull print time, filament usage and bed type.
  715. Replicates the per-field ``plate_id=None`` behaviour of the three legacy
  716. helpers exactly: usage collects every ``<filament>`` in the file, while
  717. print time and bed type come from the first ``<plate>``.
  718. """
  719. try:
  720. with zipfile.ZipFile(file_path, "r") as zf:
  721. if "Metadata/slice_info.config" not in zf.namelist():
  722. return _EMPTY_PLATE_METADATA
  723. content = zf.read("Metadata/slice_info.config").decode()
  724. root = ET.fromstring(content)
  725. except Exception as e:
  726. logger.warning("Failed to read plate metadata from %s: %s", file_path, e)
  727. return _EMPTY_PLATE_METADATA
  728. def _plate_index(plate_elem) -> int | None:
  729. for meta in plate_elem.findall("metadata"):
  730. if meta.get("key") == "index":
  731. try:
  732. return int(meta.get("value", "0"))
  733. except ValueError:
  734. return None
  735. return None
  736. def _collect_filaments(plate_elem) -> list[dict]:
  737. out: list[dict] = []
  738. for f in plate_elem.findall("filament"):
  739. filament_id = f.get("id")
  740. # Both the used_g float() and the id int() must stay inside the guard:
  741. # a non-numeric id or used_g is silently skipped (matches the legacy
  742. # helpers, which tolerated garbage rows rather than raising — a raise
  743. # here would 500 the whole queue listing).
  744. try:
  745. used_amount = float(f.get("used_g", "0"))
  746. if filament_id:
  747. out.append(
  748. {
  749. "slot_id": int(filament_id),
  750. "used_g": used_amount,
  751. "type": f.get("type", ""),
  752. "color": f.get("color", ""),
  753. }
  754. )
  755. except (ValueError, TypeError):
  756. continue
  757. return out
  758. print_time: int | None = None
  759. bed_type: str | None = None
  760. filament_usage: list[dict] = []
  761. matched_plate = None
  762. if plate_id is not None:
  763. for plate_elem in root.findall(".//plate"):
  764. if _plate_index(plate_elem) == plate_id:
  765. matched_plate = plate_elem
  766. break
  767. else:
  768. matched_plate = root.find(".//plate")
  769. if matched_plate is not None:
  770. for meta in matched_plate.findall("metadata"):
  771. key = meta.get("key")
  772. if key == "prediction" and print_time is None:
  773. try:
  774. print_time = int(meta.get("value", "0"))
  775. except ValueError:
  776. print_time = None
  777. elif key == "curr_bed_type" and meta.get("value"):
  778. bed_type = (meta.get("value") or "").strip()
  779. if plate_id is not None:
  780. if matched_plate is not None:
  781. filament_usage = _collect_filaments(matched_plate)
  782. else:
  783. # Legacy plate_id=None usage: every filament in the file, not just plate 1.
  784. for f in root.findall(".//filament"):
  785. filament_id = f.get("id")
  786. # int()/float() both guarded — a garbage id/used_g row is skipped, not raised.
  787. try:
  788. used_amount = float(f.get("used_g", "0"))
  789. if filament_id:
  790. filament_usage.append(
  791. {
  792. "slot_id": int(filament_id),
  793. "used_g": used_amount,
  794. "type": f.get("type", ""),
  795. "color": f.get("color", ""),
  796. }
  797. )
  798. except (ValueError, TypeError):
  799. continue
  800. return PlateMetadata(
  801. print_time_seconds=print_time,
  802. filament_usage=filament_usage,
  803. bed_type=bed_type,
  804. filament_used_grams=sum(f["used_g"] for f in filament_usage),
  805. )
  806. def extract_plate_metadata_from_3mf(file_path: Path, plate_id: int | None = None) -> PlateMetadata:
  807. """Return combined per-plate metadata, cached by file revision (#2573).
  808. The result is keyed by ``(path, plate_id, mtime_ns, size)`` so an unchanged
  809. file is parsed at most once; a replaced/edited file re-parses automatically.
  810. The returned ``PlateMetadata`` is shared and MUST be treated as read-only —
  811. callers that need a mutable filament list get a copy from the wrappers below.
  812. """
  813. file_path = Path(file_path)
  814. try:
  815. stat = file_path.stat()
  816. except OSError:
  817. # File missing/unreadable: parse (which will return empty) but don't
  818. # cache — the file may appear later and we don't want a sticky miss.
  819. return _parse_plate_metadata_uncached(file_path, plate_id)
  820. key = (str(file_path), plate_id, stat.st_mtime_ns, stat.st_size)
  821. with _PLATE_METADATA_CACHE_LOCK:
  822. cached = _PLATE_METADATA_CACHE.get(key)
  823. if cached is not None:
  824. _PLATE_METADATA_CACHE.move_to_end(key)
  825. return cached
  826. metadata = _parse_plate_metadata_uncached(file_path, plate_id)
  827. with _PLATE_METADATA_CACHE_LOCK:
  828. _PLATE_METADATA_CACHE[key] = metadata
  829. _PLATE_METADATA_CACHE.move_to_end(key)
  830. while len(_PLATE_METADATA_CACHE) > _PLATE_METADATA_CACHE_MAX:
  831. _PLATE_METADATA_CACHE.popitem(last=False)
  832. return metadata
  833. def extract_filament_usage_from_3mf(file_path: Path, plate_id: int | None = None) -> list[dict]:
  834. """Extract per-filament total usage from 3MF slice_info.config.
  835. This extracts the slicer-estimated total usage per filament slot,
  836. not the per-layer breakdown.
  837. Args:
  838. file_path: Path to the 3MF file
  839. plate_id: Optional plate index to filter for (for multi-plate files)
  840. Returns:
  841. List of filament usage dictionaries:
  842. [{"slot_id": 1, "used_g": 50.5, "type": "PLA", "color": "#FF0000"}, ...]
  843. """
  844. # Delegate to the cached combined parse (#2573). Return fresh dicts so callers
  845. # that mutate the list don't corrupt the shared cached PlateMetadata.
  846. return [dict(f) for f in extract_plate_metadata_from_3mf(file_path, plate_id).filament_usage]
  847. def extract_print_time_from_3mf(file_path: Path, plate_id: int | None = None) -> int | None:
  848. """Extract the slicer's predicted print time from a 3MF's slice_info.config.
  849. Multi-plate 3MFs carry one ``<plate><metadata key="prediction" .../></plate>``
  850. per plate. The archive-level `print_time_seconds` is the sum across all plates
  851. (see services/archive.py:200-264, #1593). For per-plate UI / notifications,
  852. callers re-read the 3MF and request the specific plate's value via this helper.
  853. Args:
  854. file_path: Path to the 3MF file
  855. plate_id: Plate index to filter for; if None, returns the first plate's
  856. ``prediction`` (matches the legacy single-plate read).
  857. Returns:
  858. Predicted print time in seconds, or None if not found / unparseable.
  859. """
  860. return extract_plate_metadata_from_3mf(file_path, plate_id).print_time_seconds
  861. # Bed temperature is not one key in a BambuStudio project. Every plate type has
  862. # its own per-filament array, and the plate actually fitted is named separately
  863. # in ``curr_bed_type`` -- so reading a bed temperature means picking the array
  864. # the plate points at. Keys and mapping are BambuStudio's own
  865. # ``get_bed_temp_1st_layer_key`` / ``get_bed_temp_key`` (PrintConfig.hpp), and
  866. # the plate names are the ``curr_bed_type`` enum values (PrintConfig.cpp).
  867. # First-layer temperature first: that is what the printer heats to before the
  868. # print starts, which is what preheat is trying to reach.
  869. #
  870. # ``Default Plate`` is deliberately absent -- BambuStudio maps it to no key at
  871. # all, so there is nothing to read and guessing a plate would invent a bed
  872. # temperature the slice never specified.
  873. _BED_TEMP_KEYS: dict[str, tuple[str, str]] = {
  874. "Cool Plate": ("cool_plate_temp_initial_layer", "cool_plate_temp"),
  875. "Engineering Plate": ("eng_plate_temp_initial_layer", "eng_plate_temp"),
  876. "High Temp Plate": ("hot_plate_temp_initial_layer", "hot_plate_temp"),
  877. "Textured PEI Plate": ("textured_plate_temp_initial_layer", "textured_plate_temp"),
  878. "Supertack Plate": ("supertack_plate_temp_initial_layer", "supertack_plate_temp"),
  879. }
  880. # Fallback for a config that names no plate: the Orca/PrusaSlicer spelling,
  881. # which is a single value rather than a per-plate array.
  882. _GENERIC_BED_TEMP_KEYS = ("bed_temperature_initial_layer", "bed_temperature")
  883. def _plate_temperature(val, filament_indexes: list[int] | None = None) -> int | None:
  884. """Bed temperature from one plate-temperature entry, or None.
  885. The plate arrays carry one entry per filament in the project, and a 0 means
  886. that filament cannot print on this plate. The bed only has one temperature,
  887. so the print runs at the highest its filaments ask for -- taking entry 0 the
  888. way the neighbouring scalar settings do would store a 0 for any project
  889. whose first filament is not one this plate is heated for.
  890. ``filament_indexes`` (0-based) are the filaments the printed plate uses:
  891. only theirs count, so a PLA plate of a project that also holds PETG is not
  892. heated to the PETG temperature. Without them every filament counts.
  893. """
  894. values = val if isinstance(val, list) else [val]
  895. if filament_indexes and isinstance(val, list):
  896. picked = [values[i] for i in filament_indexes if 0 <= i < len(values)]
  897. values = picked or values
  898. temps = []
  899. for entry in values:
  900. if isinstance(entry, bool) or not isinstance(entry, (int, float, str)):
  901. continue
  902. try:
  903. temps.append(int(float(entry)))
  904. except (TypeError, ValueError):
  905. continue
  906. return max(temps) if temps else None
  907. def bed_temperature_from_config(data: dict, filament_indexes: list[int] | None = None) -> int | None:
  908. """Bed temperature for the plate *data* is sliced for, or None (#2989).
  909. *data* is a parsed ``Metadata/project_settings.config``. Lives here rather
  910. than beside the archive parser so the ingest path and the one-shot backfill
  911. that repairs archives written before the fix read it exactly the same way.
  912. ``filament_indexes``: the printed plate's filaments, see _plate_temperature.
  913. """
  914. bed_type = str(data.get("curr_bed_type") or "").strip()
  915. for key in (*_BED_TEMP_KEYS.get(bed_type, ()), *_GENERIC_BED_TEMP_KEYS):
  916. if key not in data:
  917. continue
  918. temperature = _plate_temperature(data[key], filament_indexes)
  919. # A plate array of all zeros means no filament in the project prints on
  920. # this plate, which is not a bed temperature -- keep looking rather than
  921. # recording a 0 that reads as "cold bed".
  922. if temperature:
  923. return temperature
  924. return None
  925. def extract_bed_temperature_from_3mf(file_path: Path) -> int | None:
  926. """Read a 3MF's bed temperature straight off disk, or None.
  927. For the backfill, which has a ``file_path`` and nothing else. Opens only
  928. ``Metadata/project_settings.config`` -- the archive parser reads thumbnails,
  929. the model and the slice info as well, and none of that is wanted here.
  930. Every failure is None. Deliberately broader than the handful of exceptions a
  931. malformed zip is expected to raise: the caller runs inside the startup
  932. migration, which has no handler above it, so anything unlisted escaping here
  933. does not skip one archive -- it stops Bambuddy from booting, and keeps
  934. stopping it, because the one-shot flag is written in the same transaction
  935. that just rolled back. A bed temperature is not worth that.
  936. """
  937. try:
  938. with zipfile.ZipFile(file_path, "r") as zf:
  939. if "Metadata/project_settings.config" not in zf.namelist():
  940. return None
  941. data = json.loads(zf.read("Metadata/project_settings.config").decode())
  942. return bed_temperature_from_config(data) if isinstance(data, dict) else None
  943. except Exception:
  944. return None
  945. # Header values exposed as `{placeholder}` substitutions inside snippets.
  946. # Aliases let users write Prusa-style names (`{max_layer_z}`) that map onto
  947. # Bambu/Orca header keys (`max_z_height`).
  948. _HEADER_PLACEHOLDER_ALIASES = {
  949. "max_layer_z": "max_z_height",
  950. "max_print_height": "max_z_height",
  951. "total_layers": "total_layer_number",
  952. }
  953. _HEADER_KEY_RE = re.compile(r"^;\s*([^:]+?)\s*:\s*(.+?)\s*$")
  954. _PLACEHOLDER_RE = re.compile(r"\{([a-zA-Z_][a-zA-Z0-9_]*)\}")
  955. _START_GCODE_END_MARKER = "; MACHINE_START_GCODE_END"
  956. _EXECUTABLE_BLOCK_END_MARKER = "; EXECUTABLE_BLOCK_END"
  957. def _parse_3mf_gcode_header(content: str) -> dict[str, str]:
  958. """Parse the `; HEADER_BLOCK_START..END` block into a normalised dict.
  959. Keys are lowercased, ` [units]` suffixes stripped, and spaces converted
  960. to underscores so callers can look up `total_layer_number` regardless of
  961. whether the source line is `; total layer number: 80` or
  962. `; total filament length [mm] : 12155.34`.
  963. """
  964. header: dict[str, str] = {}
  965. in_header = False
  966. for raw_line in content.splitlines():
  967. line = raw_line.strip()
  968. if line == "; HEADER_BLOCK_START":
  969. in_header = True
  970. continue
  971. if line == "; HEADER_BLOCK_END":
  972. break
  973. if not in_header:
  974. continue
  975. m = _HEADER_KEY_RE.match(line)
  976. if not m:
  977. continue
  978. key, value = m.group(1), m.group(2)
  979. key = re.sub(r"\s*\[[^\]]*\]\s*$", "", key)
  980. key = key.strip().lower().replace(" ", "_")
  981. header[key] = value
  982. return header
  983. def _plate_number_of(name: str) -> int | None:
  984. """Plate index encoded in a ``…/plate_<n>.gcode`` member, or None.
  985. Parsed as an int rather than string-matched so a zero-padded
  986. ``plate_01.gcode`` resolves to the same 1 the plates endpoint reports.
  987. """
  988. marker = "plate_"
  989. idx = name.rfind(marker)
  990. if idx < 0 or not name.endswith(".gcode"):
  991. return None
  992. try:
  993. return int(name[idx + len(marker) : -len(".gcode")])
  994. except ValueError:
  995. return None
  996. def used_filament_indexes(plates: list, plate_number: int | None) -> list[int]:
  997. """Positions, in the project's per-filament settings, of the filaments the
  998. printed plate uses, sorted: empty when that can't be told.
  999. *plates* are the ``<plate>`` elements of ``slice_info.config``, whose
  1000. filament ids are 1-based. ``project_settings`` lists one value per filament
  1001. of the whole project, so the printed plate's own filaments pick which apply.
  1002. Without a plate number, the only plate decides.
  1003. """
  1004. if plate_number:
  1005. printed = [
  1006. plate
  1007. for plate in plates
  1008. if any(
  1009. meta.get("key") == "index" and meta.get("value") == str(plate_number)
  1010. for meta in plate.findall("metadata")
  1011. )
  1012. ]
  1013. else:
  1014. printed = plates if len(plates) == 1 else []
  1015. used: list[int] = []
  1016. for plate in printed[:1]:
  1017. for filament in plate.findall("filament"):
  1018. try:
  1019. if float(filament.get("used_g", "0")) > 0:
  1020. used.append(int(filament.get("id", "")))
  1021. except (TypeError, ValueError):
  1022. continue
  1023. return sorted(fid - 1 for fid in set(used) if fid > 0)
  1024. def plate_bed_temperature(file_path: Path, plate_id: int | None) -> int | None:
  1025. """Bed temperature for the plate of *file_path* that prints, or None.
  1026. An archive stores one bed temperature, the highest any filament of the
  1027. project asks for, while a queued job may print any plate of it: a PLA plate
  1028. of a project that also holds PETG is heated for PLA. *plate_id* as a queue
  1029. job holds it; none (or 0) means the file's default plate, the one dispatched.
  1030. None when the file can't be read or names no bed temperature, so the caller
  1031. falls back to the stored value.
  1032. Every failure is None, as in extract_bed_temperature_from_3mf: preheat and
  1033. keep-warm run this for every job, and a damaged file raises well beyond the
  1034. expected few (zlib.error from corrupt deflate data, OverflowError from an
  1035. "inf" temperature). Escaping here would fail the dispatch every round, or
  1036. end keep-warm for every printer.
  1037. """
  1038. try:
  1039. with zipfile.ZipFile(file_path, "r") as zf:
  1040. names = zf.namelist()
  1041. if "Metadata/project_settings.config" not in names:
  1042. return None
  1043. data = json.loads(zf.read("Metadata/project_settings.config").decode())
  1044. slice_info = zf.read("Metadata/slice_info.config") if "Metadata/slice_info.config" in names else None
  1045. if not isinstance(data, dict):
  1046. return None
  1047. plates = ET.fromstring(slice_info).findall("plate") if slice_info else []
  1048. plate_number = plate_id if plate_id is not None and plate_id > 0 else default_plate_number(names)
  1049. return bed_temperature_from_config(data, used_filament_indexes(plates, plate_number))
  1050. except Exception:
  1051. return None
  1052. def select_plate_gcode_name(names: list[str], plate_id: int | None) -> str | None:
  1053. """The ``.gcode`` member for exactly ``plate_id``, or None if it isn't there.
  1054. Returns None for a ``plate_id`` the file doesn't hold — callers that want a
  1055. fallback compose this with ``default_plate_gcode_name``; callers serving a
  1056. user's explicit plate choice want the None so they can 404 instead of
  1057. quietly rendering a different plate.
  1058. """
  1059. if plate_id is None:
  1060. return None
  1061. for name in names:
  1062. if name.endswith(".gcode") and _plate_number_of(name) == plate_id:
  1063. return name
  1064. return None
  1065. def default_plate_gcode_name(names: list[str]) -> str | None:
  1066. """The ``.gcode`` member to show when no plate was asked for.
  1067. The lowest plate number, NOT the first member in the archive: zip order is
  1068. whatever the slicer happened to write, and Bambu Studio does not write
  1069. plates in order — a two-plate file measured here stores ``plate_2.gcode``
  1070. ahead of ``plate_1.gcode``, so taking the first member opened plate 2. Files
  1071. from slicers that don't use the plate naming convention keep the old
  1072. first-member behaviour, since there is no numbering to sort by.
  1073. """
  1074. gcodes = [n for n in names if n.endswith(".gcode")]
  1075. if not gcodes:
  1076. return None
  1077. numbered = [(num, n) for n in gcodes if (num := _plate_number_of(n)) is not None]
  1078. if numbered:
  1079. return min(numbered)[1]
  1080. return gcodes[0]
  1081. def names_carry_gcode(names: list[str]) -> bool:
  1082. """Is this 3MF a sliced file — does it carry printer-executable G-code?
  1083. One definition, because several of them is the bug (#2993). The archive
  1084. side judged a file by what it holds -- the card's GCODE badge reads the
  1085. layer count and print time parsed out of the plate G-code, and
  1086. ``/archives/{id}/capabilities`` scanned the zip -- while the library judged
  1087. it by its filename. So a sliced 3MF stored as ``Foo.3mf`` rather than
  1088. ``Foo.gcode.3mf`` carried the badge and still re-imported as a source-only
  1089. project. This is the answer for anything asking the zip directly.
  1090. Defers to ``default_plate_gcode_name`` rather than testing for
  1091. ``Metadata/plate_<n>.gcode``, so a slicer that lays its output out some
  1092. other way is judged by the same rule everywhere.
  1093. """
  1094. return default_plate_gcode_name(names) is not None
  1095. def carries_gcode(file_path: Path | str) -> bool:
  1096. """``names_carry_gcode`` for a file on disk. False for anything unreadable.
  1097. Only the zip's central directory is read — no member is decompressed — so
  1098. this is cheap enough to run on every ingested file.
  1099. """
  1100. try:
  1101. with zipfile.ZipFile(file_path, "r") as zf:
  1102. return names_carry_gcode(zf.namelist())
  1103. except (OSError, zipfile.BadZipFile):
  1104. # Not a zip, gone, or unreadable. Callers treat that as "no G-code
  1105. # visible", which is what they did before this check existed.
  1106. return False
  1107. def default_plate_number(names: list[str]) -> int | None:
  1108. """The plate index to dispatch when the caller didn't ask for one.
  1109. Composes :func:`default_plate_gcode_name` with the numeric index its
  1110. chosen member encodes, so a caller that needs the integer ``plate_id`` a
  1111. print command takes gets the same "lowest plate, not first zip member"
  1112. answer the plate viewer already relies on.
  1113. None when the archive holds no G-code at all, or its default member
  1114. doesn't follow the ``plate_N`` naming convention ``default_plate_gcode_name``
  1115. falls back to a bare first member for — callers dispatching a real print
  1116. command should fall back to plate 1 themselves in that case rather than
  1117. treat None as a plate number.
  1118. A single-plate export cut out of a larger project keeps its ORIGINAL
  1119. plate number, so a caller that instead hardcodes a plate-1 fallback sends
  1120. a print command for a plate the archive may not contain. A real printer
  1121. accepts that command, can't find the G-code, and wedges (#2947).
  1122. """
  1123. selected = default_plate_gcode_name(names)
  1124. return _plate_number_of(selected) if selected is not None else None
  1125. # The header block sits at the very top of the plate G-code. Read only that
  1126. # much: a sliced plate is routinely tens of megabytes and `ZipFile.read()`
  1127. # would inflate all of it to reach ~40 lines.
  1128. _HEADER_READ_LIMIT_BYTES = 64 * 1024
  1129. def extract_max_z_height_from_3mf(file_path: Path, plate_id: int | None = None) -> float | None:
  1130. """Return the plate's ``max_z_height`` in mm, or None if not knowable.
  1131. This is the Z the toolhead sat at for the final layer — the same value
  1132. Bambu's own end G-code adds its bed-drop offset to (``G1 Z{max_layer_z +
  1133. 100}``). #2547 uses it to put the plate back into camera framing before the
  1134. finish photo, which is only safe because it is a height the printer was
  1135. physically at seconds earlier.
  1136. None means "don't know" and callers must treat it as such rather than
  1137. substituting a default: the file may be unreadable, carry no plate G-code,
  1138. or come from a slicer that writes no ``max_z_height`` header. Guessing a
  1139. height here would command a Z move to somewhere the nozzle has never been.
  1140. """
  1141. try:
  1142. with zipfile.ZipFile(file_path, "r") as zf:
  1143. names = zf.namelist()
  1144. target = select_plate_gcode_name(names, plate_id) or default_plate_gcode_name(names)
  1145. if target is None:
  1146. return None
  1147. with zf.open(target, "r") as fh:
  1148. head = fh.read(_HEADER_READ_LIMIT_BYTES)
  1149. except (OSError, zipfile.BadZipFile, KeyError) as e:
  1150. logger.debug("max_z_height: cannot read %s: %s", file_path, e)
  1151. return None
  1152. raw = _parse_3mf_gcode_header(head.decode("utf-8", errors="ignore")).get("max_z_height")
  1153. if raw is None:
  1154. return None
  1155. try:
  1156. value = float(raw)
  1157. except ValueError:
  1158. logger.debug("max_z_height: unusable value %r in %s", raw, file_path)
  1159. return None
  1160. # Zero or negative means the header key is present but meaningless. Passed
  1161. # on as a height it would become a move *toward* the bed, so drop it.
  1162. return value if value > 0 else None
  1163. def _substitute_placeholders(snippet: str, header: dict[str, str]) -> str:
  1164. """Replace `{var}` placeholders with header values, leaving unknowns intact."""
  1165. def repl(m: re.Match) -> str:
  1166. name = m.group(1)
  1167. value = header.get(name)
  1168. if value is None:
  1169. alias = _HEADER_PLACEHOLDER_ALIASES.get(name)
  1170. if alias is not None:
  1171. value = header.get(alias)
  1172. if value is None:
  1173. logger.warning(
  1174. "G-code injection: placeholder {%s} not found in 3MF header; leaving as-is",
  1175. name,
  1176. )
  1177. return m.group(0)
  1178. return value
  1179. return _PLACEHOLDER_RE.sub(repl, snippet)
  1180. def _inject_start_at_marker(content: str, snippet: str) -> str:
  1181. """Insert snippet immediately before `; MACHINE_START_GCODE_END`.
  1182. The marker sits at the bottom of the printer's startup block — bed heat,
  1183. homing, and nozzle prime are already done, so injected snippets land in
  1184. the same place a slicer-side custom-start-gcode would. Falls back to
  1185. prepending if the marker isn't present (older files / non-Bambu slicers).
  1186. """
  1187. marker_idx = content.find(_START_GCODE_END_MARKER)
  1188. if marker_idx == -1:
  1189. logger.warning(
  1190. "G-code injection: '%s' not found, prepending start snippet to whole file",
  1191. _START_GCODE_END_MARKER,
  1192. )
  1193. return snippet.rstrip("\n") + "\n" + content
  1194. line_start = content.rfind("\n", 0, marker_idx)
  1195. line_start = 0 if line_start == -1 else line_start + 1
  1196. return content[:line_start] + snippet.rstrip("\n") + "\n" + content[line_start:]
  1197. def _inject_end_before_marker(content: str, snippet: str) -> str:
  1198. """Insert snippet immediately before `; EXECUTABLE_BLOCK_END`.
  1199. The end snippet must run *inside* the executable block. Bambu firmware
  1200. (verified on a P1S) does not execute G-code that sits after
  1201. `; EXECUTABLE_BLOCK_END`, so appending to the file end silently drops the
  1202. snippet — auto-eject / plate-clear moves never fire. Inserting before the
  1203. marker places the snippet after the printer's own machine-end sequence but
  1204. still within the executed block. Falls back to appending at the file end if
  1205. the marker isn't present.
  1206. """
  1207. marker_idx = content.find(_EXECUTABLE_BLOCK_END_MARKER)
  1208. if marker_idx == -1:
  1209. logger.warning(
  1210. "G-code injection: '%s' not found, appending end snippet to file end",
  1211. _EXECUTABLE_BLOCK_END_MARKER,
  1212. )
  1213. return content.rstrip("\n") + "\n" + snippet.rstrip("\n") + "\n"
  1214. line_start = content.rfind("\n", 0, marker_idx)
  1215. line_start = 0 if line_start == -1 else line_start + 1
  1216. return content[:line_start] + snippet.rstrip("\n") + "\n" + content[line_start:]
  1217. def inject_gcode_into_3mf(
  1218. source_path: Path,
  1219. plate_id: int,
  1220. start_gcode: str | None,
  1221. end_gcode: str | None,
  1222. ):
  1223. """Create a temp copy of a 3MF with G-code injected at start/end.
  1224. Snippets support `{placeholder}` substitution against values parsed from
  1225. the 3MF G-code header block (e.g. `{max_layer_z}` → `16.00`). Start
  1226. snippets are anchored to the `; MACHINE_START_GCODE_END` marker so they
  1227. run after the printer's own startup (#422). End snippets are inserted just
  1228. before `; EXECUTABLE_BLOCK_END` so they run inside the executable block —
  1229. Bambu firmware (P1S) ignores g-code placed after that marker.
  1230. The plate's `.gcode.md5` sidecar is recomputed so firmware that validates
  1231. it against the gcode (e.g. P1S) still accepts the modified file.
  1232. Args:
  1233. source_path: Path to the original 3MF file.
  1234. plate_id: Plate number (1-indexed) to inject into.
  1235. start_gcode: G-code to insert after printer startup, or None.
  1236. end_gcode: G-code to append, or None.
  1237. Returns:
  1238. Path to temp file with injected G-code, or None if injection failed.
  1239. Caller is responsible for cleaning up the temp file.
  1240. """
  1241. import tempfile
  1242. if not start_gcode and not end_gcode:
  1243. return None
  1244. try:
  1245. # Find the target gcode file inside the 3MF
  1246. with zipfile.ZipFile(source_path, "r") as zf:
  1247. # Plate-specific gcode first, else the lowest-numbered plate.
  1248. names = zf.namelist()
  1249. target_gcode = select_plate_gcode_name(names, plate_id) or default_plate_gcode_name(names)
  1250. if target_gcode is None:
  1251. return None
  1252. # Read and modify gcode content
  1253. gcode_content = zf.read(target_gcode).decode("utf-8", errors="ignore")
  1254. header = _parse_3mf_gcode_header(gcode_content)
  1255. if start_gcode:
  1256. resolved = _substitute_placeholders(start_gcode, header)
  1257. # Log the post-substitution snippet so the actually-injected G-code
  1258. # (placeholders like {max_layer_z} already resolved) is visible at DEBUG.
  1259. logger.debug("G-code injection [%s]: resolved START snippet:\n%s", target_gcode, resolved)
  1260. gcode_content = _inject_start_at_marker(gcode_content, resolved)
  1261. if end_gcode:
  1262. resolved = _substitute_placeholders(end_gcode, header)
  1263. logger.debug("G-code injection [%s]: resolved END snippet:\n%s", target_gcode, resolved)
  1264. gcode_content = _inject_end_before_marker(gcode_content, resolved)
  1265. # The printer validates the plate gcode against an embedded
  1266. # `<plate>.gcode.md5` sidecar (uppercase hex, no trailing newline).
  1267. # Rewriting the gcode without refreshing this hash makes firmware
  1268. # reject the file at load (P1S: HMS 0500-4003 "unable to parse"),
  1269. # so recompute it from the exact bytes we're about to write.
  1270. gcode_bytes = gcode_content.encode("utf-8")
  1271. md5_name = target_gcode + ".md5"
  1272. # Not a security hash — this reproduces Bambu's `.gcode.md5` sidecar
  1273. # format, so flag it as non-security for the linters (ruff S324 / bandit B324).
  1274. md5_value = hashlib.md5(gcode_bytes, usedforsecurity=False).hexdigest().upper().encode("ascii")
  1275. # Write modified 3MF to temp file
  1276. with tempfile.NamedTemporaryFile(delete=False, suffix=".3mf") as tmp:
  1277. tmp_path = Path(tmp.name)
  1278. with zipfile.ZipFile(tmp_path, "w", zipfile.ZIP_DEFLATED) as zf_write:
  1279. for item in zf.namelist():
  1280. info = zf.getinfo(item)
  1281. if item == target_gcode:
  1282. zf_write.writestr(info, gcode_bytes)
  1283. elif item == md5_name:
  1284. zf_write.writestr(info, md5_value)
  1285. else:
  1286. zf_write.writestr(info, zf.read(item))
  1287. return tmp_path
  1288. except Exception:
  1289. # Clean up temp file on error
  1290. if "tmp_path" in locals() and tmp_path.exists():
  1291. tmp_path.unlink(missing_ok=True)
  1292. return None
  1293. def extract_project_filaments_from_3mf(zf: zipfile.ZipFile) -> list[dict]:
  1294. """Project-wide AMS slot config from ``Metadata/project_settings.config``.
  1295. Returns one dict per configured AMS slot in slot order (1-indexed), with
  1296. ``type`` and ``color`` populated from the project's ``filament_type`` and
  1297. ``filament_colour`` arrays. ``used_grams`` / ``used_meters`` are 0 because
  1298. project_settings carries the configuration, not per-print usage — the
  1299. fields exist for shape compatibility with the slice_info-derived list.
  1300. The SliceModal needs this on **unsliced** project files: slice_info.config
  1301. is empty until Bambu Studio has actually sliced the project, but the user
  1302. can still pick filament profiles for a slice we're about to perform.
  1303. """
  1304. if "Metadata/project_settings.config" not in zf.namelist():
  1305. return []
  1306. try:
  1307. proj = json.loads(zf.read("Metadata/project_settings.config").decode())
  1308. except (ValueError, OSError):
  1309. return []
  1310. if not isinstance(proj, dict):
  1311. return []
  1312. types_arr = proj.get("filament_type") or []
  1313. colors_arr = proj.get("filament_colour") or []
  1314. slot_count = max(
  1315. len(types_arr) if isinstance(types_arr, list) else 0, len(colors_arr) if isinstance(colors_arr, list) else 0
  1316. )
  1317. out: list[dict] = []
  1318. for i in range(slot_count):
  1319. out.append(
  1320. {
  1321. "slot_id": i + 1,
  1322. "type": types_arr[i] if i < len(types_arr) and isinstance(types_arr[i], str) else "",
  1323. "color": colors_arr[i] if i < len(colors_arr) and isinstance(colors_arr[i], str) else "",
  1324. "used_grams": 0,
  1325. "used_meters": 0,
  1326. }
  1327. )
  1328. return out
  1329. def expand_to_project_slots(zf: zipfile.ZipFile, used: list[dict]) -> list[dict]:
  1330. """Widen a used-only filament list to one entry per project slot.
  1331. ``used`` is the slice_info-derived list: only the slots whose G-code
  1332. actually consumed filament, each carrying real usage figures. That is the
  1333. right answer for print-time AMS matching, and the wrong one for the slice
  1334. modal, because the list the modal builds is **positional** — index 0 is
  1335. slot 1 all the way down to the ``filament_N.json`` parts handed to the CLI.
  1336. A source whose only used slot is 4 therefore produced a single dropdown
  1337. whose pick the CLI bound to slot 1, leaving slot 4 — the one the model
  1338. prints with — on whatever the source had baked in (#2712).
  1339. Returns the project's slots in slot order, each flagged ``used_in_plate``.
  1340. Rows present in ``used`` are kept whole, so their usage figures, resolved
  1341. type/colour and ``tray_info_idx`` survive; the rest come from the project
  1342. configuration with zero usage. A used slot beyond the project's slot count
  1343. is appended rather than dropped — the caller asked for a superset, and
  1344. silently losing the one slot that prints would be the original bug again.
  1345. ``used`` is returned unchanged when the file carries no project settings
  1346. to widen against: a narrower-than-ideal list still prints correctly, an
  1347. invented one might not.
  1348. """
  1349. project = extract_project_filaments_from_3mf(zf)
  1350. if not project:
  1351. return used
  1352. by_slot = {f["slot_id"]: f for f in used}
  1353. out: list[dict] = []
  1354. for slot in project:
  1355. known = by_slot.pop(slot["slot_id"], None)
  1356. if known is not None:
  1357. known["used_in_plate"] = True
  1358. out.append(known)
  1359. else:
  1360. slot["used_in_plate"] = False
  1361. out.append(slot)
  1362. # Anything slice_info reported that the project doesn't declare.
  1363. for leftover in by_slot.values():
  1364. leftover["used_in_plate"] = True
  1365. out.append(leftover)
  1366. out.sort(key=lambda f: f["slot_id"])
  1367. return out
  1368. # BambuStudio serialises bool config options as string "1"/"0" in
  1369. # project_settings.config, but forks / older versions occasionally write real
  1370. # booleans or ints — accept anything that isn't unambiguously falsy. A missing
  1371. # key counts as off: a 3MF that never declares `enable_support` gives us no
  1372. # support intent to act on.
  1373. _SUPPORTS_DISABLED_VALUES = (False, 0, "0", "false", "False", "", None)
  1374. def supports_enabled_in_config(cfg: dict[str, object]) -> bool:
  1375. """Whether a 3MF's ``project_settings.config`` has supports switched on.
  1376. Shared by the callers that read support intent out of a source file so
  1377. they agree on what "on" means: the slot extractor below and the slice
  1378. route's process-preset support carry-over (#1881 / #2820).
  1379. """
  1380. return cfg.get("enable_support") not in _SUPPORTS_DISABLED_VALUES
  1381. def extract_support_filament_slots_from_3mf(zf: zipfile.ZipFile) -> set[int]:
  1382. """Slots referenced by the process settings for support material.
  1383. Supports aren't attached to object geometry — they're generated by
  1384. the slicer's process pass — so :func:`extract_plate_extruder_set_from_3mf`,
  1385. which walks per-object extruder metadata + paint_color triangles,
  1386. doesn't see them. Callers that need the complete set of slots a
  1387. plate print will exercise (e.g. the SliceModal's filament-
  1388. substitution logic) must union this in — otherwise a support-only
  1389. slot (typical PLA-model + PVA-support setup) looks "unused" and its
  1390. user-picked profile gets silently overwritten with slot 1's,
  1391. producing a single-material print (#1881).
  1392. Returns the empty set when supports are disabled, ``support_filament``
  1393. / ``support_interface_filament`` are 0 (== "same as model"), the
  1394. project has no embedded settings, or the file isn't a valid 3MF.
  1395. """
  1396. if "Metadata/project_settings.config" not in zf.namelist():
  1397. return set()
  1398. try:
  1399. cfg = json.loads(zf.read("Metadata/project_settings.config").decode("utf-8"))
  1400. except (json.JSONDecodeError, UnicodeDecodeError, OSError):
  1401. return set()
  1402. if not isinstance(cfg, dict):
  1403. return set()
  1404. if not supports_enabled_in_config(cfg):
  1405. return set()
  1406. out: set[int] = set()
  1407. for key in ("support_filament", "support_interface_filament"):
  1408. raw = cfg.get(key)
  1409. if raw is None:
  1410. continue
  1411. try:
  1412. slot = int(raw)
  1413. except (ValueError, TypeError):
  1414. continue
  1415. # Slot 0 means "same as model" — no dedicated slot to preserve.
  1416. if slot > 0:
  1417. out.add(slot)
  1418. return out
  1419. _PAINT_COLOR_ATTR_RE = re.compile(rb'paint_color="([0-9A-Fa-f]+)"')
  1420. def _painted_states(paint_color: bytes) -> set[int]:
  1421. """Filament numbers a triangle's ``paint_color`` paints with (#3355).
  1422. The string is the slicer's TriangleSelector tree, one hex digit per
  1423. 4-bit node, written last node first. Each node: bits 0-1 are the
  1424. number of split sides; a split node (1-3) keeps the special side in bits
  1425. 2-3 and is followed by split + 1 children. A leaf keeps its state in bits
  1426. 2-3 (0 = unpainted, 1 or 2 = that filament); ``0b11`` there means the next
  1427. node holds ``state - 3``, and a ``0xF`` in that one means one more holds
  1428. ``state - 18``. Unpainted leaves print with the object's or part's own
  1429. filament, which the caller already counts. Reading each digit as a
  1430. filament number instead (extruder 1 is written ``4``, 2 ``8``, 3 ``0C``)
  1431. left real colours out, and the slice then overwrote them.
  1432. A string that ends early is malformed: what was read is kept.
  1433. """
  1434. nibbles = [int(chr(c), 16) for c in reversed(paint_color)]
  1435. states: set[int] = set()
  1436. pos = 0
  1437. pending = 1 # nodes still to read
  1438. try:
  1439. while pending:
  1440. pending -= 1
  1441. code = nibbles[pos]
  1442. pos += 1
  1443. split_sides = code & 0b11
  1444. if split_sides:
  1445. pending += split_sides + 1
  1446. continue
  1447. if code & 0b1100 == 0b1100:
  1448. low = nibbles[pos]
  1449. pos += 1
  1450. if low == 0b1111:
  1451. state = nibbles[pos] + 18
  1452. pos += 1
  1453. else:
  1454. state = low + 3
  1455. else:
  1456. state = code >> 2
  1457. if state:
  1458. states.add(state)
  1459. except IndexError:
  1460. pass
  1461. return states
  1462. def extract_plate_extruder_set_from_3mf(zf: zipfile.ZipFile, plate_id: int) -> set[int]:
  1463. """Extruder/AMS slot indices (1-indexed) used by objects on ``plate_id``.
  1464. Three sources are unioned because Bambu Studio splits per-object extruder
  1465. info across THREE places depending on how the user assigned colours:
  1466. 1. ``model_settings.config`` — top-level ``<metadata key="extruder">``
  1467. on each ``<object>`` (the "default extruder" for the whole object).
  1468. 2. ``model_settings.config`` — per-``<part>`` ``<metadata key="extruder">``
  1469. overrides (used when the user split an object into multiple parts
  1470. with distinct filaments).
  1471. 3. ``3D/Objects/object_*.model`` — ``paint_color`` attributes on
  1472. individual ``<triangle>`` elements (used when the user "painted" a
  1473. face with a different filament), decoded by :func:`_painted_states`.
  1474. Every painted leaf counts, however small: the slicer prints it with
  1475. that filament, so the slot is used.
  1476. Without (3) the painted-face data is invisible: model_settings says
  1477. every object on a multi-color plate uses extruder 1 by default but the
  1478. actual print uses 3, 4, 12 etc. via face paint, so the SliceModal would
  1479. render only one filament dropdown for what's clearly a multi-colour
  1480. print (#1150 follow-up).
  1481. """
  1482. if "Metadata/model_settings.config" not in zf.namelist():
  1483. return set()
  1484. try:
  1485. root = ET.fromstring(zf.read("Metadata/model_settings.config").decode())
  1486. except (ET.ParseError, OSError):
  1487. return set()
  1488. # Pass 1: object → set of extruders from XML metadata (sources 1 + 2)
  1489. # plus the per-object .model file path so we can later scan source 3.
  1490. object_extruders: dict[str, set[int]] = {}
  1491. object_model_paths: dict[str, list[str]] = {}
  1492. for obj_elem in root.findall(".//object"):
  1493. obj_id = obj_elem.get("id")
  1494. if not obj_id:
  1495. continue
  1496. extruders: set[int] = set()
  1497. top = obj_elem.find("metadata[@key='extruder']")
  1498. if top is not None:
  1499. try:
  1500. v = int(top.get("value", "0"))
  1501. if v > 0:
  1502. extruders.add(v)
  1503. except (ValueError, TypeError):
  1504. pass
  1505. for part_elem in obj_elem.findall(".//part"):
  1506. part_ext = part_elem.find("metadata[@key='extruder']")
  1507. if part_ext is None:
  1508. continue
  1509. try:
  1510. v = int(part_ext.get("value", "0"))
  1511. if v > 0:
  1512. extruders.add(v)
  1513. except (ValueError, TypeError):
  1514. pass
  1515. object_extruders[obj_id] = extruders
  1516. # Pass 2: 3dmodel.model maps each <object id="N"> to its component
  1517. # .model file path(s). Bambu wraps object IDs that match
  1518. # model_settings.config IDs around <components><component
  1519. # path="/3D/Objects/object_K.model" objectid="..." /></components>.
  1520. # Strip xmlns prefixes on attributes so ElementTree can find them
  1521. # without namespace gymnastics — `p:path` becomes `path` etc.
  1522. if "3D/3dmodel.model" in zf.namelist():
  1523. try:
  1524. raw = zf.read("3D/3dmodel.model").decode()
  1525. stripped = re.sub(r'xmlns:?\w*="[^"]*"', "", raw)
  1526. stripped = re.sub(r"<(/?)\w+:", r"<\1", stripped)
  1527. stripped = re.sub(r" \w+:(\w+=)", r" \1", stripped)
  1528. model_root = ET.fromstring(stripped)
  1529. for obj_elem in model_root.findall(".//object"):
  1530. oid = obj_elem.get("id")
  1531. if not oid:
  1532. continue
  1533. comps = obj_elem.find("components")
  1534. if comps is None:
  1535. continue
  1536. paths = []
  1537. for c in comps.findall("component"):
  1538. p = c.get("path")
  1539. if p:
  1540. paths.append(p.lstrip("/"))
  1541. if paths:
  1542. object_model_paths[oid] = paths
  1543. except (ET.ParseError, OSError):
  1544. pass # No 3dmodel — paint scan just won't apply
  1545. # Pass 3: scan paint_color attrs in each per-object .model file. Cache
  1546. # by file path because two objects often share the same component tree.
  1547. paint_cache: dict[str, set[int]] = {}
  1548. def _scan_paint(path: str) -> set[int]:
  1549. if path in paint_cache:
  1550. return paint_cache[path]
  1551. out: set[int] = set()
  1552. if path not in zf.namelist():
  1553. paint_cache[path] = out
  1554. return out
  1555. try:
  1556. data = zf.read(path)
  1557. except OSError:
  1558. paint_cache[path] = out
  1559. return out
  1560. # Whole-triangle paints repeat ("4", "8", ...): decode each string once.
  1561. for paint in {match.group(1) for match in _PAINT_COLOR_ATTR_RE.finditer(data)}:
  1562. out |= _painted_states(paint)
  1563. paint_cache[path] = out
  1564. return out
  1565. # Walk plates — collect extruders for objects on the requested plate.
  1566. used: set[int] = set()
  1567. for plate_elem in root.findall(".//plate"):
  1568. plater_id = None
  1569. for meta in plate_elem.findall("metadata"):
  1570. if meta.get("key") == "plater_id":
  1571. try:
  1572. plater_id = int(meta.get("value", ""))
  1573. except (ValueError, TypeError):
  1574. pass
  1575. break
  1576. if plater_id != plate_id:
  1577. continue
  1578. for inst in plate_elem.findall("model_instance"):
  1579. for inst_meta in inst.findall("metadata"):
  1580. if inst_meta.get("key") != "object_id":
  1581. continue
  1582. obj_id = inst_meta.get("value")
  1583. if not obj_id:
  1584. continue
  1585. used.update(object_extruders.get(obj_id, set()))
  1586. for path in object_model_paths.get(obj_id, []):
  1587. used.update(_scan_paint(path))
  1588. break
  1589. return used
  1590. # Keys in ``Metadata/project_settings.config`` that Bambu Studio writes an
  1591. # "inherit / unset" marker into, mapped to the marker it uses for that key.
  1592. # The slicer CLI's ``StaticPrintConfig`` validator runs against the embedded
  1593. # settings *before* ``--load-settings`` overrides apply, so a marker the CLI's
  1594. # own range check rejects makes it exit non-zero before our profile triplet is
  1595. # ever consulted.
  1596. #
  1597. # There are two markers because there are two conventions, and which one a
  1598. # given CLI rejects depends on the build:
  1599. #
  1600. # "-1" -- inherit from the parent process preset (#1201, MakerWorld P2S
  1601. # 3MFs). ``raft_first_layer_expansion`` and ``tree_support_wall_count`` are
  1602. # min 0 in every OrcaSlicer to date, so those still fail on the current
  1603. # sidecar; ``prime_tower_brim_width`` gained min -1 in Orca 2.4.2 and now
  1604. # passes there, but not on older builds.
  1605. #
  1606. # "0" -- "use the active object/part filament", the default Bambu Studio
  1607. # writes for the three feature-filament indices (#3030). Bambu Studio and
  1608. # OrcaSlicer 2.4.0+ both define these min 0, so 0 is legal there; OrcaSlicer
  1609. # 2.3.x and earlier still used the 1-based scheme (min 1, default 1) and
  1610. # reject it with ``0 not in range [1.000000,...]``. Sidecar images are
  1611. # version-tagged, so an install can be pinned to one of those.
  1612. #
  1613. # Removing the key rather than rewriting it is what makes this safe on every
  1614. # build: the CLI then falls back to its own compiled default, which is 0 on
  1615. # the builds where 0 was legal (so nothing changes) and 1 on the older ones,
  1616. # which is what "the active filament" means under that scheme.
  1617. #
  1618. # Allowlisted (rather than "strip every marker-shaped value") because some
  1619. # fields legitimately take the marker value -- z_offset, translations, and any
  1620. # feature index a user really did set to a first filament -- and a blanket
  1621. # strip would silently corrupt those.
  1622. #
  1623. # Add new entries as reports surface: the slicer names the offending field
  1624. # directly, e.g. ``<field>: <value> not in range [...]``.
  1625. PROJECT_SETTINGS_SENTINELS: dict[str, str] = {
  1626. # Reported in #1201 (MakerWorld P2S 3MFs).
  1627. "raft_first_layer_expansion": "-1",
  1628. "tree_support_wall_count": "-1",
  1629. # Known sentinel case from earlier reports, cited in #1201.
  1630. "prime_tower_brim_width": "-1",
  1631. # Reported in #3030 (MakerWorld 3MF, OrcaSlicer sidecar).
  1632. "wall_filament": "0",
  1633. "sparse_infill_filament": "0",
  1634. "solid_infill_filament": "0",
  1635. }
  1636. PROJECT_SETTINGS_PATH = "Metadata/project_settings.config"
  1637. def _is_sentinel(value: object, sentinel: str) -> bool:
  1638. """Does ``value`` carry ``sentinel``, whether stored as text or a number?
  1639. Bambu Studio writes every ``project_settings.config`` value as a string,
  1640. but a 3MF that has been round-tripped through another tool can carry the
  1641. same field as a JSON number. ``bool`` is excluded explicitly: it is an
  1642. ``int`` subclass in Python, and ``str(False)`` would otherwise never match
  1643. anyway -- the exclusion is there so a future numeric sentinel like ``0``
  1644. cannot be matched by ``False``.
  1645. """
  1646. if isinstance(value, bool):
  1647. return False
  1648. if isinstance(value, (str, int)):
  1649. return str(value) == sentinel
  1650. return False
  1651. def sanitize_project_settings_sentinels(zip_bytes: bytes) -> bytes:
  1652. """Strip inherit/unset sentinels from a 3MF's ``project_settings.config``
  1653. so the slicer CLI's range validator accepts the file (#1201, #3030).
  1654. Removes only allowlisted keys (see ``PROJECT_SETTINGS_SENTINELS``) and only
  1655. when the value is exactly that key's sentinel. The rest of the config --
  1656. and every other entry in the zip -- is preserved byte-for-byte. Unlike a
  1657. whole-file strip this leaves ``StaticPrintConfig`` initialisation intact:
  1658. the file is still present, still parses, and the slicer falls back to the
  1659. supplied ``--load-settings`` value, or to its own default, for the removed
  1660. key.
  1661. Returns the original bytes unchanged when no sanitisation is needed (input
  1662. isn't a valid zip, no ``project_settings.config``, no allowlisted sentinels
  1663. present, or any other parse failure) so the caller can pass the result on
  1664. without further checks.
  1665. """
  1666. from io import BytesIO
  1667. try:
  1668. with zipfile.ZipFile(BytesIO(zip_bytes), "r") as zin:
  1669. if PROJECT_SETTINGS_PATH not in zin.namelist():
  1670. return zip_bytes
  1671. try:
  1672. config = json.loads(zin.read(PROJECT_SETTINGS_PATH).decode("utf-8"))
  1673. except (json.JSONDecodeError, UnicodeDecodeError):
  1674. return zip_bytes
  1675. if not isinstance(config, dict):
  1676. return zip_bytes
  1677. removed = {
  1678. key: sentinel
  1679. for key, sentinel in PROJECT_SETTINGS_SENTINELS.items()
  1680. if _is_sentinel(config.get(key), sentinel)
  1681. }
  1682. if not removed:
  1683. return zip_bytes
  1684. for key in removed:
  1685. config.pop(key, None)
  1686. patched = json.dumps(config)
  1687. logger.info(
  1688. "3MF sanitiser: removed inherit sentinels %s - slicer will use its defaults for those keys",
  1689. sorted(f"{key}={sentinel}" for key, sentinel in removed.items()),
  1690. )
  1691. dst = BytesIO()
  1692. with zipfile.ZipFile(dst, "w", zipfile.ZIP_DEFLATED) as zout:
  1693. for item in zin.infolist():
  1694. if item.filename == PROJECT_SETTINGS_PATH:
  1695. zout.writestr(item, patched)
  1696. else:
  1697. zout.writestr(item, zin.read(item.filename))
  1698. return dst.getvalue()
  1699. except (zipfile.BadZipFile, OSError):
  1700. return zip_bytes