libprintcalc 0.2.0

Library for calculating 3D print job costs (material, print time, printer wear, electricity, labor, hardware) from sliced-file output.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
//! `SliceSummary`: the common shape extracted from any supported slicer
//! output.
//!
//! Two halves, with very different obligations.
//!
//! The **usage** half — plates, print times, and per-slot grams or
//! millilitres — is what costing consumes, and every parser must produce
//! it.
//!
//! The **metadata** half — [`SliceMeta`] and the profile names, vendors,
//! prices and colours on each [`FilamentUsage`] — is entirely optional
//! and feeds [`crate::matching`]. A format that records less still costs
//! correctly; it just asks the user more questions.

use std::collections::HashMap;

use serde::{Deserialize, Serialize};

/// Which slicer/format a [`SliceSummary`] was extracted from.
///
/// `#[non_exhaustive]`: more formats land over time, and each is a new
/// variant here.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum SourceFormat {
    /// Bambu Studio `.gcode.3mf`.
    #[serde(rename = "bambu-3mf")]
    Bambu3mf,
    /// Plain-text `.gcode` with PrusaSlicer-style metadata comments (most
    /// FDM slicers). Deserialize alias keeps job files written with the old
    /// `prusa-gcode` name loading.
    #[serde(rename = "gcode", alias = "prusa-gcode")]
    Gcode,
    /// PrusaSlicer binary `.bgcode`.
    #[serde(rename = "prusa-bgcode")]
    PrusaBgcode,
    /// PrusaSlicer resin `.sl1`/`.sl1s`.
    #[serde(rename = "prusa-sl1")]
    PrusaSl1,
}

/// File-wide identity a slicer recorded about the setup that produced a
/// sliced file: which printer profile, which print profile, which nozzle,
/// which slicer build. None of it is needed to *cost* a job — it's what
/// [`crate::matching`] uses to guess printer/material profiles so the
/// caller doesn't have to name them by hand.
///
/// Everything is optional and best-effort: a format that doesn't report a
/// field just leaves it `None`.
///
/// `#[non_exhaustive]`: start from [`SliceMeta::default`] and chain the
/// `with_*` setters. Fields stay public to read and assign.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(default)]
#[non_exhaustive]
pub struct SliceMeta {
    /// The slicer's own printer *profile* name, e.g. `"Prusa MINI 0.4
    /// nozzle"` or `"Bambu Lab P2S 0.4 nozzle"` — more specific than
    /// [`PlateSummary::printer_model`], which is just the machine.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub printer_profile: Option<String>,
    /// The slicer's print/quality profile, e.g. `"0.20mm Standard @MINI"`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub print_profile: Option<String>,
    /// Printer variant as the slicer labels it, usually the nozzle
    /// (`"0.4"`, `"HF0.4"`, `"default"`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub printer_variant: Option<String>,
    /// Nozzle diameter in mm.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub nozzle_diameter: Option<f64>,
    /// Which slicer wrote the file, with its version if reported, e.g.
    /// `"PrusaSlicer-2.9.6+flathub.org"` or `"BambuStudio 02.07.01.62"`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub slicer: Option<String>,
}

impl SliceMeta {
    /// Sets the slicer's printer profile name.
    pub fn with_printer_profile(mut self, value: impl Into<String>) -> Self {
        self.printer_profile = Some(value.into());
        self
    }

    /// Sets the slicer's print/quality profile name.
    pub fn with_print_profile(mut self, value: impl Into<String>) -> Self {
        self.print_profile = Some(value.into());
        self
    }

    /// Sets the printer variant label.
    pub fn with_printer_variant(mut self, value: impl Into<String>) -> Self {
        self.printer_variant = Some(value.into());
        self
    }

    /// Sets the nozzle diameter in mm.
    pub fn with_nozzle_diameter(mut self, value: f64) -> Self {
        self.nozzle_diameter = Some(value);
        self
    }

    /// Sets which slicer wrote the file.
    pub fn with_slicer(mut self, value: impl Into<String>) -> Self {
        self.slicer = Some(value.into());
        self
    }

    /// Whether every field is unset — the "format reported nothing" case,
    /// skipped entirely when serializing.
    pub fn is_empty(&self) -> bool {
        *self == SliceMeta::default()
    }
}

/// The common shape every format parser ([`crate::formats::SliceParser`])
/// extracts from a sliced file — print time and material usage, per plate,
/// plus whatever identifying [`SliceMeta`] the format carried.
///
/// `#[non_exhaustive]`: normally the output of a parser; build one by
/// hand with [`SliceSummary::new`]. Fields stay public to read and assign.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct SliceSummary {
    /// Which parser produced this summary.
    pub source_format: SourceFormat,
    /// File-wide slicer/printer identity, for profile auto-matching. Older
    /// job files predate this field, so it defaults to empty.
    #[serde(default, skip_serializing_if = "SliceMeta::is_empty")]
    pub meta: SliceMeta,
    /// Always at least one entry — single-plate formats (Prusa gcode/
    /// bgcode/sl1/sl1s) produce exactly one.
    pub plates: Vec<PlateSummary>,
}

impl SliceSummary {
    /// A summary with empty [`SliceMeta`]. `plates` should have at least
    /// one entry.
    pub fn new(source_format: SourceFormat, plates: Vec<PlateSummary>) -> Self {
        SliceSummary {
            source_format,
            meta: SliceMeta::default(),
            plates,
        }
    }

    /// Sets the file-wide slicer/printer identity.
    pub fn with_meta(mut self, meta: SliceMeta) -> Self {
        self.meta = meta;
        self
    }

    /// Every distinct `FilamentUsage::slot_id` with nonzero usage on any
    /// plate, sorted. Used to decide whether a job needs one filament
    /// (`--filament`) or a per-slot map (`--filament-map`) — and, for the
    /// single-slot case, which slot_id that one filament actually belongs
    /// to. That's not always `"1"`: Bambu single-tray and Prusa's
    /// scalar single-extruder case both normalize to `"1"`, but a
    /// multi-extruder-*capable* printer's comma-list metadata numbers
    /// slots from `0` even when only one ends up used.
    pub fn distinct_filament_slots(&self) -> Vec<String> {
        self.slots().into_iter().map(|s| s.slot_id).collect()
    }

    /// One [`SlotUsage`] per slot with nonzero usage anywhere in the file,
    /// sorted by slot id — each slot's total usage plus whatever the
    /// slicer said about the filament loaded in it.
    ///
    /// This is the "everything the file knows about slot N" view:
    /// [`crate::matching`] guesses a material profile from it, the CLI
    /// prints it, and [`crate::model::cost::CalcError::MissingMaterial`]
    /// names the unmapped ones with their type and color rather than a
    /// bare slot number.
    pub fn slots(&self) -> Vec<SlotUsage> {
        let mut slots: Vec<SlotUsage> = Vec::new();
        for usage in self.plates.iter().flat_map(|p| &p.filament_usage) {
            if usage.grams.unwrap_or(0.0) == 0.0 && usage.ml.unwrap_or(0.0) == 0.0 {
                continue; // tray/extruder present but not used on this print
            }
            match slots.iter_mut().find(|s| s.slot_id == usage.slot_id) {
                Some(slot) => slot.add(usage),
                None => slots.push(SlotUsage::from_usage(usage)),
            }
        }
        slots.sort_by(|a, b| a.slot_id.cmp(&b.slot_id));
        slots
    }

    /// The printer the slicer targeted, as reported by the first plate
    /// that names one — every format that reports it at all reports the
    /// same value for every plate.
    pub fn printer_model(&self) -> Option<&str> {
        self.plates.iter().find_map(|p| p.printer_model.as_deref())
    }

    /// The first plate's layer height, same rule as [`Self::printer_model`].
    pub fn layer_height(&self) -> Option<f64> {
        self.plates.iter().find_map(|p| p.layer_height)
    }

    /// Total print time across every plate, in seconds.
    pub fn total_print_time_seconds(&self) -> f64 {
        self.plates.iter().map(|p| p.print_time_seconds).sum()
    }
}

/// One plate's worth of a sliced file — print time and every filament slot
/// with nonzero usage on it.
///
/// `#[non_exhaustive]`: build one with [`PlateSummary::new`]. Fields stay
/// public to read and assign.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct PlateSummary {
    /// 1-based, matches the slicer's own plate numbering.
    pub plate_index: u32,
    /// How long this plate took (or was predicted) to print.
    pub print_time_seconds: f64,
    /// One entry per slot/tray/extruder that deposited material on this
    /// plate — a plain single-material print still has exactly one.
    pub filament_usage: Vec<FilamentUsage>,
    /// The printer model the slicer targeted, if the format reports one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub printer_model: Option<String>,
    /// Layer height in mm, if the format reports one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub layer_height: Option<f64>,
    /// Anything format-specific worth keeping that doesn't have a home in
    /// the fields above.
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub extra: HashMap<String, String>,
}

impl PlateSummary {
    /// A plate with no printer model, layer height or extras.
    pub fn new(
        plate_index: u32,
        print_time_seconds: f64,
        filament_usage: Vec<FilamentUsage>,
    ) -> Self {
        PlateSummary {
            plate_index,
            print_time_seconds,
            filament_usage,
            printer_model: None,
            layer_height: None,
            extra: HashMap::new(),
        }
    }

    /// Sets the printer model the slicer targeted.
    pub fn with_printer_model(mut self, value: impl Into<String>) -> Self {
        self.printer_model = Some(value.into());
        self
    }

    /// Sets the layer height in mm.
    pub fn with_layer_height(mut self, value: f64) -> Self {
        self.layer_height = Some(value);
        self
    }

    /// Sets the format-specific extras.
    pub fn with_extra(mut self, extra: HashMap<String, String>) -> Self {
        self.extra = extra;
        self
    }
}

/// One filament/resin slot's usage on a plate — a Bambu AMS tray, a
/// multi-extruder Prusa slot, or the sole slot of a single-material print.
///
/// Beyond the amount used, every field here is the slicer's own
/// description of what was loaded in the slot. It's all optional: a format
/// that doesn't report a field leaves it `None`, and nothing in the cost
/// calc depends on any of it — it exists so a job can be built without the
/// caller retyping what the file already says.
///
/// `#[non_exhaustive]`: build one with [`FilamentUsage::grams`] or
/// [`FilamentUsage::ml`] and the `with_*` setters. Fields stay public to
/// read and assign.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct FilamentUsage {
    /// Opaque, format-native slot id — whatever the slicer itself uses to
    /// distinguish slots (AMS tray `id`, Prusa extruder index, ...).
    pub slot_id: String,
    /// Free-form material name/description as the slicer reports it,
    /// usually the family (`"PLA"`, `"PETG"`); for resin, the full
    /// material name.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub material_type: Option<String>,
    /// Free-form display color, e.g. a hex code.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub color: Option<String>,
    /// The slicer's own filament/resin *profile* name, e.g. `"Generic PLA
    /// @System"`, `"Bambu PLA Basic @BBL P2S"`, or an SLA material name.
    /// The strongest hint there is for matching a stored profile.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub profile_name: Option<String>,
    /// Manufacturer as the slicer reports it, e.g. `"Bambu Lab"`,
    /// `"Prusa Polymers"`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub vendor: Option<String>,
    /// The price the slicer's own filament profile carries — per kg for
    /// filament, per liter for resin, matching
    /// [`crate::MaterialProfile::price`]. Lets a job be costed off the
    /// file alone when no stored profile matches.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub price: Option<f64>,
    /// Material density in g/cm³, if reported.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub density: Option<f64>,
    /// Length of filament used, in meters, if reported. Informational —
    /// costing goes by `grams`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub meters: Option<f64>,
    /// Set for filament (weight-measured) usage; `None` for resin.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub grams: Option<f64>,
    /// Set for resin (volume-measured) usage; `None` for filament.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ml: Option<f64>,
}

impl FilamentUsage {
    /// Filament usage: `grams` deposited from `slot_id`.
    pub fn grams(slot_id: impl Into<String>, grams: f64) -> Self {
        FilamentUsage {
            slot_id: slot_id.into(),
            grams: Some(grams),
            ..Default::default()
        }
    }

    /// Resin usage: `ml` consumed from `slot_id`.
    pub fn ml(slot_id: impl Into<String>, ml: f64) -> Self {
        FilamentUsage {
            slot_id: slot_id.into(),
            ml: Some(ml),
            ..Default::default()
        }
    }

    /// Sets the material family as the slicer reports it.
    pub fn with_material_type(mut self, value: impl Into<String>) -> Self {
        self.material_type = Some(value.into());
        self
    }

    /// Sets the display color.
    pub fn with_color(mut self, value: impl Into<String>) -> Self {
        self.color = Some(value.into());
        self
    }

    /// Sets the slicer's filament/resin profile name.
    pub fn with_profile_name(mut self, value: impl Into<String>) -> Self {
        self.profile_name = Some(value.into());
        self
    }

    /// Sets the manufacturer as the slicer reports it.
    pub fn with_vendor(mut self, value: impl Into<String>) -> Self {
        self.vendor = Some(value.into());
        self
    }

    /// Sets the price the slicer's own profile carries.
    pub fn with_price(mut self, value: f64) -> Self {
        self.price = Some(value);
        self
    }

    /// Sets the material density in g/cm³.
    pub fn with_density(mut self, value: f64) -> Self {
        self.density = Some(value);
        self
    }

    /// Sets the length of filament used, in meters.
    pub fn with_meters(mut self, value: f64) -> Self {
        self.meters = Some(value);
        self
    }
}

/// One slot's totals across every plate, plus the slicer's description of
/// the filament in it. Built by [`SliceSummary::slots`].
///
/// `#[non_exhaustive]`: read-only output of the library.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct SlotUsage {
    /// The slot's format-native id, as in [`FilamentUsage::slot_id`].
    pub slot_id: String,
    /// First non-empty [`FilamentUsage::material_type`] seen for the slot.
    pub material_type: Option<String>,
    /// First non-empty [`FilamentUsage::color`] seen for the slot.
    pub color: Option<String>,
    /// First non-empty [`FilamentUsage::profile_name`] seen for the slot.
    pub profile_name: Option<String>,
    /// First non-empty [`FilamentUsage::vendor`] seen for the slot.
    pub vendor: Option<String>,
    /// First [`FilamentUsage::price`] seen for the slot.
    pub price: Option<f64>,
    /// Total grams across every plate (`0.0` for resin).
    pub grams: f64,
    /// Total ml across every plate (`0.0` for filament).
    pub ml: f64,
}

impl SlotUsage {
    fn from_usage(usage: &FilamentUsage) -> Self {
        SlotUsage {
            slot_id: usage.slot_id.clone(),
            material_type: nonempty(usage.material_type.as_deref()),
            color: nonempty(usage.color.as_deref()),
            profile_name: nonempty(usage.profile_name.as_deref()),
            vendor: nonempty(usage.vendor.as_deref()),
            price: usage.price,
            grams: usage.grams.unwrap_or(0.0),
            ml: usage.ml.unwrap_or(0.0),
        }
    }

    fn add(&mut self, usage: &FilamentUsage) {
        self.grams += usage.grams.unwrap_or(0.0);
        self.ml += usage.ml.unwrap_or(0.0);
        // First plate to describe the slot wins; later plates only fill
        // in what it left blank.
        fill(&mut self.material_type, usage.material_type.as_deref());
        fill(&mut self.color, usage.color.as_deref());
        fill(&mut self.profile_name, usage.profile_name.as_deref());
        fill(&mut self.vendor, usage.vendor.as_deref());
        if self.price.is_none() {
            self.price = usage.price;
        }
    }

    /// A short human label for the slot, as used in error messages and
    /// CLI output: `"slot 1 (PLA #AE6342)"`, degrading to just
    /// `"slot 1"` when the file said nothing about it.
    pub fn label(&self) -> String {
        let mut parts: Vec<&str> = Vec::new();
        if let Some(name) = self.profile_name.as_deref().filter(|s| !s.is_empty()) {
            parts.push(name);
        } else if let Some(kind) = self.material_type.as_deref().filter(|s| !s.is_empty()) {
            parts.push(kind);
        }
        if let Some(color) = self.color.as_deref().filter(|s| !s.is_empty()) {
            parts.push(color);
        }
        if parts.is_empty() {
            format!("slot {}", self.slot_id)
        } else {
            format!("slot {} ({})", self.slot_id, parts.join(" "))
        }
    }
}

fn nonempty(value: Option<&str>) -> Option<String> {
    value.filter(|s| !s.is_empty()).map(String::from)
}

/// Sets `target` from `value` only if it's still unset and `value` is
/// something — so a later plate that says nothing can't overwrite an
/// earlier plate's description with a blank.
fn fill(target: &mut Option<String>, value: Option<&str>) {
    if target.is_none() {
        *target = nonempty(value);
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn usage(slot_id: &str, grams: f64) -> FilamentUsage {
        FilamentUsage {
            slot_id: slot_id.into(),
            grams: Some(grams),
            ..FilamentUsage::default()
        }
    }

    fn plate(index: u32, usage: Vec<FilamentUsage>) -> PlateSummary {
        PlateSummary {
            plate_index: index,
            print_time_seconds: 100.0,
            filament_usage: usage,
            printer_model: None,
            layer_height: None,
            extra: HashMap::new(),
        }
    }

    #[test]
    fn distinct_filament_slots_dedupes_sorts_and_skips_zero_usage() {
        let summary = SliceSummary {
            source_format: SourceFormat::Bambu3mf,
            meta: SliceMeta::default(),
            plates: vec![
                plate(1, vec![usage("2", 1.0), usage("1", 2.0), usage("3", 0.0)]),
                plate(2, vec![usage("1", 1.0)]),
            ],
        };
        assert_eq!(
            summary.distinct_filament_slots(),
            vec!["1".to_string(), "2".to_string()]
        );
    }

    /// `slots()` totals a slot's usage across plates and keeps the first
    /// description the file gave it.
    #[test]
    fn slots_aggregate_usage_and_carry_slicer_metadata() {
        let described = FilamentUsage {
            slot_id: "1".into(),
            material_type: Some("PLA".into()),
            color: Some("#AE6342".into()),
            profile_name: Some("Bambu PLA Basic @BBL P2S".into()),
            vendor: Some("Bambu Lab".into()),
            price: Some(24.99),
            grams: Some(4.0),
            ..FilamentUsage::default()
        };
        let summary = SliceSummary {
            source_format: SourceFormat::Bambu3mf,
            meta: SliceMeta::default(),
            plates: vec![plate(1, vec![described]), plate(2, vec![usage("1", 2.5)])],
        };

        let slots = summary.slots();
        assert_eq!(slots.len(), 1);
        assert_eq!(slots[0].grams, 6.5);
        assert_eq!(slots[0].price, Some(24.99));
        assert_eq!(
            slots[0].profile_name.as_deref(),
            Some("Bambu PLA Basic @BBL P2S")
        );
        assert_eq!(
            slots[0].label(),
            "slot 1 (Bambu PLA Basic @BBL P2S #AE6342)"
        );
    }

    /// A slot the file said nothing about still gets a usable label.
    #[test]
    fn bare_slot_label_is_just_the_slot_id() {
        let summary = SliceSummary {
            source_format: SourceFormat::Gcode,
            meta: SliceMeta::default(),
            plates: vec![plate(1, vec![usage("0", 1.0)])],
        };
        assert_eq!(summary.slots()[0].label(), "slot 0");
    }

    /// An all-`None` `SliceMeta` serializes away entirely, so summaries
    /// from formats that report nothing look exactly as they did before.
    #[test]
    fn empty_meta_is_skipped_when_serializing() {
        let summary = SliceSummary {
            source_format: SourceFormat::Gcode,
            meta: SliceMeta::default(),
            plates: vec![plate(1, vec![usage("1", 1.0)])],
        };
        let text = toml::to_string(&summary).unwrap();
        assert!(!text.contains("meta"));
        assert_eq!(toml::from_str::<SliceSummary>(&text).unwrap(), summary);
    }
}