rectangle.rs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. use std::fmt::{Debug, Display};
  2. use binrw::{BinRead, BinWrite};
  3. use diff::Diff;
  4. use log::warn;
  5. use crate::{
  6. field_of::FieldOf,
  7. types::{Coordinate, ObjectType, F64},
  8. };
  9. use super::{ObjectCore, ObjectModifier, Translate};
  10. #[derive(BinRead, BinWrite, Clone, Debug, Diff, PartialEq)]
  11. #[diff(attr(
  12. #[derive(Debug, PartialEq)]
  13. ))]
  14. pub struct Rectangle {
  15. pub core: ObjectCore,
  16. #[brw(magic(8u32))] // Number of following fields in struct
  17. pub drawn_corner_a: FieldOf<Coordinate>,
  18. pub drawn_corner_b: FieldOf<Coordinate>,
  19. pub round_bottom_left: F64,
  20. pub round_bottom_right: F64,
  21. pub round_top_right: F64,
  22. pub round_top_left: F64,
  23. pub modifier: ObjectModifier,
  24. }
  25. impl Display for Rectangle {
  26. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  27. let (origin, width, height) = self
  28. .modifier
  29. .corrected(*self.drawn_corner_a, *self.drawn_corner_b);
  30. if format!("{}", origin) != format!("{}", *self.core.origin) {
  31. warn!(
  32. "Origin mismatch! Core: {}, Calculated: {}",
  33. *self.core.origin, origin
  34. );
  35. }
  36. write!(
  37. f,
  38. "{}, Origin: {}, Width: {:.2}, Height: {:.2}",
  39. self.core, origin, width, height,
  40. )
  41. }
  42. }
  43. impl Default for Rectangle {
  44. fn default() -> Self {
  45. Self {
  46. core: ObjectCore::default(ObjectType::Rectangle),
  47. drawn_corner_a: Coordinate { x: 0.0, y: 0.0 }.into(),
  48. drawn_corner_b: Coordinate { x: 0.0, y: 0.0 }.into(),
  49. round_bottom_left: 0.0.into(),
  50. round_bottom_right: 0.0.into(),
  51. round_top_right: 0.0.into(),
  52. round_top_left: 0.0.into(),
  53. modifier: ObjectModifier::default(),
  54. }
  55. }
  56. }
  57. // origin_x = x_corretion + (drawn_a.x + drawn_b.x) / 2 * x_scale
  58. // x_correction = origin_x - (drawn_a.x + drawn_b.x) / 2 * x_scale
  59. impl Translate for Rectangle {
  60. fn move_absolute(&mut self, origin: Option<Coordinate>, z: Option<f64>) {
  61. origin.map(|origin| {
  62. let delta: Coordinate = origin - *self.core.origin;
  63. self.modifier.move_relative(delta);
  64. });
  65. self.core.move_absolute(origin, z);
  66. }
  67. fn move_relative(&mut self, delta: Option<Coordinate>, z: Option<f64>) {
  68. delta.map(|delta| {
  69. self.modifier.move_relative(delta);
  70. });
  71. self.core.move_relative(delta, z);
  72. }
  73. }