1use serde::{Deserialize, Serialize};
20use uuid::Uuid;
21
22use super::field_ast::{ScalarField, VectorField};
23
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
27pub struct FieldId(pub Uuid);
28
29impl FieldId {
30 #[cfg(not(target_arch = "wasm32"))]
34 pub fn new() -> Self {
35 Self(Uuid::new_v4())
36 }
37
38 pub fn from_uuid(id: Uuid) -> Self {
39 Self(id)
40 }
41
42 pub fn as_uuid(self) -> Uuid {
43 self.0
44 }
45}
46
47#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
49pub struct CouplingId(pub Uuid);
50
51impl CouplingId {
52 #[cfg(not(target_arch = "wasm32"))]
53 pub fn new() -> Self {
54 Self(Uuid::new_v4())
55 }
56
57 pub fn from_uuid(id: Uuid) -> Self {
58 Self(id)
59 }
60
61 pub fn as_uuid(self) -> Uuid {
62 self.0
63 }
64}
65
66#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
69pub enum FieldDefinition {
70 Scalar(ScalarField),
71 Vector(VectorField),
72}
73
74#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
78pub enum FieldExtent {
79 Global,
81 Region {
83 min_x: f32,
84 min_y: f32,
85 max_x: f32,
86 max_y: f32,
87 },
88 AttachedToNode(Uuid),
90 Polygon { points: Vec<(f32, f32)> },
97}
98
99impl FieldExtent {
100 pub fn contains(&self, x: f32, y: f32) -> Option<bool> {
106 match self {
107 FieldExtent::Global => Some(true),
108 FieldExtent::Region {
109 min_x,
110 min_y,
111 max_x,
112 max_y,
113 } => Some(x >= *min_x && x <= *max_x && y >= *min_y && y <= *max_y),
114 FieldExtent::AttachedToNode(_) => None,
115 FieldExtent::Polygon { points } => Some(polygon_contains(points, x, y)),
116 }
117 }
118
119 pub fn boundary_distance(&self, x: f32, y: f32) -> Option<f32> {
124 match self {
125 FieldExtent::Global => None,
126 FieldExtent::AttachedToNode(_) => None,
127 FieldExtent::Region {
128 min_x,
129 min_y,
130 max_x,
131 max_y,
132 } => {
133 let inside = (x - min_x).min(max_x - x).min(y - min_y).min(max_y - y);
134 Some(inside)
135 }
136 FieldExtent::Polygon { points } => {
137 if points.len() < 3 {
138 return None;
139 }
140 let nearest = points
141 .iter()
142 .enumerate()
143 .map(|(index, a)| {
144 let b = points[(index + 1) % points.len()];
145 segment_distance(*a, b, (x, y))
146 })
147 .fold(f32::INFINITY, f32::min);
148 Some(if polygon_contains(points, x, y) {
149 nearest
150 } else {
151 -nearest
152 })
153 }
154 }
155 }
156}
157
158fn polygon_contains(points: &[(f32, f32)], x: f32, y: f32) -> bool {
161 if points.len() < 3 {
162 return false;
163 }
164 let mut inside = false;
165 for (index, a) in points.iter().enumerate() {
166 let b = points[(index + 1) % points.len()];
167 if (a.1 > y) != (b.1 > y) && x < a.0 + (b.0 - a.0) * (y - a.1) / (b.1 - a.1) {
168 inside = !inside;
169 }
170 }
171 inside
172}
173
174fn segment_distance(a: (f32, f32), b: (f32, f32), p: (f32, f32)) -> f32 {
175 let (abx, aby) = (b.0 - a.0, b.1 - a.1);
176 let (apx, apy) = (p.0 - a.0, p.1 - a.1);
177 let length_sq = abx * abx + aby * aby;
178 let t = if length_sq <= f32::EPSILON {
179 0.0
180 } else {
181 ((apx * abx + apy * aby) / length_sq).clamp(0.0, 1.0)
182 };
183 let (dx, dy) = (apx - abx * t, apy - aby * t);
184 (dx * dx + dy * dy).sqrt()
185}
186
187#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
191pub enum FieldLifecycle {
192 Active,
193 Retired,
194}
195
196#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
198pub struct Field {
199 pub id: FieldId,
200 pub name: Option<String>,
203 pub definition: FieldDefinition,
204 pub extent: FieldExtent,
205 pub lifecycle: FieldLifecycle,
206}
207
208impl Field {
209 pub fn new(id: FieldId, definition: FieldDefinition) -> Self {
211 Self {
212 id,
213 name: None,
214 definition,
215 extent: FieldExtent::Global,
216 lifecycle: FieldLifecycle::Active,
217 }
218 }
219
220 pub fn with_name(mut self, name: impl Into<String>) -> Self {
221 self.name = Some(name.into());
222 self
223 }
224
225 pub fn with_extent(mut self, extent: FieldExtent) -> Self {
226 self.extent = extent;
227 self
228 }
229
230 pub fn is_active(&self) -> bool {
231 self.lifecycle == FieldLifecycle::Active
232 }
233}
234
235#[cfg(test)]
236mod tests {
237 use super::super::field_ast::Falloff;
238 use super::*;
239
240 fn sample_uuid(n: u8) -> Uuid {
241 Uuid::from_bytes([n; 16])
242 }
243
244 #[test]
245 fn field_serde_roundtrip() {
246 let field = Field::new(
247 FieldId::from_uuid(sample_uuid(1)),
248 FieldDefinition::Scalar(ScalarField::disk_at(0.0, 0.0, 50.0, Falloff::Smoothstep)),
249 )
250 .with_name("focus")
251 .with_extent(FieldExtent::AttachedToNode(sample_uuid(2)));
252 let s = serde_json::to_string(&field).unwrap();
253 let back: Field = serde_json::from_str(&s).unwrap();
254 assert_eq!(field, back);
255 }
256
257 #[test]
258 fn defaults_are_global_active() {
259 let f = Field::new(
260 FieldId::from_uuid(sample_uuid(3)),
261 FieldDefinition::Vector(VectorField::Coord),
262 );
263 assert_eq!(f.extent, FieldExtent::Global);
264 assert!(f.is_active());
265 assert!(f.name.is_none());
266 }
267
268 #[test]
269 fn a_polygon_extent_contains_and_measures() {
270 let extent = FieldExtent::Polygon {
273 points: vec![(0.0, 0.0), (10.0, 0.0), (0.0, 10.0)],
274 };
275
276 assert_eq!(extent.contains(2.0, 2.0), Some(true));
277 assert_eq!(extent.contains(9.0, 9.0), Some(false));
278 assert!(extent.boundary_distance(2.0, 2.0).unwrap() > 0.0);
279 assert!(extent.boundary_distance(20.0, 20.0).unwrap() < 0.0);
280 let inside = extent.boundary_distance(3.0, 1.0).unwrap();
282 assert!((inside - 1.0).abs() < 1e-4, "got {inside}");
283 }
284
285 #[test]
286 fn a_degenerate_polygon_contains_nothing() {
287 let extent = FieldExtent::Polygon {
288 points: vec![(0.0, 0.0), (10.0, 0.0)],
289 };
290 assert_eq!(extent.contains(5.0, 0.0), Some(false));
291 assert_eq!(extent.boundary_distance(5.0, 0.0), None);
292 }
293
294 #[test]
295 fn attachment_is_a_question_for_a_graph() {
296 let extent = FieldExtent::AttachedToNode(sample_uuid(9));
298 assert_eq!(extent.contains(0.0, 0.0), None);
299 assert_eq!(extent.boundary_distance(0.0, 0.0), None);
300 }
301
302 #[test]
303 fn a_polygon_extent_round_trips() {
304 let field = Field::new(
305 FieldId::from_uuid(sample_uuid(7)),
306 FieldDefinition::Scalar(ScalarField::Const(1.0)),
307 )
308 .with_extent(FieldExtent::Polygon {
309 points: vec![(0.0, 0.0), (4.0, 0.0), (4.0, 4.0), (0.0, 4.0)],
310 });
311 let json = serde_json::to_string(&field).unwrap();
312 assert_eq!(serde_json::from_str::<Field>(&json).unwrap(), field);
313 }
314
315 #[test]
316 fn ids_are_distinct_types_but_uuid_backed() {
317 let fid = FieldId::from_uuid(sample_uuid(4));
318 let cid = CouplingId::from_uuid(sample_uuid(4));
319 assert_eq!(fid.as_uuid(), cid.as_uuid());
320 }
321}