use core::future::Future;
use core::ops::ControlFlow;
use core::pin::Pin;
use core::task::{Context, Poll, Waker};
use std::collections::BTreeMap;
use std::sync::{Arc, Mutex, PoisonError};
use printobserver_printer_api::GcodeSink;
use printobserver_types::contract::Sample;
use printobserver_types::schemars::JsonSchema;
use printobserver_types::serde::{Deserialize, Serialize};
use printobserver_types::{PrintId, Timestamp};
use crate::toolpath::{
ExtrusionKind, LayerRef, LayerToolpath, ObjectOutline, Reach, SpoolError, ToolpathSegment,
};
const LINE_LIMIT: usize = 4096;
const TYPE_LIMIT: usize = 64;
const RISE_WINDOW_S: i64 = 30 * 60;
const LAYERS_SHOWN_BELOW: usize = 5;
const FLOW_WELL_UNDER_ONE: f64 = 0.9;
const OVER_AIR: [&str; 2] = ["Bridge infill", "Overhang perimeter"];
const SUPPORTS: [&str; 2] = ["Support material", "Support material interface"];
const WALLS: [&str; 2] = ["Perimeter", "External perimeter"];
const OBJECT_LIMIT: usize = 1024;
const AXIS_LIMIT: f64 = 1e4;
const WORD_LIMIT: f64 = 1e7;
const WORD_COUNT: usize = 8;
const TRAVEL_MM: f64 = 1e-6;
const NOT_THE_PART: &str = "Custom";
const FAN_FULL: f64 = 255.0;
const CHORD_MM: f64 = 0.5;
pub const PLANNED_CHANGE_REACH_BYTES: u64 = 4096;
const CHANGE_LIMIT: usize = 1024;
#[derive(Debug, Clone, Copy, PartialEq)]
struct Head {
at: [f64; 3],
e: f64,
axes: Positioning,
extruder: Positioning,
current_type: Option<usize>,
}
#[derive(Debug, Clone, PartialEq)]
struct Layer {
begins: u64,
at: u64,
head: Head,
z_mm: Option<f64>,
types: u64,
}
#[derive(Debug, Clone, Copy, PartialEq)]
struct Mark<T> {
at: u64,
value: T,
}
#[derive(Debug, Clone, Default, PartialEq)]
struct ObjectDraft {
bounds: Option<[f64; 4]>,
reach: Reach,
}
#[derive(Debug, Clone, PartialEq)]
pub struct GcodeIndex {
bytes: u64,
lines: u64,
layers: Vec<Layer>,
type_names: Vec<String>,
labelled_types: bool,
time_left: Vec<Mark<i64>>,
flow: Vec<Mark<f64>>,
fan: Vec<Mark<f64>>,
objects: Vec<BedArea>,
labelled_objects: bool,
outlines: Vec<ObjectOutline>,
blocks: Vec<(u64, Option<usize>)>,
spool: Option<std::path::PathBuf>,
changes: Vec<ChangeMark>,
change_minutes: Vec<Mark<i64>>,
first_colour: Option<String>,
extruded_mm: f64,
}
#[derive(Debug, Clone, PartialEq)]
struct ChangeMark {
change: PlannedChange,
at: u64,
fed_before_mm: f64,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct SetInFile {
pub value: f64,
pub at: u64,
}
impl GcodeIndex {
#[must_use]
pub const fn bytes(&self) -> u64 {
self.bytes
}
#[must_use]
pub const fn lines(&self) -> u64 {
self.lines
}
#[must_use]
pub const fn layer_count(&self) -> usize {
self.layers.len()
}
#[must_use]
pub const fn entries(&self) -> usize {
self.layers.len()
+ self.time_left.len()
+ self.flow.len()
+ self.fan.len()
+ self.objects.len()
+ self.changes.len()
+ self.change_minutes.len()
}
#[must_use]
pub fn resident_bytes(&self) -> usize {
let names: usize = self.type_names.iter().map(String::capacity).sum();
core::mem::size_of::<Self>()
+ self.layers.capacity() * core::mem::size_of::<Layer>()
+ self.type_names.capacity() * core::mem::size_of::<String>()
+ names
+ self.time_left.capacity() * core::mem::size_of::<Mark<i64>>()
+ self.flow.capacity() * core::mem::size_of::<Mark<f64>>()
+ self.fan.capacity() * core::mem::size_of::<Mark<f64>>()
+ self.objects.capacity() * core::mem::size_of::<BedArea>()
+ self.outlines.capacity() * core::mem::size_of::<ObjectOutline>()
+ self
.outlines
.iter()
.map(|outline| outline.hull_mm.capacity() * core::mem::size_of::<[f32; 2]>())
.sum::<usize>()
+ self.blocks.capacity() * core::mem::size_of::<(u64, Option<usize>)>()
+ self.changes.capacity() * core::mem::size_of::<ChangeMark>()
+ self
.changes
.iter()
.filter_map(|mark| mark.change.color.as_ref())
.map(String::capacity)
.sum::<usize>()
+ self.change_minutes.capacity() * core::mem::size_of::<Mark<i64>>()
+ self.first_colour.as_ref().map_or(0, String::capacity)
}
#[must_use]
pub fn planned_changes(&self) -> Vec<PlannedChange> {
self.changes
.iter()
.map(|mark| mark.change.clone())
.collect()
}
#[must_use]
pub fn planned_change(&self, index: u32) -> Option<&PlannedChange> {
self.changes
.iter()
.map(|mark| &mark.change)
.find(|change| change.index == index)
}
#[must_use]
pub fn planned_segments(&self) -> Vec<PlannedSegment> {
if self.changes.is_empty() {
return Vec::new();
}
let colours = core::iter::once(&self.first_colour)
.chain(self.changes.iter().map(|mark| &mark.change.color));
let fed = core::iter::once(0.0)
.chain(self.changes.iter().map(|mark| mark.fed_before_mm))
.zip(
self.changes
.iter()
.map(|mark| mark.fed_before_mm)
.chain(core::iter::once(self.extruded_mm)),
);
let segments: Vec<PlannedSegment> = (0_u32..)
.zip(colours.zip(fed))
.map(|(segment, (colour, (from, to)))| PlannedSegment {
segment,
color: colour.clone(),
filament_mm: millimetres(to - from),
})
.collect();
segments
}
#[must_use]
pub fn change_waiting_at(&self, file_position_bytes: u64) -> Option<&PlannedChange> {
self.changes
.iter()
.rev()
.map(|mark| &mark.change)
.find(|change| change.offset_bytes <= file_position_bytes)
.filter(|change| waits_at(change, file_position_bytes))
}
fn changes_read(&self, position: i64) -> usize {
u64::try_from(position).map_or(0, |position| {
self.changes.partition_point(|mark| mark.at <= position)
})
}
#[must_use]
pub fn expected_color_at(&self, position: i64) -> Option<String> {
if self.changes.is_empty() {
return None;
}
match self.changes_read(position).checked_sub(1) {
None => self.first_colour.clone(),
Some(last) => self.changes[last].change.color.clone(),
}
}
#[must_use]
pub fn object_outlines(&self) -> &[ObjectOutline] {
&self.outlines
}
#[must_use]
pub fn object_at(&self, file_position_bytes: u64) -> Option<usize> {
if !self.labelled_objects {
return (!self.outlines.is_empty()).then_some(0);
}
let started = self
.blocks
.partition_point(|(start, _)| *start <= file_position_bytes);
self.blocks[..started]
.iter()
.rev()
.find_map(|(_, outline)| *outline)
}
#[must_use]
pub fn layer_at(&self, file_position_bytes: u64) -> Option<LayerRef> {
self.layers
.iter()
.rposition(|layer| layer.at <= file_position_bytes)
.map(LayerRef)
}
#[must_use]
pub fn layer_z_mm(&self, layer: LayerRef) -> Option<f64> {
self.layers.get(layer.0).and_then(|held| held.z_mm)
}
fn lays_object(&self, layer: &Layer) -> bool {
layer.types & !self.type_bits(&SUPPORTS) != 0
}
#[must_use]
pub fn object_layer_at_or_below(&self, layer: LayerRef) -> Option<LayerRef> {
let held = self.layers.get(..=layer.0)?;
held.iter()
.rposition(|layer| self.lays_object(layer))
.map(LayerRef)
}
#[must_use]
pub fn first_object_layer(&self) -> Option<(LayerRef, u64)> {
let first = self
.layers
.iter()
.position(|layer| self.lays_object(layer))?;
Some((LayerRef(first), self.layer_end(first)))
}
fn layer_end(&self, index: usize) -> u64 {
self.layers
.get(index + 1)
.map_or(self.bytes, |next| next.begins)
}
pub fn layer_toolpath(&self, layer: LayerRef) -> Result<LayerToolpath, SpoolError> {
use std::io::{Read as _, Seek as _, SeekFrom};
let held = self.layers.get(layer.0).ok_or(SpoolError::UnknownLayer)?;
let path = self.spool.as_ref().ok_or(SpoolError::NoSpool)?;
let io = |error: std::io::Error| SpoolError::Io {
detail: error.to_string(),
};
let length =
usize::try_from(self.layer_end(layer.0).saturating_sub(held.at)).map_err(|_| {
SpoolError::Io {
detail: "a layer too long to hold".to_owned(),
}
})?;
let mut file = std::fs::File::open(path).map_err(io)?;
file.seek(SeekFrom::Start(held.at)).map_err(io)?;
let mut bytes = vec![0; length];
file.read_exact(&mut bytes).map_err(io)?;
let mut builder = IndexBuilder::reading_layer(self.type_names.clone(), held.head);
let _ = builder.take(&bytes);
if !builder.line.is_empty() {
builder.end_line();
}
#[expect(
clippy::cast_possible_truncation,
reason = "a layer height is a few hundred millimetres at most"
)]
let z_mm = held.z_mm.unwrap_or(0.0) as f32;
Ok(LayerToolpath {
z_mm,
segments: builder.collected.unwrap_or_default(),
})
}
#[must_use]
pub fn busiest_layer(&self) -> Option<(usize, i64)> {
self.layers
.iter()
.map(|layer| {
(
usize::try_from(layer.types.count_ones()).unwrap_or(usize::MAX),
i64::try_from(layer.at).unwrap_or(i64::MAX),
)
})
.reduce(|best, next| if next.0 > best.0 { next } else { best })
}
#[must_use]
pub fn flow_at(&self, position: i64) -> Option<SetInFile> {
last_at(&self.flow, position).map(|mark| SetInFile {
value: mark.value,
at: mark.at,
})
}
#[must_use]
pub fn fan_at(&self, position: i64) -> Option<SetInFile> {
last_at(&self.fan, position).map(|mark| SetInFile {
value: mark.value,
at: mark.at,
})
}
#[must_use]
pub fn plan_at(&self, position: i64) -> SlicerPlan {
self.plan_with(position, None, None)
}
#[must_use]
pub fn plan_with(
&self,
position: i64,
flow_changed: Option<f64>,
fan_changed: Option<f64>,
) -> SlicerPlan {
let mut unknown = Vec::new();
let layer_index = self
.layers
.iter()
.rposition(|layer| reached(layer.at, position));
let final_z_mm = self.layers.last().and_then(|layer| layer.z_mm);
if self.layers.is_empty() {
unknown.push(PlanFact::Layer);
}
if final_z_mm.is_none() {
unknown.push(PlanFact::FinalZ);
}
if !self.labelled_types {
unknown.push(PlanFact::Types);
}
let types = layer_index.map_or_else(Vec::new, |index| {
let bits = self.layers[index].types;
self.type_names
.iter()
.enumerate()
.filter(|(bit, _)| bits & (1 << bit) != 0)
.map(|(_, name)| name.clone())
.collect()
});
let minutes_left = last_at(&self.time_left, position).map(|mark| mark.value);
if minutes_left.is_none() {
unknown.push(PlanFact::MinutesLeft);
}
let flow_factor = set_value(
self.flow_at(position).map(|set| set.value),
flow_changed,
PlanFact::FlowFactor,
&mut unknown,
);
let fan_percent = set_value(
self.fan_at(position).map(|set| set.value),
fan_changed,
PlanFact::FanPercent,
&mut unknown,
);
if !self.labelled_objects {
unknown.push(PlanFact::Objects);
}
unknown.sort_unstable();
let in_force =
|set: &Option<SetValue>| set.as_ref().and_then(|set| set.changed.or(set.file));
let mut at_odds = Vec::new();
if let Some(index) = layer_index {
let shown = self.layers[index.saturating_sub(LAYERS_SHOWN_BELOW)..=index]
.iter()
.fold(0, |bits, layer| bits | layer.types);
if in_force(&fan_percent).is_some_and(|fan| fan <= 0.0)
&& shown & self.type_bits(&OVER_AIR) != 0
{
at_odds.push(PlanMismatch::FanOffOverBridges);
}
if in_force(&flow_factor).is_some_and(|flow| flow < FLOW_WELL_UNDER_ONE)
&& self.layers[index].types & self.type_bits(&WALLS) != 0
{
at_odds.push(PlanMismatch::FlowLowOverWalls);
}
}
let next_change = self
.changes
.get(self.changes_read(position))
.map(|mark| mark.change.clone());
let minutes_to_next_change = next_change
.as_ref()
.and_then(|_| last_at(&self.change_minutes, position))
.map(|mark| mark.value);
SlicerPlan {
expected_color: self.expected_color_at(position),
next_change,
minutes_to_next_change,
change_waiting: None,
layer: layer_index.map(|index| index + 1),
z_mm: layer_index.and_then(|index| self.layers[index].z_mm),
final_z_mm,
types,
minutes_left,
flow_factor,
fan_percent,
object_count: self.labelled_objects.then_some(self.objects.len()),
objects: self.objects.clone(),
rise: None,
at_odds,
unknown,
}
}
fn type_bits(&self, names: &[&str]) -> u64 {
self.type_names
.iter()
.enumerate()
.filter(|(_, name)| names.contains(&name.as_str()))
.fold(0, |bits, (bit, _)| bits | (1 << bit))
}
#[must_use]
pub fn risen_since(&self, earlier: i64, now: i64) -> Option<f64> {
self.height_and_rise_since(earlier, now)
.map(|[_, risen]| risen)
}
#[must_use]
pub fn height_and_rise_since(&self, earlier: i64, now: i64) -> Option<[f64; 2]> {
let at = |position| {
self.layers
.iter()
.rposition(|layer| reached(layer.at, position))
.filter(|index| self.layers[*index].z_mm.is_some())
};
let (then, now) = (at(earlier)?, at(now)?);
let supports = self.type_bits(&SUPPORTS);
let lays_the_part = |layer: &&Layer| layer.types & !supports != 0;
let mut top = self.layers[..=then]
.iter()
.rev()
.filter(lays_the_part)
.find_map(|layer| layer.z_mm)
.or(self.layers[then].z_mm)?;
let height = top;
let mut risen = 0.0;
for layer in self
.layers
.iter()
.take(now + 1)
.skip(then + 1)
.filter(lays_the_part)
{
let Some(z) = layer.z_mm else { continue };
risen += (z - top).max(0.0);
top = top.max(z);
}
let tenth = |mm: f64| (mm * 10.0).round() / 10.0;
Some([tenth(height), tenth(risen)])
}
}
fn set_value(
file: Option<f64>,
changed: Option<f64>,
fact: PlanFact,
unknown: &mut Vec<PlanFact>,
) -> Option<SetValue> {
if file.is_none() {
unknown.push(fact);
}
(file.is_some() || changed.is_some()).then_some(SetValue { file, changed })
}
const fn waits_at(change: &PlannedChange, position: u64) -> bool {
position >= change.offset_bytes && position - change.offset_bytes <= PLANNED_CHANGE_REACH_BYTES
}
fn millimetres(length: f64) -> f64 {
(length.max(0.0) * 1000.0).round() / 1000.0
}
fn reached(at: u64, position: i64) -> bool {
u64::try_from(position).is_ok_and(|position| at <= position)
}
fn last_at<T: Copy>(marks: &[Mark<T>], position: i64) -> Option<Mark<T>> {
let Ok(position) = u64::try_from(position) else {
return None;
};
let reached = marks.partition_point(|mark| mark.at <= position);
reached.checked_sub(1).map(|index| marks[index])
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
#[schemars(crate = "printobserver_types::schemars")]
pub struct SetValue {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub file: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub changed: Option<f64>,
}
pub type BedArea = [i64; 4];
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
#[schemars(crate = "printobserver_types::schemars")]
pub struct Rise {
pub since: Timestamp,
pub mm: [f64; 2],
}
pub(crate) fn null_is_sent(schema: &mut printobserver_types::schemars::Schema) {
use printobserver_types::serde_json::Value;
if let Some(Value::Object(properties)) = schema.get_mut("properties") {
for property in properties.values_mut() {
if property.get("properties").is_some()
&& let Ok(inline) =
printobserver_types::schemars::Schema::try_from(core::mem::take(property))
{
let mut inline = inline;
null_is_sent(&mut inline);
*property = inline.to_value();
}
}
}
let nullable = |property: &Value| match property.get("type") {
Some(Value::Array(types)) => types.iter().any(|named| named == "null"),
_ => property
.get("anyOf")
.and_then(Value::as_array)
.is_some_and(|arms| {
arms.iter()
.any(|arm| arm.get("type") == Some(&Value::from("null")))
}),
};
let sent: Vec<Value> = schema
.get("properties")
.and_then(Value::as_object)
.map(|properties| {
properties
.iter()
.filter(|(_, property)| nullable(property))
.map(|(name, _)| Value::from(name.as_str()))
.collect()
})
.unwrap_or_default();
if sent.is_empty() {
return;
}
let required = schema
.ensure_object()
.entry("required")
.or_insert_with(|| Value::Array(Vec::new()));
if let Value::Array(required) = required {
for name in sent {
if !required.contains(&name) {
required.push(name);
}
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde", rename_all = "snake_case")]
#[schemars(crate = "printobserver_types::schemars")]
pub enum PlannedChangeKind {
ColorChange,
Pause,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
#[schemars(crate = "printobserver_types::schemars", transform = null_is_sent)]
pub struct PlannedChange {
pub index: u32,
pub kind: PlannedChangeKind,
pub offset_bytes: u64,
pub layer: u32,
pub z_mm: f64,
pub color: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
#[schemars(crate = "printobserver_types::schemars", transform = null_is_sent)]
pub struct PlannedSegment {
pub segment: u32,
pub color: Option<String>,
pub filament_mm: f64,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
#[schemars(crate = "printobserver_types::schemars", transform = null_is_sent)]
pub struct PlannedChanges {
pub changes: Vec<PlannedChange>,
pub segments: Vec<PlannedSegment>,
pub waiting: Option<u32>,
pub expected_color: Option<String>,
}
impl Sample for PlannedChange {
fn sample_full() -> Self {
Self {
index: 0,
kind: PlannedChangeKind::ColorChange,
offset_bytes: 48_213,
layer: 12,
z_mm: 2.4,
color: Some("#FF0000".to_owned()),
}
}
fn sample_alternates() -> Vec<Self> {
vec![Self {
index: 1,
kind: PlannedChangeKind::Pause,
offset_bytes: 96_410,
layer: 24,
z_mm: 4.8,
color: None,
}]
}
}
impl Sample for PlannedSegment {
fn sample_full() -> Self {
Self {
segment: 1,
color: Some("#FF0000".to_owned()),
filament_mm: 812.4,
}
}
fn sample_alternates() -> Vec<Self> {
vec![Self {
segment: 0,
color: None,
filament_mm: 0.0,
}]
}
}
impl Sample for PlannedChanges {
fn sample_full() -> Self {
Self {
changes: vec![PlannedChange::sample_full()],
segments: vec![
PlannedSegment {
segment: 0,
color: Some("#FFFFFF".to_owned()),
filament_mm: 301.7,
},
PlannedSegment::sample_full(),
],
waiting: Some(0),
expected_color: Some("#FF0000".to_owned()),
}
}
fn sample_alternates() -> Vec<Self> {
vec![Self {
waiting: None,
expected_color: None,
..Self::sample_full()
}]
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde", rename_all = "snake_case")]
#[schemars(crate = "printobserver_types::schemars")]
pub enum PlanMismatch {
FanOffOverBridges,
FlowLowOverWalls,
}
#[derive(
Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema,
)]
#[serde(crate = "printobserver_types::serde", rename_all = "snake_case")]
#[schemars(crate = "printobserver_types::schemars")]
pub enum PlanFact {
Layer,
FinalZ,
Types,
MinutesLeft,
FlowFactor,
FanPercent,
Objects,
Rise,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
#[schemars(crate = "printobserver_types::schemars")]
pub struct SlicerPlan {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub expected_color: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub next_change: Option<PlannedChange>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub minutes_to_next_change: Option<i64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub change_waiting: Option<PlannedChange>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub layer: Option<usize>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub z_mm: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub final_z_mm: Option<f64>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub types: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub minutes_left: Option<i64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub flow_factor: Option<SetValue>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub fan_percent: Option<SetValue>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub object_count: Option<usize>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub objects: Vec<BedArea>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub rise: Option<Rise>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub at_odds: Vec<PlanMismatch>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub unknown: Vec<PlanFact>,
}
impl Sample for SlicerPlan {
fn sample_full() -> Self {
Self {
expected_color: Some("#FF0000".to_owned()),
next_change: Some(PlannedChange::sample_full()),
minutes_to_next_change: Some(17),
change_waiting: Some(PlannedChange::sample_full()),
layer: Some(12),
z_mm: Some(2.4),
types: vec![
"Perimeter".to_owned(),
"External perimeter".to_owned(),
"Support material".to_owned(),
],
final_z_mm: Some(30.0),
minutes_left: Some(42),
flow_factor: Some(SetValue {
file: Some(1.0),
changed: Some(0.95),
}),
fan_percent: Some(SetValue {
file: Some(100.0),
changed: None,
}),
object_count: Some(1),
objects: vec![[100, 99, 150, 117]],
rise: Some(Rise {
since: Timestamp::sample_full(),
mm: [7.2, 4.8],
}),
at_odds: vec![PlanMismatch::FlowLowOverWalls],
unknown: vec![PlanFact::Objects],
}
}
fn sample_minimal() -> Self {
Self {
expected_color: None,
next_change: None,
minutes_to_next_change: None,
change_waiting: None,
layer: None,
z_mm: None,
final_z_mm: None,
types: Vec::new(),
minutes_left: None,
flow_factor: None,
fan_percent: None,
object_count: None,
objects: Vec::new(),
rise: None,
at_odds: Vec::new(),
unknown: Vec::new(),
}
}
}
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
enum Positioning {
#[default]
Absolute,
Relative,
}
#[derive(Debug, Default)]
pub struct IndexBuilder {
line: Vec<u8>,
overlong: bool,
read: u64,
lines: u64,
layers: Vec<Layer>,
type_names: Vec<String>,
labelled_types: bool,
current_type: Option<usize>,
time_left: Vec<Mark<i64>>,
flow: Vec<Mark<f64>>,
fan: Vec<Mark<f64>>,
objects: Vec<ObjectDraft>,
object_numbers: BTreeMap<i64, usize>,
current_object: Option<usize>,
labelled_objects: bool,
at: [f64; 3],
e: f64,
axes: Positioning,
extruder: Positioning,
line_began: u64,
all: Reach,
blocks: Vec<(u64, usize)>,
spool: Option<Spooling>,
collected: Option<Vec<ToolpathSegment>>,
reached_last: Option<[f64; 2]>,
changes: Vec<ChangeDraft>,
change_minutes: Vec<Mark<i64>>,
colour_comment: Option<(u64, String)>,
first_colour: Option<String>,
extruded_mm: f64,
laid_in_layers: usize,
}
#[derive(Debug, Clone, PartialEq)]
struct ChangeDraft {
kind: PlannedChangeKind,
offset: u64,
at: u64,
layer: usize,
color: Option<String>,
fed_before_mm: f64,
}
#[derive(Debug)]
struct Spooling {
path: std::path::PathBuf,
writer: std::io::BufWriter<std::fs::File>,
failed: bool,
}
impl GcodeSink for IndexBuilder {
fn take(&mut self, piece: &[u8]) -> ControlFlow<()> {
if let Some(spool) = self.spool.as_mut().filter(|spool| !spool.failed) {
use std::io::Write as _;
spool.failed = spool.writer.write_all(piece).is_err();
}
let mut start = 0;
let mut at = 0;
while at < piece.len() {
if piece[at] == b'\n' {
let head = &piece[start..at];
self.read += u64::try_from(at + 1 - start).unwrap_or(u64::MAX);
if self.line.is_empty() && !self.overlong {
self.lines += 1;
if head.len() <= LINE_LIMIT {
self.read_line(head);
}
} else {
self.hold(head);
self.end_line();
}
self.line_began = self.read;
start = at + 1;
}
at += 1;
}
let rest = &piece[start..];
self.hold(rest);
self.read += u64::try_from(rest.len()).unwrap_or(u64::MAX);
ControlFlow::Continue(())
}
}
impl IndexBuilder {
#[must_use]
pub fn new() -> Self {
Self::default()
}
pub fn spooling(path: std::path::PathBuf) -> std::io::Result<Self> {
let file = std::fs::File::create(&path)?;
Ok(Self {
spool: Some(Spooling {
path,
writer: std::io::BufWriter::with_capacity(1 << 16, file),
failed: false,
}),
..Self::default()
})
}
fn reading_layer(type_names: Vec<String>, head: Head) -> Self {
Self {
type_names,
labelled_types: true,
current_type: head.current_type,
at: head.at,
e: head.e,
axes: head.axes,
extruder: head.extruder,
collected: Some(Vec::new()),
..Self::default()
}
}
#[must_use]
pub fn finish(mut self) -> GcodeIndex {
if !self.line.is_empty() || self.overlong {
self.end_line();
}
let mut drafts: Vec<Option<ObjectDraft>> = self.objects.into_iter().map(Some).collect();
let mut objects = Vec::new();
let mut outlines = Vec::new();
let mut outline_of = vec![None; drafts.len()];
for place in self.object_numbers.into_values() {
let Some(draft) = drafts.get_mut(place).and_then(Option::take) else {
continue;
};
let Some([least_x, least_y, most_x, most_y]) = draft.bounds else {
continue;
};
objects.push([
whole(tenth(least_x).floor()),
whole(tenth(least_y).floor()),
whole(tenth(most_x).ceil()),
whole(tenth(most_y).ceil()),
]);
outline_of[place] = Some(outlines.len());
outlines.push(draft.reach.outline().unwrap_or(ObjectOutline {
hull_mm: Vec::new(),
}));
}
if !self.labelled_objects {
outlines.extend(self.all.outline());
}
let blocks = self
.blocks
.into_iter()
.map(|(start, place)| (start, outline_of.get(place).copied().flatten()))
.collect();
let spool = self.spool.and_then(|mut spool| {
use std::io::Write as _;
if spool.failed || spool.writer.flush().is_err() {
drop(spool.writer);
let _ = std::fs::remove_file(&spool.path);
return None;
}
Some(spool.path)
});
let changes = (0_u32..)
.zip(self.changes)
.map(|(index, draft)| {
let layer = draft.layer.min(self.layers.len().saturating_sub(1));
ChangeMark {
change: PlannedChange {
index,
kind: draft.kind,
offset_bytes: draft.offset,
layer: u32::try_from(layer + 1).unwrap_or(u32::MAX),
z_mm: self
.layers
.get(layer)
.and_then(|held| held.z_mm)
.unwrap_or(0.0),
color: draft.color,
},
at: draft.at,
fed_before_mm: draft.fed_before_mm,
}
})
.collect();
GcodeIndex {
bytes: self.read,
lines: self.lines,
changes,
change_minutes: self.change_minutes,
first_colour: self.first_colour,
extruded_mm: self.extruded_mm,
layers: self.layers,
type_names: self.type_names,
labelled_types: self.labelled_types,
time_left: self.time_left,
flow: self.flow,
fan: self.fan,
objects,
labelled_objects: self.labelled_objects,
outlines,
blocks,
spool,
}
}
fn hold(&mut self, bytes: &[u8]) {
if self.overlong {
return;
}
if self.line.len() + bytes.len() > LINE_LIMIT {
self.overlong = true;
self.line.clear();
return;
}
self.line.extend_from_slice(bytes);
}
fn end_line(&mut self) {
self.lines += 1;
let line = core::mem::take(&mut self.line);
if !self.overlong {
self.read_line(&line);
}
self.overlong = false;
self.line = line;
self.line.clear();
}
fn read_line(&mut self, raw: &[u8]) {
let raw = raw.trim_ascii();
if let Some(comment) = raw.strip_prefix(b";") {
if let Ok(comment) = core::str::from_utf8(comment) {
self.comment(comment.trim_end());
}
return;
}
if let [b'G', code @ b'0'..=b'3', b' ', rest @ ..] = raw {
self.motion(u32::from(code - b'0'), &move_of(rest));
return;
}
let held = words(raw);
let mut words = held.as_slice();
if let Some((Word { letter: b'N', .. }, rest)) = words.split_first() {
words = rest;
}
let Some(first) = words.first() else {
return;
};
let code = if held.numbered {
held.second_code
} else {
held.first_code
};
match (char::from(first.letter), code) {
('G', Some(code @ 0..=3)) => self.motion(code, &Move::of(&words[1..])),
('G', Some(28)) => self.home(&words[1..]),
('G', Some(90)) => self.axes = Positioning::Absolute,
('G', Some(91)) => self.axes = Positioning::Relative,
('G', Some(92)) => self.declare(&words[1..]),
('M', Some(82)) => self.extruder = Positioning::Absolute,
('M', Some(83)) => self.extruder = Positioning::Relative,
('M', Some(73)) => self.estimate(&words[1..]),
('M', Some(221)) => self.flow_factor(&words[1..]),
('M', Some(106)) => self.fan_speed(&words[1..], Fan::Set),
('M', Some(107)) => self.fan_speed(&words[1..], Fan::Off),
('M', Some(486)) => self.object(raw, &words[1..]),
('M', Some(600)) => self.planned(PlannedChangeKind::ColorChange),
('M', Some(601)) => self.planned(PlannedChangeKind::Pause),
_ => {}
}
}
fn comment(&mut self, comment: &str) {
if comment == "LAYER_CHANGE" {
self.layers.push(Layer {
begins: self.line_began,
head: Head {
at: self.at,
e: self.e,
axes: self.axes,
extruder: self.extruder,
current_type: self.current_type,
},
at: self.read,
z_mm: None,
types: 0,
});
} else if let Some(z) = comment.strip_prefix("Z:") {
if let Some(layer) = self.layers.last_mut()
&& layer.z_mm.is_none()
{
layer.z_mm = z
.trim()
.parse::<f64>()
.ok()
.filter(|z| (0.0..=AXIS_LIMIT).contains(z));
}
} else if let Some(change) = comment.strip_prefix("COLOR_CHANGE,") {
self.colour_comment = change
.split(',')
.nth(1)
.and_then(colour_of)
.map(|colour| (self.lines, colour));
} else if let Some(colours) = comment.trim_start().strip_prefix("filament_colour = ") {
if self.first_colour.is_none() {
self.first_colour = colours.split(';').next().and_then(colour_of);
}
} else if let Some(name) = comment.strip_prefix("TYPE:") {
let name = name.trim();
self.labelled_types = true;
self.current_type = if name == NOT_THE_PART {
None
} else {
self.intern(name)
};
}
}
fn intern(&mut self, name: &str) -> Option<usize> {
if let Some(bit) = self.type_names.iter().position(|held| held == name) {
return Some(bit);
}
if self.type_names.len() >= TYPE_LIMIT {
return None;
}
self.type_names.push(name.to_owned());
Some(self.type_names.len() - 1)
}
fn motion(&mut self, code: u32, words: &Move) {
let start = self.at;
let relative = self.axes == Positioning::Relative;
if let Some(x) = words.x {
self.place(0, x, relative);
}
if let Some(y) = words.y {
self.place(1, y, relative);
}
if let Some(z) = words.z {
self.place(2, z, relative);
}
let mut fed = 0.0;
if let Some(value) = words.e {
if relative || self.extruder == Positioning::Relative {
self.e += value;
fed = value;
} else {
fed = value - self.e;
self.e = value;
}
}
let travel = (self.at[0] - start[0]).hypot(self.at[1] - start[1]);
self.extruded_mm += fed;
if fed <= 0.0 || (travel <= TRAVEL_MM && code < 2) {
return;
}
self.laid_in_layers = self.layers.len();
if let (Some(layer), Some(bit)) = (self.layers.last_mut(), self.current_type) {
layer.types |= 1 << bit;
}
let end = self.at;
let turn = match code {
2 => Some(Turn::Clockwise),
3 => Some(Turn::CounterClockwise),
_ => None,
};
let arc = turn.and_then(|turn| arc_of(words, turn, start, end));
if let Some(collected) = self.collected.as_mut() {
let kind = self
.current_type
.and_then(|bit| self.type_names.get(bit))
.map_or(ExtrusionKind::Other, |name| ExtrusionKind::of_type(name));
collect_segments(collected, kind, start, end, arc);
return;
}
let part_of_plan = !(self.labelled_types && self.current_type.is_none());
let reach = if let Some(object) = self.current_object {
let draft = &mut self.objects[object];
grow(&mut draft.bounds, start[0], start[1]);
grow(&mut draft.bounds, end[0], end[1]);
if let Some(turn) = turn {
for [x, y] in arc_extremes(words, turn, start, end) {
grow(&mut draft.bounds, x, y);
}
}
&mut draft.reach
} else if !self.labelled_objects && part_of_plan {
&mut self.all
} else {
return;
};
if self.reached_last != Some([start[0], start[1]]) {
reach.point(start[0], start[1]);
}
reach.point(end[0], end[1]);
self.reached_last = Some([end[0], end[1]]);
if let Some(arc) = arc {
reach.arc(arc.centre, arc.radius, arc.base, arc.sweep);
}
}
fn place(&mut self, axis: usize, value: f64, relative: bool) {
let landed = if relative {
self.at[axis] + value
} else {
value
};
if landed.abs() <= AXIS_LIMIT {
self.at[axis] = landed;
}
}
fn home(&mut self, words: &[Word]) {
let named: Vec<usize> = ['X', 'Y', 'Z']
.into_iter()
.enumerate()
.filter(|(_, letter)| words.iter().any(|word| char::from(word.letter) == *letter))
.map(|(axis, _)| axis)
.collect();
if named.is_empty() {
self.at = [0.0; 3];
} else {
for axis in named {
self.at[axis] = 0.0;
}
}
}
fn declare(&mut self, words: &[Word]) {
if words.is_empty() {
self.at = [0.0; 3];
self.e = 0.0;
return;
}
for (axis, letter) in ['X', 'Y', 'Z'].into_iter().enumerate() {
if let Some(value) = number(words, letter).filter(|value| value.abs() <= AXIS_LIMIT) {
self.at[axis] = value;
}
}
if let Some(value) = number(words, 'E') {
self.e = value;
}
}
fn estimate(&mut self, words: &[Word]) {
if let Some(minutes) = number(words, 'C').filter(|minutes| *minutes >= 0.0) {
self.change_minutes.push(Mark {
at: self.read,
value: whole(minutes),
});
}
if number(words, 'P').is_none() {
return;
}
if let Some(minutes) = number(words, 'R').filter(|minutes| *minutes >= 0.0) {
self.time_left.push(Mark {
at: self.read,
value: whole(minutes),
});
}
}
fn planned(&mut self, kind: PlannedChangeKind) {
let named = self.colour_comment.take();
if self.changes.len() >= CHANGE_LIMIT {
return;
}
let color = match kind {
PlannedChangeKind::ColorChange => named
.filter(|(line, _)| line + 1 == self.lines)
.map(|(_, colour)| colour),
PlannedChangeKind::Pause => None,
};
let layer = if self.laid_in_layers == self.layers.len() {
self.layers.len()
} else {
self.layers.len() - 1
};
self.changes.push(ChangeDraft {
kind,
offset: self.line_began,
at: self.read,
layer,
color,
fed_before_mm: self.extruded_mm,
});
}
fn flow_factor(&mut self, words: &[Word]) {
if let Some(percent) = number(words, 'S').filter(|percent| *percent >= 0.0) {
mark_setting(&mut self.flow, self.read, percent / 100.0);
}
}
fn fan_speed(&mut self, words: &[Word], command: Fan) {
if number(words, 'P').is_some_and(|fan| fan != 0.0) {
return;
}
let speed = match command {
Fan::Off => 0.0,
Fan::Set => number(words, 'S').unwrap_or(FAN_FULL),
};
let percent = (speed.clamp(0.0, FAN_FULL) / FAN_FULL * 100.0).round();
mark_setting(&mut self.fan, self.read, percent);
}
fn object(&mut self, raw: &[u8], words: &[Word]) {
if raw
.strip_prefix(b"M486")
.is_some_and(|rest| rest.trim_ascii_start().starts_with(b"A"))
{
self.labelled_objects = true;
return;
}
let Some(number) = number(words, 'S')
.filter(|number| (number - number.round()).abs() < f64::EPSILON && *number >= -1.0)
else {
return;
};
self.labelled_objects = true;
if number < 0.0 {
self.current_object = None;
self.reached_last = None;
return;
}
let id = whole(number);
let place = if let Some(place) = self.object_numbers.get(&id) {
*place
} else if self.objects.len() >= OBJECT_LIMIT {
self.current_object = None;
self.reached_last = None;
return;
} else {
self.objects.push(ObjectDraft::default());
self.object_numbers.insert(id, self.objects.len() - 1);
self.objects.len() - 1
};
self.current_object = Some(place);
self.reached_last = None;
self.blocks.push((self.read, place));
}
}
fn colour_of(text: &str) -> Option<String> {
let text = text.trim();
let hex = text.strip_prefix('#')?;
(hex.len() == 6 && hex.bytes().all(|byte| byte.is_ascii_hexdigit()))
.then(|| text.to_ascii_uppercase())
}
fn mark_setting(marks: &mut Vec<Mark<f64>>, at: u64, value: f64) {
marks.push(Mark { at, value });
}
fn whole(value: f64) -> i64 {
format!("{:.0}", value.round()).parse().unwrap_or_default()
}
fn tenth(value: f64) -> f64 {
(value * 10.0).round() / 10.0
}
fn grow(bounds: &mut Option<[f64; 4]>, x: f64, y: f64) {
*bounds = Some(match *bounds {
None => [x, y, x, y],
Some([least_x, least_y, most_x, most_y]) => {
[least_x.min(x), least_y.min(y), most_x.max(x), most_y.max(y)]
}
});
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Turn {
Clockwise,
CounterClockwise,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Fan {
Set,
Off,
}
fn arc_extremes(
words: &Move,
turn: Turn,
start: [f64; 3],
end: [f64; 3],
) -> impl Iterator<Item = [f64; 2]> {
let reach = arc_of(words, turn, start, end).map(|arc| {
let ArcGeometry {
centre,
radius,
base,
sweep,
..
} = arc;
let tau = core::f64::consts::TAU;
(0..4).filter_map(move |quarter| {
let angle = core::f64::consts::FRAC_PI_2 * f64::from(quarter);
((angle - base).rem_euclid(tau) <= sweep + 1e-9).then(|| {
[
centre[0] + radius * angle.cos(),
centre[1] + radius * angle.sin(),
]
})
})
});
reach.into_iter().flatten()
}
#[derive(Debug, Clone, Copy)]
struct ArcGeometry {
centre: [f64; 2],
radius: f64,
base: f64,
sweep: f64,
turn: Turn,
}
fn arc_of(words: &Move, turn: Turn, start: [f64; 3], end: [f64; 3]) -> Option<ArcGeometry> {
let centre = words.r.map_or_else(
|| {
Some([
start[0] + words.i.unwrap_or(0.0),
start[1] + words.j.unwrap_or(0.0),
])
},
|radius| centre_of_radius(radius, turn, start, end),
)?;
let radius = (start[0] - centre[0]).hypot(start[1] - centre[1]);
let from = (start[1] - centre[1]).atan2(start[0] - centre[0]);
let to = (end[1] - centre[1]).atan2(end[0] - centre[0]);
let tau = core::f64::consts::TAU;
let (base, sweep) = match turn {
Turn::Clockwise => (to, (from - to).rem_euclid(tau)),
Turn::CounterClockwise => (from, (to - from).rem_euclid(tau)),
};
let sweep = if sweep < 1e-9 { tau } else { sweep };
Some(ArcGeometry {
centre,
radius,
base,
sweep,
turn,
})
}
fn collect_segments(
collected: &mut Vec<ToolpathSegment>,
kind: ExtrusionKind,
start: [f64; 3],
end: [f64; 3],
arc: Option<ArcGeometry>,
) {
#[expect(
clippy::cast_possible_truncation,
reason = "bed millimetres are far inside f32's range; a toolpath is drawn, not measured"
)]
let at = |x: f64, y: f64| [x as f32, y as f32];
let Some(arc) = arc else {
collected.push(ToolpathSegment {
from_mm: at(start[0], start[1]),
to_mm: at(end[0], end[1]),
kind,
});
return;
};
let length = arc.sweep * arc.radius;
let chords = (length / CHORD_MM).ceil().clamp(1.0, 4096.0);
let (from, step) = match arc.turn {
Turn::CounterClockwise => (arc.base, arc.sweep / chords),
Turn::Clockwise => (arc.base + arc.sweep, -arc.sweep / chords),
};
let mut previous = at(start[0], start[1]);
let mut k = 1.0;
while k < chords {
let angle = from + step * k;
let next = at(
arc.centre[0] + arc.radius * angle.cos(),
arc.centre[1] + arc.radius * angle.sin(),
);
collected.push(ToolpathSegment {
from_mm: previous,
to_mm: next,
kind,
});
previous = next;
k += 1.0;
}
collected.push(ToolpathSegment {
from_mm: previous,
to_mm: at(end[0], end[1]),
kind,
});
}
fn centre_of_radius(radius: f64, turn: Turn, start: [f64; 3], end: [f64; 3]) -> Option<[f64; 2]> {
let chord = [end[0] - start[0], end[1] - start[1]];
let length = chord[0].hypot(chord[1]);
if length <= TRAVEL_MM || length > 2.0 * radius.abs() {
return None;
}
let rise = (radius * radius - length * length / 4.0).max(0.0).sqrt();
let left = match turn {
Turn::Clockwise => -1.0,
Turn::CounterClockwise => 1.0,
};
let side = left * radius.signum() * rise / length;
Some([
start[0] + chord[0] / 2.0 - chord[1] * side,
start[1] + chord[1] / 2.0 + chord[0] * side,
])
}
fn words(command: &[u8]) -> Words {
let mut found = Words {
held: [Word {
letter: 0,
value: f64::NAN,
}; WORD_COUNT],
len: 0,
first_code: None,
second_code: None,
numbered: false,
};
let length = command.len();
let mut at = 0;
while at < length {
let letter = command[at];
if letter == b';' || letter == b'*' {
break;
}
at += 1;
let upper = match letter {
b'a'..=b'z' => letter - (b'a' - b'A'),
b'A'..=b'Z' => letter,
_ => continue,
};
let start = at;
let (value, next) = number_at(command, at);
at = next;
let text = &command[start..at];
if found.len == 0 {
found.first_code = whole_number(text);
found.numbered = upper == b'N';
} else if found.len == 1 {
found.second_code = whole_number(text);
}
if found.len < WORD_COUNT {
found.held[found.len] = Word {
letter: upper,
value,
};
found.len += 1;
}
}
found
}
fn number_at(line: &[u8], mut at: usize) -> (f64, usize) {
let start = at;
while at < line.len()
&& !matches!(line[at], b' ' | b'\t' | b';' | b'*' | b'A'..=b'Z' | b'a'..=b'z')
{
at += 1;
}
(decimal(&line[start..at]).unwrap_or(f64::NAN), at)
}
#[derive(Debug, Clone, Copy, Default)]
struct Move {
x: Option<f64>,
y: Option<f64>,
z: Option<f64>,
e: Option<f64>,
i: Option<f64>,
j: Option<f64>,
r: Option<f64>,
}
impl Move {
fn of(words: &[Word]) -> Self {
Self {
x: number(words, 'X'),
y: number(words, 'Y'),
z: number(words, 'Z'),
e: number(words, 'E'),
i: number(words, 'I'),
j: number(words, 'J'),
r: number(words, 'R'),
}
}
}
fn move_of(line: &[u8]) -> Move {
let mut found = Move::default();
let length = line.len();
let mut at = 0;
while at < length {
let letter = line[at];
at += 1;
let slot = match letter {
b';' | b'*' => break,
b'X' | b'x' => &mut found.x,
b'Y' | b'y' => &mut found.y,
b'Z' | b'z' => &mut found.z,
b'E' | b'e' => &mut found.e,
b'I' | b'i' => &mut found.i,
b'J' | b'j' => &mut found.j,
b'R' | b'r' => &mut found.r,
b'A'..=b'Z' | b'a'..=b'z' => {
while at < length && !matches!(line[at], b' ' | b'\t' | b';' | b'*') {
at += 1;
}
continue;
}
_ => continue,
};
let (value, next) = number_at(line, at);
at = next;
if slot.is_none() {
*slot = Some(value).filter(|value| value.is_finite() && value.abs() <= WORD_LIMIT);
}
}
found
}
#[derive(Debug, Clone, Copy)]
struct Word {
letter: u8,
value: f64,
}
struct Words {
held: [Word; WORD_COUNT],
len: usize,
first_code: Option<u32>,
second_code: Option<u32>,
numbered: bool,
}
impl Words {
fn as_slice(&self) -> &[Word] {
&self.held[..self.len]
}
}
fn whole_number(text: &[u8]) -> Option<u32> {
let mut value: u32 = 0;
let mut at = 0;
while at < text.len() {
let byte = text[at];
if !byte.is_ascii_digit() {
return None;
}
value = value.checked_mul(10)?.checked_add(u32::from(byte - b'0'))?;
at += 1;
}
(!text.is_empty()).then_some(value)
}
fn decimal(text: &[u8]) -> Option<f64> {
core::str::from_utf8(text).ok()?.parse::<f64>().ok()
}
fn number(words: &[Word], letter: char) -> Option<f64> {
let mut at = 0;
while at < words.len() {
let Word {
letter: word,
value,
} = words[at];
if char::from(word) == letter {
return Some(value).filter(|value| value.is_finite() && value.abs() <= WORD_LIMIT);
}
at += 1;
}
None
}
#[must_use]
pub fn index_of(pieces: &[&[u8]]) -> GcodeIndex {
let mut builder = IndexBuilder::new();
for piece in pieces {
let _ = builder.take(piece);
}
builder.finish()
}
#[derive(Debug, Default)]
enum Slot {
#[default]
Empty,
Building(Vec<Waker>),
Ready(Arc<GcodeIndex>),
}
#[derive(Debug, Default)]
pub struct GcodeIndexes {
slots: Mutex<BTreeMap<PrintId, Slot>>,
looked: Mutex<BTreeMap<PrintId, Vec<(Timestamp, i64)>>>,
}
#[derive(Debug)]
pub enum Claimed<'a> {
Ready(Arc<GcodeIndex>),
Build(BuildClaim<'a>),
}
#[derive(Debug)]
pub struct BuildClaim<'a> {
indexes: &'a GcodeIndexes,
print_id: PrintId,
done: bool,
}
impl BuildClaim<'_> {
#[must_use]
pub fn finish(mut self, index: GcodeIndex) -> Arc<GcodeIndex> {
let index = Arc::new(index);
self.settle(Slot::Ready(Arc::clone(&index)));
self.done = true;
index
}
fn settle(&self, next: Slot) {
let waiting = {
let mut slots = self.indexes.held();
let slot = slots.entry(self.print_id).or_default();
match core::mem::replace(slot, next) {
Slot::Building(waiting) => waiting,
Slot::Empty | Slot::Ready(_) => Vec::new(),
}
};
for waker in waiting {
waker.wake();
}
}
}
impl Drop for BuildClaim<'_> {
fn drop(&mut self) {
if !self.done {
self.settle(Slot::Empty);
}
}
}
impl GcodeIndexes {
fn held(&self) -> std::sync::MutexGuard<'_, BTreeMap<PrintId, Slot>> {
self.slots.lock().unwrap_or_else(PoisonError::into_inner)
}
pub const fn claim(&self, print_id: PrintId) -> Claim<'_> {
Claim {
indexes: self,
print_id,
}
}
#[must_use]
pub fn built(&self, print_id: PrintId) -> Option<Arc<GcodeIndex>> {
match self.held().get(&print_id) {
Some(Slot::Ready(index)) => Some(Arc::clone(index)),
_ => None,
}
}
}
#[derive(Debug)]
pub struct Claim<'a> {
indexes: &'a GcodeIndexes,
print_id: PrintId,
}
impl<'a> Future for Claim<'a> {
type Output = Claimed<'a>;
fn poll(self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<Self::Output> {
let mut slots = self.indexes.held();
let slot = slots.entry(self.print_id).or_default();
match slot {
Slot::Ready(index) => Poll::Ready(Claimed::Ready(Arc::clone(index))),
Slot::Building(waiting) => {
if !waiting.iter().any(|held| held.will_wake(context.waker())) {
waiting.push(context.waker().clone());
}
Poll::Pending
}
Slot::Empty => {
*slot = Slot::Building(Vec::new());
Poll::Ready(Claimed::Build(BuildClaim {
indexes: self.indexes,
print_id: self.print_id,
done: false,
}))
}
}
}
}
const HELD_INDEXES: usize = 16;
impl GcodeIndexes {
pub(crate) fn note_look(
&self,
print_id: PrintId,
captured: Timestamp,
position: i64,
now: Timestamp,
) {
let mut looked = self.looked.lock().unwrap_or_else(PoisonError::into_inner);
let frames = looked.entry(print_id).or_default();
frames.push((captured, position));
frames.sort_by_key(|(captured, _)| *captured);
if let Ok(until) = now.plus_seconds(-RISE_WINDOW_S) {
let aged = frames.partition_point(|(captured, _)| *captured <= until);
frames.drain(..aged.saturating_sub(1));
}
while looked.len() > HELD_INDEXES {
let Some(oldest) = looked.keys().next().copied() else {
break;
};
let _ = looked.remove(&oldest);
}
}
fn newest_look_until(&self, print_id: PrintId, until: Timestamp) -> Option<(Timestamp, i64)> {
let looked = self.looked.lock().unwrap_or_else(PoisonError::into_inner);
looked
.get(&print_id)?
.iter()
.rev()
.find(|(captured, _)| *captured <= until)
.copied()
}
fn trim(&self, keep: PrintId) {
let mut slots = self.held();
let ready: Vec<PrintId> = slots
.iter()
.filter(|(print_id, slot)| **print_id != keep && matches!(slot, Slot::Ready(_)))
.map(|(print_id, _)| *print_id)
.collect();
let over = slots.len().saturating_sub(HELD_INDEXES);
for print_id in ready.into_iter().take(over) {
slots.remove(&print_id);
}
}
}
impl crate::supervisor::Supervisor {
pub(crate) async fn slicer_plan(
&self,
print: &crate::records::PrintRecord,
job: Option<&printobserver_printer_api::JobSnapshot>,
interventions: &[crate::records::Intervention],
) -> Result<Option<SlicerPlan>, crate::error::CoreError> {
let Some((position, file)) = job
.and_then(|job| job.file_position_bytes.zip(job.file_name.as_deref()))
.filter(|(_, file)| {
print.ended_at.is_none() && print.file_name.as_deref() == Some(*file)
})
else {
return Ok(None);
};
let Some(index) = self.index_of(print.id, file).await else {
return Ok(None);
};
let (flow, fan) = self
.changes_since(print.id, &index, position, interventions)
.await?;
let mut plan = index.plan_with(position, flow, fan);
plan.change_waiting = self
.planned_change_waiting(print.id)
.await?
.map(|waiting| waiting.reached.change);
plan.rise = self.rise_of(print.id, &index, position).await?;
if plan.rise.is_none() {
plan.unknown.push(PlanFact::Rise);
plan.unknown.sort_unstable();
}
Ok(Some(plan))
}
async fn rise_of(
&self,
print_id: PrintId,
index: &GcodeIndex,
position: i64,
) -> Result<Option<Rise>, crate::error::CoreError> {
use printobserver_types::EventPayload as _;
use crate::kinds::PeriodicObservationPayload;
let now = self.clock().now();
let Ok(until) = now.plus_seconds(-RISE_WINDOW_S) else {
return Ok(None);
};
let events = self
.stores()
.events
.history(crate::store::HistoryQuery {
print_id,
kinds: printobserver_types::EventKind::new(PeriodicObservationPayload::KIND)
.into_iter()
.collect(),
since: None,
until: Some(until),
limit: Some(1),
})
.await?;
let observed = events.first().and_then(|event| {
let observed = event.payload_as::<PeriodicObservationPayload>()?.ok()?;
let earlier = observed.job?.file_position_bytes?;
Some((
observed.frame_captured_at.unwrap_or(event.received_at),
earlier,
))
});
let looked = self.gcode_indexes().newest_look_until(print_id, until);
let newest = match (observed, looked) {
(Some(observed), Some(looked)) => Some(if looked.0 > observed.0 {
looked
} else {
observed
}),
(observed, looked) => observed.or(looked),
};
Ok(newest.and_then(|(since, earlier)| {
Some(Rise {
since,
mm: index.height_and_rise_since(earlier, position)?,
})
}))
}
pub async fn print_gcode_index(&self, print_id: PrintId) -> Option<Arc<GcodeIndex>> {
let print = self.stores().prints.print(print_id).await.ok()??;
if print.ended_at.is_some() {
return None;
}
self.index_of(print.id, print.file_name.as_deref()?).await
}
pub(crate) fn drop_gcode_spool(&self, print_id: PrintId) {
if let Some(directory) = self.config().gcode_spool_dir.as_deref() {
let _ = std::fs::remove_file(crate::toolpath::spool_path(directory, print_id));
}
}
pub async fn sweep_gcode_spools(&self) -> Result<(), crate::error::CoreError> {
let Some(directory) = self.config().gcode_spool_dir.clone() else {
return Ok(());
};
let open: Vec<String> = self
.stores()
.prints
.open_prints()
.await?
.iter()
.map(|print| print.id.to_string())
.collect();
let Ok(entries) = std::fs::read_dir(&directory) else {
return Ok(());
};
for entry in entries.flatten() {
let name = entry.file_name();
let Some(print) = name
.to_str()
.and_then(|name| name.strip_suffix(crate::toolpath::SPOOL_SUFFIX))
.filter(|print| print.parse::<PrintId>().is_ok())
else {
continue;
};
if !open.iter().any(|id| id == print) {
let _ = std::fs::remove_file(entry.path());
}
}
Ok(())
}
async fn index_of(&self, print_id: PrintId, file: &str) -> Option<Arc<GcodeIndex>> {
let file_name = printobserver_types::FileName::new(file).ok()?;
let claim = match self.gcode_indexes().claim(print_id).await {
Claimed::Ready(index) => return Some(index),
Claimed::Build(claim) => claim,
};
let mut builder = self
.config()
.gcode_spool_dir
.as_deref()
.and_then(|directory| {
IndexBuilder::spooling(crate::toolpath::spool_path(directory, print_id)).ok()
})
.unwrap_or_default();
self.read_gcode(file_name.clone(), &mut builder)
.await
.ok()?;
let index = claim.finish(builder.finish());
self.gcode_indexes().trim(print_id);
if let Ok(body) = printobserver_types::EventBody::of(&crate::kinds::GcodeIndexedPayload {
file_name,
bytes: index.bytes(),
layers: u64::try_from(index.layer_count()).unwrap_or(u64::MAX),
}) {
let _ = self.append_system_event(print_id, body).await;
}
Some(index)
}
async fn changes_since(
&self,
print_id: PrintId,
index: &GcodeIndex,
position: i64,
interventions: &[crate::records::Intervention],
) -> Result<(Option<f64>, Option<f64>), crate::error::CoreError> {
use printobserver_types::EventPayload as _;
use crate::kinds::{ActionExecutedPayload, ActionRequestedPayload};
use crate::records::PrintAction;
let kinds = [ActionRequestedPayload::KIND, ActionExecutedPayload::KIND]
.iter()
.filter_map(|kind| printobserver_types::EventKind::new(*kind).ok())
.collect();
let events = self
.stores()
.events
.history(crate::store::HistoryQuery {
print_id,
kinds,
since: None,
until: None,
limit: Some(crate::store::MAX_HISTORY_LIMIT),
})
.await?;
let requested: BTreeMap<crate::records::ActionId, PrintAction> = events
.iter()
.filter_map(printobserver_types::EventRecord::payload_as::<ActionRequestedPayload>)
.filter_map(Result::ok)
.map(|payload| (payload.action_id, payload.action))
.collect();
let mut flow = None;
let mut fan = None;
for executed in events
.iter()
.filter_map(printobserver_types::EventRecord::payload_as::<ActionExecutedPayload>)
.filter_map(Result::ok)
{
let standing = executed
.intervention_id
.is_none_or(|opened| interventions.iter().any(|active| active.id == opened));
let made = executed
.file_position_bytes
.and_then(|made| u64::try_from(made).ok())
.unwrap_or(0);
let after = |set: Option<SetInFile>| set.is_none_or(|set| made >= set.at);
match requested.get(&executed.action_id) {
Some(PrintAction::SetFlowrateFactor { factor, .. }) if flow.is_none() => {
flow = Some((standing && after(index.flow_at(position))).then_some(*factor));
}
Some(PrintAction::SetFanPercent { percent, .. }) if fan.is_none() => {
fan = Some((standing && after(index.fan_at(position))).then_some(*percent));
}
_ => {}
}
}
Ok((flow.flatten(), fan.flatten()))
}
}
#[cfg(test)]
mod tests {
use super::{GcodeIndexes, HELD_INDEXES, OVER_AIR, RISE_WINDOW_S, SUPPORTS, WALLS};
use crate::toolpath::ExtrusionKind;
#[test]
fn the_plans_type_names_map_to_the_kinds_the_toolpath_draws() {
for name in WALLS {
assert_eq!(ExtrusionKind::of_type(name), ExtrusionKind::Wall, "{name}");
}
for name in SUPPORTS {
assert_eq!(
ExtrusionKind::of_type(name),
ExtrusionKind::Support,
"{name}"
);
}
for name in OVER_AIR {
assert!(
matches!(
ExtrusionKind::of_type(name),
ExtrusionKind::Bridge | ExtrusionKind::Overhang
),
"{name}"
);
}
}
use printobserver_types::{PrintId, Timestamp};
fn after(start: Timestamp, seconds: i64) -> Timestamp {
start.plus_seconds(seconds).expect("an instant")
}
fn held(indexes: &GcodeIndexes, print_id: PrintId) -> Vec<(Timestamp, i64)> {
indexes
.looked
.lock()
.expect("the looks are held")
.get(&print_id)
.cloned()
.unwrap_or_default()
}
#[test]
fn the_newest_aged_look_is_kept_and_every_older_one_let_go() {
let indexes = GcodeIndexes::default();
let print = PrintId::new();
let start = Timestamp::now();
indexes.note_look(print, start, 10, start);
indexes.note_look(print, after(start, 60), 20, after(start, 60));
let now = after(start, 60 + RISE_WINDOW_S + 30);
indexes.note_look(print, now, 30, now);
assert_eq!(
held(&indexes, print),
vec![(after(start, 60), 20), (now, 30)]
);
assert_eq!(
indexes.newest_look_until(print, after(now, -RISE_WINDOW_S)),
Some((after(start, 60), 20))
);
assert_eq!(indexes.newest_look_until(print, after(start, 30)), None);
}
#[test]
fn the_looks_of_prints_beyond_the_held_count_are_let_go_oldest_first() {
let indexes = GcodeIndexes::default();
let now = Timestamp::now();
let mut prints: Vec<PrintId> = (0..=HELD_INDEXES).map(|_| PrintId::new()).collect();
prints.sort_unstable();
for print in &prints {
indexes.note_look(*print, now, 1, now);
}
assert!(held(&indexes, prints[0]).is_empty());
for print in &prints[1..] {
assert_eq!(held(&indexes, *print), vec![(now, 1)]);
}
}
}