Skip to main content

numen/
field.rs

1// Copyright 2026 Mark Alan Boykin
2// This Source Code Form is subject to the terms of the Mozilla Public
3// License, v. 2.0. If a copy of the MPL was not distributed with this
4// file, You can obtain one at https://mozilla.org/MPL/2.0/.
5// SPDX-License-Identifier: MPL-2.0
6
7//! The `Field` truth primitive — fields as a third graph element beside nodes
8//! and edges (the field-system extraction
9//! decision; this is its step-3 kernel slice).
10//!
11//! A [`Field`] is identity + a portable [`FieldDefinition`] (the scalar/vector
12//! AST as data) + a [`FieldExtent`] + a [`FieldLifecycle`]. The definition is
13//! truth the kernel owns and persists; numen evaluates it. Identity is a
14//! stable, federatable UUID ([`FieldId`]); the kernel id is canonical once
15//! fields are graph truth.
16//!
17//! Storage (plan Phase 1) is a parallel keyed store on `Graph`, **not** a
18//! petgraph node weight and **not** an `EdgePayload` sidecar: a coupling is
19//! field-to-selector, never node-to-node, so it cannot ride the node/edge graph.
20//!
21//! Derives are serde only for now; rkyv archiving lands at the `Persisted*` DTO
22//! layer (plan Phase 2). WASM-clean.
23
24use serde::{Deserialize, Serialize};
25use uuid::Uuid;
26
27use super::field_ast::{ScalarField, VectorField};
28
29/// Stable, federatable field identity. UUID-backed and canonical for graph truth.
30#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
31pub struct FieldId(pub Uuid);
32
33impl FieldId {
34    /// Fresh random identity. Non-WASM only (`Uuid::new_v4` needs an OS
35    /// randomness source absent on `wasm32-unknown-unknown`); WASM hosts
36    /// construct via [`FieldId::from_uuid`] with a host-supplied UUID.
37    #[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/// Stable identity for a coupling rule.
52#[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/// A field's portable definition: scalar- or vector-valued. The AST is data;
71/// numen evaluates it.
72#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
73pub enum FieldDefinition {
74    Scalar(ScalarField),
75    Vector(VectorField),
76}
77
78/// Where a field applies. (`Region` is an axis-aligned world-space box, kept as
79/// four scalars to stay rkyv-friendly at the DTO layer without a `Box2D`
80/// archive helper.)
81#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
82pub enum FieldExtent {
83    /// Applies everywhere.
84    Global,
85    /// Applies within an axis-aligned world-space box.
86    Region {
87        min_x: f32,
88        min_y: f32,
89        max_x: f32,
90        max_y: f32,
91    },
92    /// Travels with a node (its `Node.id`).
93    AttachedToNode(Uuid),
94    /// Applies within a closed world-space polygon.
95    ///
96    /// The hulls extent: a place-graph cell, a drawn hull, a map region. Kept
97    /// as bare point pairs for the same rkyv-friendliness reason `Region` is
98    /// four scalars. Fewer than three points is a degenerate extent that
99    /// contains nothing.
100    Polygon { points: Vec<(f32, f32)> },
101}
102
103impl FieldExtent {
104    /// Whether a world-space point falls inside this extent.
105    ///
106    /// `None` for [`AttachedToNode`](FieldExtent::AttachedToNode), which only
107    /// a graph can answer: the extent travels with a node this type cannot
108    /// see. Callers with a graph resolve that arm themselves.
109    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    /// Distance from a point to the extent's boundary, for falloff shaping.
124    ///
125    /// Positive inside, negative outside, `None` where boundaries make no
126    /// sense (`Global` has none; `AttachedToNode` needs a graph).
127    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
162/// Even-odd ray cast. Winding is not significant, matching the scene
163/// contract's polygon footprint.
164fn 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    // Preserve empty/collinear polygon semantics; an inclusive edge must not
175    // turn a degenerate polygon into a path-shaped field.
176    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        // Inclusive boundary, without an unruled epsilon/hysteresis policy.
198        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/// Field lifecycle state. Mirrors the spirit of `NodeLifecycle`: a field is
224/// authored (Active) and can be retired without losing its definition for
225/// history/federation. Richer states (Warm/Cold equivalents) are deferred.
226#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
227pub enum FieldLifecycle {
228    Active,
229    Retired,
230}
231
232/// A field as kernel truth: identity + portable definition + extent + lifecycle.
233#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
234pub struct Field {
235    pub id: FieldId,
236    /// Optional authoring name (parity with numen's named registry; lets
237    /// definitions reference each other by a human label before id resolution).
238    pub name: Option<String>,
239    pub definition: FieldDefinition,
240    pub extent: FieldExtent,
241    pub lifecycle: FieldLifecycle,
242}
243
244impl Field {
245    /// A global, active field with no authoring name.
246    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        // A triangle. Containment is even-odd; boundary distance is signed,
307        // positive inside, so falloffs can shape against the edge.
308        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        // On an axis edge, distance to the nearest boundary is the y height.
317        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        // The honest None: this type cannot know where a node is.
333        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}