Skip to main content

numen/
field.rs

1//! The `Field` truth primitive — fields as a third graph element beside nodes
2//! and edges (the field-system extraction
3//! decision; this is its step-3 kernel slice).
4//!
5//! A [`Field`] is identity + a portable [`FieldDefinition`] (the scalar/vector
6//! AST as data) + a [`FieldExtent`] + a [`FieldLifecycle`]. The definition is
7//! truth the kernel owns and persists; `quint` evaluates it. Identity is a
8//! stable, federatable UUID ([`FieldId`]), unlike `quint`'s original
9//! registry-local `FieldId(u64)` — the kernel id is canonical once fields are
10//! kernel truth.
11//!
12//! Storage (plan Phase 1) is a parallel keyed store on `Graph`, **not** a
13//! petgraph node weight and **not** an `EdgePayload` sidecar: a coupling is
14//! field-to-selector, never node-to-node, so it cannot ride the node/edge graph.
15//!
16//! Derives are serde only for now; rkyv archiving lands at the `Persisted*` DTO
17//! layer (plan Phase 2). WASM-clean.
18
19use serde::{Deserialize, Serialize};
20use uuid::Uuid;
21
22use super::field_ast::{ScalarField, VectorField};
23
24/// Stable, federatable field identity. UUID-backed (vs `quint`'s original
25/// registry-local `FieldId(u64)`); this is the canonical id for kernel truth.
26#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
27pub struct FieldId(pub Uuid);
28
29impl FieldId {
30    /// Fresh random identity. Non-WASM only (`Uuid::new_v4` needs an OS
31    /// randomness source absent on `wasm32-unknown-unknown`); WASM hosts
32    /// construct via [`FieldId::from_uuid`] with a host-supplied UUID.
33    #[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/// Stable identity for a coupling rule.
48#[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/// A field's portable definition: scalar- or vector-valued. The AST is data;
67/// `quint` evaluates it.
68#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
69pub enum FieldDefinition {
70    Scalar(ScalarField),
71    Vector(VectorField),
72}
73
74/// Where a field applies. (`Region` is an axis-aligned world-space box, kept as
75/// four scalars to stay rkyv-friendly at the DTO layer without a `Box2D`
76/// archive helper.)
77#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
78pub enum FieldExtent {
79    /// Applies everywhere.
80    Global,
81    /// Applies within an axis-aligned world-space box.
82    Region {
83        min_x: f32,
84        min_y: f32,
85        max_x: f32,
86        max_y: f32,
87    },
88    /// Travels with a node (its `Node.id`).
89    AttachedToNode(Uuid),
90    /// Applies within a closed world-space polygon.
91    ///
92    /// The hulls extent: a place-graph cell, a drawn hull, a map region. Kept
93    /// as bare point pairs for the same rkyv-friendliness reason `Region` is
94    /// four scalars. Fewer than three points is a degenerate extent that
95    /// contains nothing.
96    Polygon { points: Vec<(f32, f32)> },
97}
98
99impl FieldExtent {
100    /// Whether a world-space point falls inside this extent.
101    ///
102    /// `None` for [`AttachedToNode`](FieldExtent::AttachedToNode), which only
103    /// a graph can answer: the extent travels with a node this type cannot
104    /// see. Callers with a graph resolve that arm themselves.
105    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    /// Distance from a point to the extent's boundary, for falloff shaping.
120    ///
121    /// Positive inside, negative outside, `None` where boundaries make no
122    /// sense (`Global` has none; `AttachedToNode` needs a graph).
123    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
158/// Even-odd ray cast. Winding is not significant, matching the scene
159/// contract's polygon footprint.
160fn 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/// Field lifecycle state. Mirrors the spirit of `NodeLifecycle`: a field is
188/// authored (Active) and can be retired without losing its definition for
189/// history/federation. Richer states (Warm/Cold equivalents) are deferred.
190#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
191pub enum FieldLifecycle {
192    Active,
193    Retired,
194}
195
196/// A field as kernel truth: identity + portable definition + extent + lifecycle.
197#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
198pub struct Field {
199    pub id: FieldId,
200    /// Optional authoring name (parity with `quint`'s named registry; lets
201    /// definitions reference each other by a human label before id resolution).
202    pub name: Option<String>,
203    pub definition: FieldDefinition,
204    pub extent: FieldExtent,
205    pub lifecycle: FieldLifecycle,
206}
207
208impl Field {
209    /// A global, active field with no authoring name.
210    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        // A triangle. Containment is even-odd; boundary distance is signed,
271        // positive inside, so falloffs can shape against the edge.
272        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        // On an axis edge, distance to the nearest boundary is the y height.
281        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        // The honest None: this type cannot know where a node is.
297        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}