1use serde::{Deserialize, Serialize};
25use uuid::Uuid;
26
27use super::field_ast::{ScalarField, VectorField};
28
29#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
31pub struct FieldId(pub Uuid);
32
33impl FieldId {
34 #[cfg(not(target_arch = "wasm32"))]
38 pub fn new() -> Self {
39 Self(Uuid::new_v4())
40 }
41
42 pub fn from_uuid(id: Uuid) -> Self {
43 Self(id)
44 }
45
46 pub fn as_uuid(self) -> Uuid {
47 self.0
48 }
49}
50
51#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
53pub struct CouplingId(pub Uuid);
54
55impl CouplingId {
56 #[cfg(not(target_arch = "wasm32"))]
57 pub fn new() -> Self {
58 Self(Uuid::new_v4())
59 }
60
61 pub fn from_uuid(id: Uuid) -> Self {
62 Self(id)
63 }
64
65 pub fn as_uuid(self) -> Uuid {
66 self.0
67 }
68}
69
70#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
73pub enum FieldDefinition {
74 Scalar(ScalarField),
75 Vector(VectorField),
76}
77
78#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
82pub enum FieldExtent {
83 Global,
85 Region {
87 min_x: f32,
88 min_y: f32,
89 max_x: f32,
90 max_y: f32,
91 },
92 AttachedToNode(Uuid),
94 Polygon { points: Vec<(f32, f32)> },
101}
102
103impl FieldExtent {
104 pub fn contains(&self, x: f32, y: f32) -> Option<bool> {
110 match self {
111 FieldExtent::Global => Some(true),
112 FieldExtent::Region {
113 min_x,
114 min_y,
115 max_x,
116 max_y,
117 } => Some(x >= *min_x && x <= *max_x && y >= *min_y && y <= *max_y),
118 FieldExtent::AttachedToNode(_) => None,
119 FieldExtent::Polygon { points } => Some(polygon_contains(points, x, y)),
120 }
121 }
122
123 pub fn boundary_distance(&self, x: f32, y: f32) -> Option<f32> {
128 match self {
129 FieldExtent::Global => None,
130 FieldExtent::AttachedToNode(_) => None,
131 FieldExtent::Region {
132 min_x,
133 min_y,
134 max_x,
135 max_y,
136 } => {
137 let inside = (x - min_x).min(max_x - x).min(y - min_y).min(max_y - y);
138 Some(inside)
139 },
140 FieldExtent::Polygon { points } => {
141 if points.len() < 3 {
142 return None;
143 }
144 let nearest = points
145 .iter()
146 .enumerate()
147 .map(|(index, a)| {
148 let b = points[(index + 1) % points.len()];
149 segment_distance(*a, b, (x, y))
150 })
151 .fold(f32::INFINITY, f32::min);
152 Some(if polygon_contains(points, x, y) {
153 nearest
154 } else {
155 -nearest
156 })
157 },
158 }
159 }
160}
161
162fn polygon_contains(points: &[(f32, f32)], x: f32, y: f32) -> bool {
165 if points.len() < 3 {
166 return false;
167 }
168 if !x.is_finite()
169 || !y.is_finite()
170 || points.iter().any(|(x, y)| !x.is_finite() || !y.is_finite())
171 {
172 return false;
173 }
174 let a = points[0];
177 let Some(b) = points.iter().find(|b| **b != a) else {
178 return false;
179 };
180 let collinear = points.iter().all(|p| {
181 (f64::from(b.0) - f64::from(a.0)) * (f64::from(p.1) - f64::from(a.1))
182 == (f64::from(b.1) - f64::from(a.1)) * (f64::from(p.0) - f64::from(a.0))
183 });
184 if collinear {
185 return false;
186 }
187 let (x, y) = (f64::from(x), f64::from(y));
188 let mut inside = false;
189 for (index, a) in points.iter().enumerate() {
190 let b = points[(index + 1) % points.len()];
191 let (ax, ay, bx, by) = (
192 f64::from(a.0),
193 f64::from(a.1),
194 f64::from(b.0),
195 f64::from(b.1),
196 );
197 let cross = (bx - ax) * (y - ay) - (by - ay) * (x - ax);
199 if cross == 0.0 && x >= ax.min(bx) && x <= ax.max(bx) && y >= ay.min(by) && y <= ay.max(by)
200 {
201 return true;
202 }
203 if (ay > y) != (by > y) && x < ax + (bx - ax) * (y - ay) / (by - ay) {
204 inside = !inside;
205 }
206 }
207 inside
208}
209
210fn segment_distance(a: (f32, f32), b: (f32, f32), p: (f32, f32)) -> f32 {
211 let (abx, aby) = (b.0 - a.0, b.1 - a.1);
212 let (apx, apy) = (p.0 - a.0, p.1 - a.1);
213 let length_sq = abx * abx + aby * aby;
214 let t = if length_sq <= f32::EPSILON {
215 0.0
216 } else {
217 ((apx * abx + apy * aby) / length_sq).clamp(0.0, 1.0)
218 };
219 let (dx, dy) = (apx - abx * t, apy - aby * t);
220 (dx * dx + dy * dy).sqrt()
221}
222
223#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
227pub enum FieldLifecycle {
228 Active,
229 Retired,
230}
231
232#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
234pub struct Field {
235 pub id: FieldId,
236 pub name: Option<String>,
239 pub definition: FieldDefinition,
240 pub extent: FieldExtent,
241 pub lifecycle: FieldLifecycle,
242}
243
244impl Field {
245 pub fn new(id: FieldId, definition: FieldDefinition) -> Self {
247 Self {
248 id,
249 name: None,
250 definition,
251 extent: FieldExtent::Global,
252 lifecycle: FieldLifecycle::Active,
253 }
254 }
255
256 pub fn with_name(mut self, name: impl Into<String>) -> Self {
257 self.name = Some(name.into());
258 self
259 }
260
261 pub fn with_extent(mut self, extent: FieldExtent) -> Self {
262 self.extent = extent;
263 self
264 }
265
266 pub fn is_active(&self) -> bool {
267 self.lifecycle == FieldLifecycle::Active
268 }
269}
270
271#[cfg(test)]
272mod tests {
273 use super::super::field_ast::Falloff;
274 use super::*;
275
276 fn sample_uuid(n: u8) -> Uuid {
277 Uuid::from_bytes([n; 16])
278 }
279
280 #[test]
281 fn field_serde_roundtrip() {
282 let field = Field::new(
283 FieldId::from_uuid(sample_uuid(1)),
284 FieldDefinition::Scalar(ScalarField::disk_at(0.0, 0.0, 50.0, Falloff::Smoothstep)),
285 )
286 .with_name("focus")
287 .with_extent(FieldExtent::AttachedToNode(sample_uuid(2)));
288 let s = serde_json::to_string(&field).unwrap();
289 let back: Field = serde_json::from_str(&s).unwrap();
290 assert_eq!(field, back);
291 }
292
293 #[test]
294 fn defaults_are_global_active() {
295 let f = Field::new(
296 FieldId::from_uuid(sample_uuid(3)),
297 FieldDefinition::Vector(VectorField::Coord),
298 );
299 assert_eq!(f.extent, FieldExtent::Global);
300 assert!(f.is_active());
301 assert!(f.name.is_none());
302 }
303
304 #[test]
305 fn a_polygon_extent_contains_and_measures() {
306 let extent = FieldExtent::Polygon {
309 points: vec![(0.0, 0.0), (10.0, 0.0), (0.0, 10.0)],
310 };
311
312 assert_eq!(extent.contains(2.0, 2.0), Some(true));
313 assert_eq!(extent.contains(9.0, 9.0), Some(false));
314 assert!(extent.boundary_distance(2.0, 2.0).unwrap() > 0.0);
315 assert!(extent.boundary_distance(20.0, 20.0).unwrap() < 0.0);
316 let inside = extent.boundary_distance(3.0, 1.0).unwrap();
318 assert!((inside - 1.0).abs() < 1e-4, "got {inside}");
319 }
320
321 #[test]
322 fn a_degenerate_polygon_contains_nothing() {
323 let extent = FieldExtent::Polygon {
324 points: vec![(0.0, 0.0), (10.0, 0.0)],
325 };
326 assert_eq!(extent.contains(5.0, 0.0), Some(false));
327 assert_eq!(extent.boundary_distance(5.0, 0.0), None);
328 }
329
330 #[test]
331 fn attachment_is_a_question_for_a_graph() {
332 let extent = FieldExtent::AttachedToNode(sample_uuid(9));
334 assert_eq!(extent.contains(0.0, 0.0), None);
335 assert_eq!(extent.boundary_distance(0.0, 0.0), None);
336 }
337
338 #[test]
339 fn a_polygon_extent_round_trips() {
340 let field = Field::new(
341 FieldId::from_uuid(sample_uuid(7)),
342 FieldDefinition::Scalar(ScalarField::Const(1.0)),
343 )
344 .with_extent(FieldExtent::Polygon {
345 points: vec![(0.0, 0.0), (4.0, 0.0), (4.0, 4.0), (0.0, 4.0)],
346 });
347 let json = serde_json::to_string(&field).unwrap();
348 assert_eq!(serde_json::from_str::<Field>(&json).unwrap(), field);
349 }
350
351 #[test]
352 fn ids_are_distinct_types_but_uuid_backed() {
353 let fid = FieldId::from_uuid(sample_uuid(4));
354 let cid = CouplingId::from_uuid(sample_uuid(4));
355 assert_eq!(fid.as_uuid(), cid.as_uuid());
356 }
357}
358
359#[cfg(test)]
360mod inclusive_boundary_tests {
361 use super::*;
362 #[test]
363 fn polygon_reference_points_include_every_edge_and_vertex_in_both_windings() {
364 let mut points = vec![(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)];
365 for _ in 0..2 {
366 let extent = FieldExtent::Polygon {
367 points: points.clone(),
368 };
369 for (x, y) in [
370 (0., 0.),
371 (10., 0.),
372 (10., 10.),
373 (0., 10.),
374 (0., 5.),
375 (10., 5.),
376 (5., 0.),
377 (5., 10.),
378 (5., 5.),
379 ] {
380 assert_eq!(extent.contains(x, y), Some(true), "({x}, {y})");
381 }
382 assert_eq!(
383 extent.contains(f32::from_bits(10.0_f32.to_bits() + 1), 5.0),
384 Some(false)
385 );
386 assert_eq!(extent.contains(f32::NAN, 5.0), Some(false));
387 points.reverse();
388 assert_eq!(
389 FieldExtent::Polygon {
390 points: vec![(0.0, 0.0), (5.0, 0.0), (10.0, 0.0)]
391 }
392 .contains(5.0, 0.0),
393 Some(false)
394 );
395 }
396 }
397}