units.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. # Created: 2019-01-05
  2. # Copyright (c) 2019 Manfred Moitzi
  3. # License: MIT License
  4. MSP_METRIC_UNITS_FACTORS = {
  5. 'km': .001,
  6. 'm': 1.0,
  7. 'dm': 10.,
  8. 'cm': 100.,
  9. 'mm': 1000.,
  10. 'µm': 1000000.,
  11. 'yd': 1.093613298,
  12. 'ft': 3.280839895,
  13. 'in': 39.37007874,
  14. 'mi': 0.00062137119,
  15. }
  16. class DrawingUnits:
  17. def __init__(self, base: float = 1., unit: str = 'm'):
  18. self.base = float(base)
  19. self.unit = unit.lower()
  20. self._units = MSP_METRIC_UNITS_FACTORS
  21. self._msp_factor = base * self._units[self.unit]
  22. def factor(self, unit: str = 'm') -> float:
  23. return self._msp_factor / self._units[unit.lower()]
  24. def __call__(self, unit: str) -> float:
  25. return self.factor(unit)
  26. class PaperSpaceUnits:
  27. def __init__(self, msp=DrawingUnits(), unit: str = 'mm', scale: float = 1):
  28. self.unit = unit.lower()
  29. self.scale = scale
  30. self._msp = msp
  31. self._psp = DrawingUnits(1, self.unit)
  32. def from_msp(self, value: float, unit: str):
  33. drawing_units = value * self._msp(unit.lower())
  34. return drawing_units / (self._msp(self.unit) * self.scale)
  35. def to_msp(self, value: float, unit: str):
  36. paper_space_units = value * self.scale * self._psp.factor(unit)
  37. model_space_units = paper_space_units * self._msp.factor(self.unit)
  38. return model_space_units