useFilamentMapping.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  1. import { useMemo } from 'react';
  2. import { getColorName } from '../utils/colors';
  3. import type { RackGroupInfo } from '../components/PrintModal/types';
  4. import {
  5. normalizeColor,
  6. normalizeColorForCompare,
  7. colorsAreSimilar,
  8. filamentTypesCompatible,
  9. findNearestSimilar,
  10. formatSlotLabel,
  11. getGlobalTrayId,
  12. isAmsHtUnit,
  13. preferLowestSortKey,
  14. compareSortKeys,
  15. rackExternalLabel,
  16. } from '../utils/amsHelpers';
  17. import { externalSlotIndex, trayLayoutOf } from '../utils/trayIds';
  18. import { markBlocked } from '../utils/filamentScope';
  19. import type { FilamentPolicy, PrinterStatus, SlotSpoolIdentity } from '../api/client';
  20. /** Global-tray-id → the identity of the spool Bambuddy has bound to that slot. */
  21. export type SlotSpoolIdentities = Map<number, SlotSpoolIdentity>;
  22. /**
  23. * Name a slot after the spool bound to it, the way the printer card does.
  24. *
  25. * Telemetry can only ever say "PLA" plus a colour hex for anything that isn't
  26. * a Bambu spool: the tray record has no brand field, `tray_sub_brands` stays
  27. * empty, and the hex gets resolved against Bambu's own colour catalogue. So a
  28. * Devil Design PLA Basic Orange the operator assigned in Bambuddy read back as
  29. * "PLA (Sunflower Yellow)" here while the printer card named it correctly.
  30. *
  31. * Returns null when the slot has no binding or the binding says nothing
  32. * useful, and the caller keeps the telemetry description it had before.
  33. */
  34. function spoolDisplayName(identity: SlotSpoolIdentity | undefined): string | null {
  35. if (!identity) return null;
  36. // Same order the hover card prints: brand, then material, then subtype.
  37. const parts = [identity.brand, identity.material, identity.subtype].filter(Boolean);
  38. return parts.length > 0 ? parts.join(' ') : null;
  39. }
  40. /**
  41. * Build loaded filaments list from printer status (non-hook version).
  42. * Extracts filaments from all AMS units (regular and HT) and external spool.
  43. *
  44. * `slotSpools` is optional and display-only: it renames slots after their
  45. * bound spool without touching `type`, `color` or `trayInfoIdx`, so matching
  46. * and the dispatcher keep drawing on the printer's own telemetry.
  47. *
  48. * `policies` are the signed-in user's filament rules (#3522): trays they don't
  49. * allow come back with `blocked` set.
  50. */
  51. export function buildLoadedFilaments(
  52. printerStatus: PrinterStatus | undefined,
  53. slotSpools?: SlotSpoolIdentities,
  54. policies?: FilamentPolicy[] | null,
  55. ): LoadedFilament[] {
  56. const filaments: LoadedFilament[] = [];
  57. const amsExtruderMap = printerStatus?.ams_extruder_map;
  58. // Dual-nozzle detection. The backend always emits a 2-entry nozzles array
  59. // (default-stub second entry for single-nozzle printers), so length is not
  60. // a reliable signal. Real second-nozzle hardware sets `nozzle_diameter` from
  61. // the MQTT `right_nozzle_diameter` field (bambu_mqtt.py:2619-2621); without
  62. // that field, nozzles[1] stays at its empty default. Belt-and-braces: a
  63. // populated ams_extruder_map (dual-nozzle with AMS) and >1 vt_tray (only
  64. // dual-nozzle hardware exposes multiple external feeds) each independently
  65. // imply dual-nozzle — keep them as fallbacks for any firmware rev that
  66. // surfaces one signal but not the other. (#1257)
  67. // A rack printer (H3C) has nine external inputs but one extruder.
  68. const rackExternals = trayLayoutOf(printerStatus?.ams, printerStatus?.vt_tray).rack;
  69. const hasDualNozzle =
  70. Boolean(printerStatus?.nozzles?.[1]?.nozzle_diameter)
  71. || (amsExtruderMap && Object.keys(amsExtruderMap).length > 0)
  72. || ((printerStatus?.vt_tray?.length ?? 0) > 1 && !rackExternals);
  73. // Add filaments from all AMS units (regular and HT)
  74. printerStatus?.ams?.forEach((amsUnit) => {
  75. const isHt = isAmsHtUnit(amsUnit.id);
  76. amsUnit.tray.forEach((tray) => {
  77. if (tray.tray_type) {
  78. const color = normalizeColor(tray.tray_color);
  79. const globalTrayId = getGlobalTrayId(amsUnit.id, tray.id, false, amsUnit.ams_type);
  80. const identity = slotSpools?.get(globalTrayId);
  81. filaments.push({
  82. type: tray.tray_type,
  83. color,
  84. colorName: identity?.color_name?.trim() || getColorName(color, tray.tray_sub_brands, tray.tray_info_idx),
  85. amsId: amsUnit.id,
  86. trayId: tray.id,
  87. isHt,
  88. isExternal: false,
  89. label: formatSlotLabel(amsUnit.id, tray.id, isHt, false, amsUnit.ams_type),
  90. globalTrayId,
  91. trayInfoIdx: tray.tray_info_idx || '',
  92. traySubBrands: tray.tray_sub_brands || '',
  93. spoolName: spoolDisplayName(identity) ?? undefined,
  94. extraColors: identity?.extra_colors ?? undefined,
  95. effectType: identity?.effect_type ?? undefined,
  96. spoolSubtype: identity?.subtype ?? undefined,
  97. extruderId: amsExtruderMap?.[String(amsUnit.id)],
  98. remain: tray.remain ?? -1,
  99. });
  100. }
  101. });
  102. });
  103. // Add external spool(s) if loaded
  104. for (const extTray of printerStatus?.vt_tray ?? []) {
  105. if (extTray.tray_type) {
  106. const color = normalizeColor(extTray.tray_color);
  107. const trayId = extTray.id ?? 254;
  108. const hasDualExternal = (printerStatus?.vt_tray?.length ?? 0) > 1 && !rackExternals;
  109. // The external holder's global tray id IS the tray id (254 / 255), which
  110. // is how the backend keys it too — see `_ams_key_to_global`.
  111. const identity = slotSpools?.get(trayId);
  112. filaments.push({
  113. type: extTray.tray_type,
  114. color,
  115. colorName: identity?.color_name?.trim() || getColorName(color, extTray.tray_sub_brands, extTray.tray_info_idx),
  116. amsId: -1,
  117. trayId: externalSlotIndex(trayId),
  118. isHt: false,
  119. isExternal: true,
  120. label: rackExternals ? rackExternalLabel(trayId) : hasDualExternal ? (trayId === 254 ? 'Ext-L' : 'Ext-R') : 'External',
  121. globalTrayId: trayId,
  122. trayInfoIdx: extTray.tray_info_idx || '',
  123. traySubBrands: extTray.tray_sub_brands || '',
  124. spoolName: spoolDisplayName(identity) ?? undefined,
  125. extraColors: identity?.extra_colors ?? undefined,
  126. effectType: identity?.effect_type ?? undefined,
  127. spoolSubtype: identity?.subtype ?? undefined,
  128. extruderId: hasDualNozzle ? (255 - trayId) : undefined,
  129. remain: extTray.remain ?? -1,
  130. });
  131. }
  132. }
  133. return markBlocked(filaments, policies);
  134. }
  135. /**
  136. * Compute AMS mapping for a printer given filament requirements and printer status.
  137. * This is a non-hook version that can be called imperatively (e.g., in a loop for multiple printers).
  138. *
  139. * Priority: unique tray_info_idx match > exact color match > similar color match > type-only match
  140. *
  141. * The tray_info_idx is a filament type identifier stored in the 3MF file when the user
  142. * slices (e.g., "GFA00" for generic PLA, "P4d64437" for custom presets). If the same
  143. * tray_info_idx appears in only ONE available tray, we use that tray. If multiple trays
  144. * have the same tray_info_idx (e.g., two spools of generic PLA), we fall back to color
  145. * matching among those trays.
  146. *
  147. * @param filamentReqs - Required filaments from the 3MF file
  148. * @param printerStatus - Current printer status with AMS information
  149. * @param policies - The signed-in user's filament rules (#3522); blocked trays are never picked
  150. * @returns AMS mapping array or undefined if no mapping needed
  151. */
  152. export function computeAmsMapping(
  153. filamentReqs: { filaments: FilamentRequirement[] } | undefined,
  154. printerStatus: PrinterStatus | undefined,
  155. preferLowest?: boolean,
  156. inventoryByTrayId?: Map<number, number>,
  157. policies?: FilamentPolicy[] | null,
  158. ): number[] | undefined {
  159. const loadedFilaments = buildLoadedFilaments(printerStatus, undefined, policies);
  160. if (loadedFilaments.length === 0) return undefined;
  161. // FTS routes any AMS slot to any extruder, so per-nozzle slot restriction
  162. // doesn't apply when it's installed (#1162).
  163. const ftsActive = printerStatus?.fila_switch?.installed === true;
  164. // No manual overrides on this path — it maps a printer the user is not looking
  165. // at (per-printer fan-out), so there is no panel to override a slot in.
  166. return buildAmsMapping(
  167. buildFilamentComparison(filamentReqs, loadedFilaments, {}, preferLowest, inventoryByTrayId, ftsActive),
  168. );
  169. }
  170. /**
  171. * Represents a loaded filament in the printer's AMS/HT/External spool holder.
  172. */
  173. export interface LoadedFilament {
  174. type: string;
  175. color: string;
  176. colorName: string;
  177. amsId: number;
  178. trayId: number;
  179. isHt: boolean;
  180. isExternal: boolean;
  181. label: string;
  182. globalTrayId: number;
  183. /** Unique spool identifier (e.g., "GFA00", "P4d64437") */
  184. trayInfoIdx?: string;
  185. /** Filament subtype name (e.g., "PLA Basic", "PLA Matte", "PETG HF") */
  186. traySubBrands?: string;
  187. /** "Devil Design PLA Basic" — the spool Bambuddy has bound to this slot,
  188. * when there is one. Display only; prefer it over `traySubBrands`, which
  189. * the printer leaves empty for everything that isn't a Bambu spool. */
  190. spoolName?: string;
  191. /** Extruder ID for dual-nozzle printers (0=right, 1=left) */
  192. extruderId?: number;
  193. /** Remaining filament percentage (0-100), -1 = unknown */
  194. remain: number;
  195. /** The bound spool's remaining colour stops and effect overlay, when the
  196. * slot has a binding (#3159). Display only, like `spoolName`: a tray record
  197. * carries one hex, so without these a two-tone spool draws as its base
  198. * colour. Absent for a slot configured on the printer -- the firmware has
  199. * nothing to report, and a solid swatch is then the honest one. */
  200. extraColors?: string;
  201. effectType?: string;
  202. /** The bound spool's subtype ("PLA Silk", "Multicolor"), which decides
  203. * whether the swatch renders its stops as a conic sweep. */
  204. spoolSubtype?: string;
  205. /** The signed-in user's groups may not use this filament (#3522): never auto-picked, greyed out in the picker */
  206. blocked?: boolean;
  207. }
  208. /**
  209. * Represents a required filament from the 3MF file.
  210. */
  211. export interface FilamentRequirement {
  212. slot_id: number;
  213. type: string;
  214. color: string;
  215. used_grams: number;
  216. /** Unique spool identifier from slicing (e.g., "GFA00", "P4d64437") */
  217. tray_info_idx?: string;
  218. /** Target nozzle for dual-nozzle printers (0=right, 1=left) */
  219. nozzle_id?: number;
  220. /** Filament group this slot prints in, on a nozzle-rack machine (#1784).
  221. * The group is the slicer's logical nozzle, so it is what a rack position
  222. * gets chosen for. Absent on every other model. */
  223. group_id?: number;
  224. /** What that group needs of a hotend, for filtering the rack positions it
  225. * can be sent to. */
  226. group?: RackGroupInfo;
  227. }
  228. /**
  229. * Status of filament comparison between required and loaded.
  230. */
  231. export type FilamentStatus = 'match' | 'type_only' | 'mismatch' | 'empty';
  232. /**
  233. * Result of comparing a required filament with loaded filaments.
  234. */
  235. export interface FilamentComparison extends FilamentRequirement {
  236. loaded: LoadedFilament | undefined;
  237. hasFilament: boolean;
  238. typeMatch: boolean;
  239. colorMatch: boolean;
  240. status: FilamentStatus;
  241. isManual: boolean;
  242. }
  243. export interface FilamentRequirementsResponse {
  244. filaments: FilamentRequirement[];
  245. }
  246. interface UseFilamentMappingResult {
  247. /** List of all filaments loaded in the printer */
  248. loadedFilaments: LoadedFilament[];
  249. /** Comparison results for each required filament */
  250. filamentComparison: FilamentComparison[];
  251. /** AMS mapping array for the print command */
  252. amsMapping: number[] | undefined;
  253. /** Whether any required filament type is not loaded */
  254. hasTypeMismatch: boolean;
  255. /** Whether any required filament has a color mismatch */
  256. hasColorMismatch: boolean;
  257. }
  258. /**
  259. * Hook to build loaded filaments list from printer status.
  260. * Extracts filaments from all AMS units (regular and HT) and external spool.
  261. */
  262. export function useLoadedFilaments(
  263. printerStatus: PrinterStatus | undefined,
  264. slotSpools?: SlotSpoolIdentities,
  265. policies?: FilamentPolicy[] | null,
  266. ): LoadedFilament[] {
  267. return useMemo(() => {
  268. return buildLoadedFilaments(printerStatus, slotSpools, policies);
  269. }, [printerStatus, slotSpools, policies]);
  270. }
  271. /**
  272. * Does the tray we picked actually carry the colour the slice asked for?
  273. *
  274. * Shared by the manual and auto branches below so the two can never disagree
  275. * about the same tray again (#2687). Exact hex first, then the perceptual
  276. * tolerance, so a spool the printer reports one shade off still reads as a
  277. * match.
  278. *
  279. * A requirement with no colour at all is not a mismatch — the 3MF simply
  280. * didn't ask for one (`filament_requirements.py` defaults it to `""`), so any
  281. * loaded colour satisfies it. Loaded trays always have a colour: buildLoaded-
  282. * Filaments falls back to grey when MQTT reports none.
  283. */
  284. function coloursMatch(loadedColor: string | undefined, requiredColor: string | undefined): boolean {
  285. const required = normalizeColorForCompare(requiredColor);
  286. if (!required) return true;
  287. return (
  288. normalizeColorForCompare(loadedColor) === required || colorsAreSimilar(loadedColor, requiredColor)
  289. );
  290. }
  291. /**
  292. * Compare required filaments with loaded filaments (non-hook version).
  293. *
  294. * Tray assignment is stateful across the list — a tray matched to one slot is
  295. * not offered to the next — so this must be run over exactly the slots of one
  296. * print, never a union of several plates: two plates that share a colour on
  297. * different slots would otherwise compete for the same tray and one of them
  298. * would fall through to a worse match, or to none (#2551 follow-up).
  299. */
  300. export function buildFilamentComparison(
  301. filamentReqs: FilamentRequirementsResponse | undefined,
  302. loadedFilaments: LoadedFilament[],
  303. manualMappings: Record<number, number>,
  304. preferLowest?: boolean,
  305. inventoryByTrayId?: Map<number, number>,
  306. ftsActive = false,
  307. ): FilamentComparison[] {
  308. if (!filamentReqs?.filaments || filamentReqs.filaments.length === 0) return [];
  309. // Track which trays have been assigned to avoid duplicates
  310. // First, mark all manually assigned trays as used
  311. const usedTrayIds = new Set<number>(Object.values(manualMappings));
  312. return filamentReqs.filaments.map((req) => {
  313. const slotId = req.slot_id || 0;
  314. // Check if there's a manual override for this slot
  315. if (slotId > 0 && manualMappings[slotId] !== undefined) {
  316. const manualTrayId = manualMappings[slotId];
  317. const manualLoaded = loadedFilaments.find((f) => f.globalTrayId === manualTrayId);
  318. if (manualLoaded) {
  319. const typeMatch = filamentTypesCompatible(manualLoaded.type, req.type);
  320. const colorMatch = coloursMatch(manualLoaded.color, req.color);
  321. let status: FilamentStatus;
  322. if (typeMatch && colorMatch) {
  323. status = 'match';
  324. } else if (typeMatch) {
  325. status = 'type_only';
  326. } else {
  327. status = 'mismatch';
  328. }
  329. return {
  330. ...req,
  331. loaded: manualLoaded,
  332. hasFilament: true,
  333. typeMatch,
  334. colorMatch,
  335. status,
  336. isManual: true,
  337. };
  338. }
  339. }
  340. // Auto-match: Find a loaded filament
  341. // Priority: unique tray_info_idx match > exact color match > similar color match > type-only match
  342. // IMPORTANT: Exclude trays that are already assigned (manually or auto)
  343. const reqTrayInfoIdx = req.tray_info_idx || '';
  344. // Get available trays (not already used). A tray the user's groups block is
  345. // never auto-picked (#3522); a manual pick of one is kept above as theirs,
  346. // and the scheduler re-picks it at dispatch.
  347. let available = loadedFilaments.filter((f) => !usedTrayIds.has(f.globalTrayId) && !f.blocked);
  348. // Nozzle-aware filtering: restrict to trays on the correct nozzle.
  349. // This is a hard filter — cross-nozzle assignment causes print failures.
  350. // Skip when an FTS is installed: it can route any slot to either extruder.
  351. if (req.nozzle_id != null && !ftsActive) {
  352. available = available.filter((f) => f.extruderId === req.nozzle_id);
  353. }
  354. // Sort lowest-first when the preference is on. Inventory-tracked spools
  355. // sort before MQTT-only ones; see preferLowestSortKey for the rationale.
  356. if (preferLowest) {
  357. available = [...available].sort((a, b) =>
  358. compareSortKeys(
  359. preferLowestSortKey(a, inventoryByTrayId),
  360. preferLowestSortKey(b, inventoryByTrayId),
  361. ),
  362. );
  363. }
  364. let idxMatch: LoadedFilament | undefined;
  365. let exactMatch: LoadedFilament | undefined;
  366. let similarMatch: LoadedFilament | undefined;
  367. let typeOnlyMatch: LoadedFilament | undefined;
  368. // Check if tray_info_idx is unique among available trays
  369. if (reqTrayInfoIdx) {
  370. const idxMatches = available.filter((f) => f.trayInfoIdx === reqTrayInfoIdx);
  371. if (idxMatches.length === 1) {
  372. // Unique tray_info_idx - use it as definitive match
  373. idxMatch = idxMatches[0];
  374. } else if (idxMatches.length > 1) {
  375. // Multiple trays with same tray_info_idx - use color matching among them
  376. if (preferLowest) {
  377. idxMatches.sort((a, b) =>
  378. compareSortKeys(
  379. preferLowestSortKey(a, inventoryByTrayId),
  380. preferLowestSortKey(b, inventoryByTrayId),
  381. ),
  382. );
  383. }
  384. exactMatch = idxMatches.find(
  385. (f) =>
  386. filamentTypesCompatible(f.type, req.type) &&
  387. normalizeColorForCompare(f.color) === normalizeColorForCompare(req.color)
  388. );
  389. if (!exactMatch) {
  390. similarMatch = findNearestSimilar(
  391. idxMatches.filter((f) => filamentTypesCompatible(f.type, req.type)),
  392. req.color,
  393. (f) => f.color,
  394. );
  395. }
  396. if (!exactMatch && !similarMatch) {
  397. typeOnlyMatch = idxMatches.find(
  398. (f) => filamentTypesCompatible(f.type, req.type)
  399. );
  400. }
  401. }
  402. }
  403. // If no idx match, do standard type/color matching on all available trays
  404. if (!idxMatch && !exactMatch && !similarMatch && !typeOnlyMatch) {
  405. exactMatch = available.find(
  406. (f) =>
  407. filamentTypesCompatible(f.type, req.type) &&
  408. normalizeColorForCompare(f.color) === normalizeColorForCompare(req.color)
  409. );
  410. if (!exactMatch) {
  411. similarMatch = findNearestSimilar(
  412. available.filter((f) => filamentTypesCompatible(f.type, req.type)),
  413. req.color,
  414. (f) => f.color,
  415. );
  416. }
  417. if (!exactMatch && !similarMatch) {
  418. typeOnlyMatch = available.find(
  419. (f) => filamentTypesCompatible(f.type, req.type)
  420. );
  421. }
  422. }
  423. const loaded = idxMatch || exactMatch || similarMatch || typeOnlyMatch || undefined;
  424. // Mark this tray as used so it won't be assigned to another slot
  425. if (loaded) {
  426. usedTrayIds.add(loaded.globalTrayId);
  427. }
  428. const hasFilament = !!loaded;
  429. const typeMatch = hasFilament;
  430. // #2687: judge the colour on the tray we actually picked, never on which
  431. // branch found it. tray_info_idx identifies the filament *variant* — GFA00
  432. // is PLA Basic, GFA01 PLA Matte, GFA17 PLA Translucent — not an individual
  433. // spool, so one Matte spool idx-matches every Matte requirement whatever
  434. // colour it is. The old rule ("same spool = same color") therefore reported
  435. // red-required-on-green-loaded as a match, while manually picking that same
  436. // tray reported the mismatch honestly. Variant still decides *selection*
  437. // (#2650: Basic is not Matte) — it just no longer decides the verdict.
  438. const colorMatch = hasFilament && coloursMatch(loaded.color, req.color);
  439. // No tray of the required type at all is a type mismatch; otherwise the
  440. // colour decides between a full match and type-only.
  441. let status: FilamentStatus;
  442. if (!hasFilament) {
  443. status = 'mismatch';
  444. } else if (colorMatch) {
  445. status = 'match';
  446. } else {
  447. status = 'type_only';
  448. }
  449. return {
  450. ...req,
  451. loaded,
  452. hasFilament,
  453. typeMatch,
  454. colorMatch,
  455. status,
  456. isManual: false,
  457. };
  458. });
  459. }
  460. /**
  461. * Build the AMS mapping array the print command carries (non-hook version).
  462. * Position = slot_id - 1 (0-indexed), value = global tray ID, or -1 for a slot
  463. * with no matching tray. Indexed by the 3MF's own slot ids, which are global to
  464. * the file, so a plate that only prints slot 3 still emits `[-1, -1, tray]`.
  465. */
  466. export function buildAmsMapping(filamentComparison: FilamentComparison[]): number[] | undefined {
  467. if (filamentComparison.length === 0) return undefined;
  468. const maxSlotId = Math.max(...filamentComparison.map((f) => f.slot_id || 0));
  469. if (maxSlotId <= 0) return undefined;
  470. const mapping = new Array(maxSlotId).fill(-1);
  471. filamentComparison.forEach((f) => {
  472. if (f.slot_id && f.slot_id > 0) {
  473. mapping[f.slot_id - 1] = f.loaded?.globalTrayId ?? -1;
  474. }
  475. });
  476. return mapping;
  477. }
  478. /**
  479. * Hook to compare required filaments with loaded filaments and build AMS mapping.
  480. * Handles both auto-matching and manual overrides.
  481. *
  482. * @param filamentReqs - Required filaments from the 3MF file
  483. * @param printerStatus - Current printer status with AMS information
  484. * @param manualMappings - Manual slot overrides (slot_id -> globalTrayId)
  485. */
  486. export function useFilamentMapping(
  487. filamentReqs: FilamentRequirementsResponse | undefined,
  488. printerStatus: PrinterStatus | undefined,
  489. manualMappings: Record<number, number>,
  490. preferLowest?: boolean,
  491. inventoryByTrayId?: Map<number, number>,
  492. slotSpools?: SlotSpoolIdentities,
  493. /** The signed-in user's filament rules (#3522), from `useFilamentPolicies` */
  494. policies?: FilamentPolicy[] | null,
  495. ): UseFilamentMappingResult {
  496. const loadedFilaments = useLoadedFilaments(printerStatus, slotSpools, policies);
  497. // FTS routes any AMS slot to any extruder, so per-nozzle slot restriction
  498. // doesn't apply when it's installed (#1162).
  499. const ftsActive = printerStatus?.fila_switch?.installed === true;
  500. const filamentComparison = useMemo(
  501. () =>
  502. buildFilamentComparison(
  503. filamentReqs,
  504. loadedFilaments,
  505. manualMappings,
  506. preferLowest,
  507. inventoryByTrayId,
  508. ftsActive,
  509. ),
  510. [filamentReqs, loadedFilaments, manualMappings, preferLowest, ftsActive, inventoryByTrayId],
  511. );
  512. // Don't emit a mapping until the printer's trays are known. With no loaded
  513. // filaments (e.g. printerStatus still loading), buildFilamentComparison marks
  514. // every required slot unmatched and buildAmsMapping would serialize an
  515. // all-[-1] array — which the backend used to treat as an explicit
  516. // external-spool selection, silently printing to an empty feed (#2589).
  517. // Return undefined instead so the scheduler resolves the mapping from live
  518. // status at dispatch. Mirrors the guard in computeAmsMapping.
  519. const amsMapping = useMemo(
  520. () => (loadedFilaments.length === 0 ? undefined : buildAmsMapping(filamentComparison)),
  521. [filamentComparison, loadedFilaments.length],
  522. );
  523. const hasTypeMismatch = filamentComparison.some((f) => f.status === 'mismatch');
  524. const hasColorMismatch = filamentComparison.some((f) => f.status === 'type_only');
  525. return {
  526. loadedFilaments,
  527. filamentComparison,
  528. amsMapping,
  529. hasTypeMismatch,
  530. hasColorMismatch,
  531. };
  532. }