qualia_core_db/specialized_libs/computational_geometry/
primitives.rs1use bytemuck::{Pod, Zeroable};
2use serde::{Deserialize, Serialize};
3
4use crate::tensor::Tensor10D;
5
6#[repr(C)]
8#[derive(Debug, Default, Clone, Copy, PartialEq, Pod, Zeroable, Serialize, Deserialize)]
9pub struct Point2 {
10 pub x: f64,
11 pub y: f64,
12}
13
14impl Point2 {
15 #[inline]
16 pub const fn new(x: f64, y: f64) -> Self {
18 Self { x, y }
19 }
20}
21
22#[repr(C)]
24#[derive(Debug, Default, Clone, Copy, PartialEq, Pod, Zeroable, Serialize, Deserialize)]
25pub struct Point3 {
26 pub x: f64,
27 pub y: f64,
28 pub z: f64,
29}
30
31impl Point3 {
32 #[inline]
33 pub const fn new(x: f64, y: f64, z: f64) -> Self {
35 Self { x, y, z }
36 }
37}
38
39#[repr(i8)]
40#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
41pub enum Orientation {
42 Clockwise = -1,
43 Collinear = 0,
44 CounterClockwise = 1,
45}
46
47#[inline]
54pub fn orientation_2(a: Point2, b: Point2, c: Point2) -> Orientation {
55 let acx = a.x - c.x;
56 let bcx = b.x - c.x;
57 let acy = a.y - c.y;
58 let bcy = b.y - c.y;
59 let left = acx * bcy;
60 let right = acy * bcx;
61 let det = left - right;
62
63 let scale = left.abs() + right.abs();
64 let error_bound = scale * (8.0 * f64::EPSILON);
65 let resolved = if det.abs() > error_bound {
66 det
67 } else {
68 let left_error = acx.mul_add(bcy, -left);
70 let right_error = acy.mul_add(bcx, -right);
71 det + (left_error - right_error)
72 };
73
74 if resolved > 0.0 {
75 Orientation::CounterClockwise
76 } else if resolved < 0.0 {
77 Orientation::Clockwise
78 } else {
79 Orientation::Collinear
80 }
81}
82
83#[inline]
85pub fn orientation_2_tensor_xy(a: &Tensor10D, b: &Tensor10D, c: &Tensor10D) -> Orientation {
86 orientation_2(
87 Point2::new(a.x as f64, a.y as f64),
88 Point2::new(b.x as f64, b.y as f64),
89 Point2::new(c.x as f64, c.y as f64),
90 )
91}
92
93#[cfg(test)]
94mod tests {
95 use super::*;
96
97 #[test]
98 fn orientation_classifies_turns() {
99 let a = Point2::new(0.0, 0.0);
100 let b = Point2::new(1.0, 0.0);
101 assert_eq!(
102 orientation_2(a, b, Point2::new(1.0, 1.0)),
103 Orientation::CounterClockwise
104 );
105 assert_eq!(
106 orientation_2(a, b, Point2::new(1.0, -1.0)),
107 Orientation::Clockwise
108 );
109 assert_eq!(
110 orientation_2(a, b, Point2::new(2.0, 0.0)),
111 Orientation::Collinear
112 );
113 }
114
115 #[test]
116 fn tensor_predicate_uses_spatial_plane() {
117 let mut a = Tensor10D::default();
118 let mut b = Tensor10D::default();
119 let mut c = Tensor10D::default();
120 b.x = 1.0;
121 c.x = 1.0;
122 c.y = 1.0;
123 a.q = 4.0;
124 b.v = 2.0;
125 c.sigma = 9.0;
126 assert_eq!(
127 orientation_2_tensor_xy(&a, &b, &c),
128 Orientation::CounterClockwise
129 );
130 }
131}