microcad_lang/model/attribute/
resolution_attribute.rs

1// Copyright © 2025 The µcad authors <info@ucad.xyz>
2// SPDX-License-Identifier: AGPL-3.0-or-later
3
4//! Resolution attribute.
5
6use microcad_core::Scalar;
7
8use crate::{ty::QuantityType, value::*};
9
10/// Render resolution when rendering things e.g. to polygons or meshes.
11#[derive(Debug, Clone)]
12pub enum ResolutionAttribute {
13    /// Linear resolution in millimeters (Default = 0.1mm)
14    Absolute(Scalar),
15
16    /// Relative resolution.
17    Relative(Scalar),
18}
19
20impl Default for ResolutionAttribute {
21    fn default() -> Self {
22        Self::Absolute(0.1)
23    }
24}
25
26impl From<ResolutionAttribute> for Value {
27    fn from(resolution_attribute: ResolutionAttribute) -> Self {
28        match resolution_attribute {
29            ResolutionAttribute::Absolute(linear) => {
30                Self::Quantity(Quantity::new(linear, QuantityType::Length))
31            }
32            ResolutionAttribute::Relative(relative) => {
33                Self::Quantity(Quantity::new(relative, QuantityType::Scalar))
34            }
35        }
36    }
37}
38
39impl TryFrom<Value> for ResolutionAttribute {
40    type Error = ValueError;
41
42    fn try_from(value: Value) -> Result<Self, Self::Error> {
43        match value {
44            Value::Quantity(Quantity {
45                value,
46                quantity_type: QuantityType::Scalar,
47            }) => Ok(ResolutionAttribute::Relative(value)),
48            Value::Quantity(Quantity {
49                value,
50                quantity_type: QuantityType::Length,
51            }) => Ok(ResolutionAttribute::Absolute(value)),
52            _ => Err(ValueError::CannotConvert(
53                value.to_string(),
54                "ResolutionAttribute".to_string(),
55            )),
56        }
57    }
58}
59
60impl std::fmt::Display for ResolutionAttribute {
61    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
62        match self {
63            ResolutionAttribute::Absolute(linear) => write!(f, "Linear({linear} mm)"),
64            ResolutionAttribute::Relative(relative) => write!(f, "Relative({relative}%)"),
65        }
66    }
67}