Skip to main content

qualia_core_db/domains/geospatial/
triggers.rs

1use std::collections::HashMap;
2
3use crate::modalities::spatio_temporal::{self, Rcc8Relation};
4use crate::q_hash;
5use crate::NQuin;
6
7/// A registry mapping spatial regions (e.g., geohash or bounding box hash) to
8/// governed N3 trigger rules. When a user or entity crosses into a region,
9/// the corresponding rules are injected into the Webizen VM for evaluation.
10pub struct LocationTriggerRegistry {
11    pub region_rules: HashMap<u64, Vec<NQuin>>,
12}
13
14impl LocationTriggerRegistry {
15    /// Creates an empty trigger registry.
16    pub fn new() -> Self {
17        Self {
18            region_rules: HashMap::new(),
19        }
20    }
21
22    /// Registers `rule_quin` to fire in `region_hash`.
23    pub fn register_trigger(&mut self, region_hash: u64, rule_quin: NQuin) {
24        self.region_rules
25            .entry(region_hash)
26            .or_default()
27            .push(rule_quin);
28    }
29
30    /// All rule quins registered for `location_hash`.
31    pub fn evaluate_triggers_at(&self, location_hash: u64) -> Vec<NQuin> {
32        let mut triggers = Vec::new();
33        if let Some(rules) = self.region_rules.get(&location_hash) {
34            triggers.extend(rules.iter().copied());
35        }
36        triggers
37    }
38}
39
40impl Default for LocationTriggerRegistry {
41    fn default() -> Self {
42        Self::new()
43    }
44}
45
46/// Engine that fires location triggers, optionally using RCC-8 containment when
47/// boundary quins are available in the arena.
48pub struct LocationTriggerEngine {
49    registry: LocationTriggerRegistry,
50}
51
52impl LocationTriggerEngine {
53    /// Creates a trigger engine with an empty registry.
54    pub fn new() -> Self {
55        Self {
56            registry: LocationTriggerRegistry::new(),
57        }
58    }
59
60    /// Registers a trigger rule in `region_hash`.
61    pub fn register_trigger(&mut self, region_hash: u64, rule_quin: NQuin) {
62        self.registry.register_trigger(region_hash, rule_quin);
63    }
64
65    /// Collect triggers that should fire when entering `location_hash`.
66    /// Evaluates RCC-8 containment when boundary quins and a location point are present.
67    pub fn on_enter(&self, location_hash: u64, arena_quins: &[NQuin]) -> Vec<NQuin> {
68        self.fire_triggers_at(location_hash, arena_quins)
69    }
70
71    /// Returns rule quins to inject for the given location.
72    pub fn fire_triggers_at(&self, location_hash: u64, arena_quins: &[NQuin]) -> Vec<NQuin> {
73        let mut triggers = self.registry.evaluate_triggers_at(location_hash);
74
75        let boundary = q_hash("spatial:boundary");
76        let location_point = q_hash("q42:locationPoint");
77
78        let loc_point = arena_quins.iter().find_map(|quin| {
79            if quin.subject == location_hash && quin.predicate == location_point {
80                Some(spatio_temporal::unpack_point(quin.object))
81            } else {
82                None
83            }
84        });
85
86        if let Some(point) = loc_point {
87            let point_slice = [point];
88            for (region_hash, rules) in &self.registry.region_rules {
89                if *region_hash == location_hash {
90                    continue;
91                }
92                let region_poly = collect_boundary_points(*region_hash, arena_quins, boundary);
93                if region_poly.len() < 3 {
94                    continue;
95                }
96                let relation = spatio_temporal::evaluate_rcc8_points(
97                    location_hash,
98                    &point_slice,
99                    *region_hash,
100                    &region_poly,
101                );
102                if is_containment(relation) {
103                    for rule in rules {
104                        if !triggers.iter().any(|t| t == rule) {
105                            triggers.push(*rule);
106                        }
107                    }
108                }
109            }
110        }
111
112        triggers
113    }
114}
115
116impl Default for LocationTriggerEngine {
117    fn default() -> Self {
118        Self::new()
119    }
120}
121
122fn is_containment(relation: Rcc8Relation) -> bool {
123    matches!(
124        relation,
125        Rcc8Relation::NonTangentialProperPart
126            | Rcc8Relation::TangentiallyProperPart
127            | Rcc8Relation::Equal
128    )
129}
130
131fn collect_boundary_points(
132    region_id: u64,
133    arena_quins: &[NQuin],
134    boundary_pred: u64,
135) -> Vec<(f64, f64)> {
136    let mut indexed: Vec<(u32, (f64, f64))> = Vec::new();
137    for quin in arena_quins {
138        if quin.subject == region_id && quin.predicate == boundary_pred {
139            let idx = quin.metadata as u32;
140            indexed.push((idx, spatio_temporal::unpack_point(quin.object)));
141        }
142    }
143    indexed.sort_by_key(|(idx, _)| *idx);
144    indexed.into_iter().map(|(_, pt)| pt).collect()
145}
146
147#[cfg(test)]
148mod tests {
149    use super::*;
150
151    #[test]
152    fn test_register_and_evaluate_trigger() {
153        let mut registry = LocationTriggerRegistry::new();
154        let region = 0x123456789;
155        let rule = NQuin {
156            subject: 1,
157            predicate: 2,
158            object: 3,
159            context: 0,
160            metadata: 0,
161            parity: 0,
162        };
163        registry.register_trigger(region, rule);
164
165        let triggers = registry.evaluate_triggers_at(region);
166        assert_eq!(triggers.len(), 1);
167        assert_eq!(triggers[0].subject, 1);
168
169        let no_triggers = registry.evaluate_triggers_at(0x999);
170        assert_eq!(no_triggers.len(), 0);
171    }
172
173    #[test]
174    fn test_location_trigger_engine_rcc8_containment() {
175        let mut engine = LocationTriggerEngine::new();
176        let region = 0xDEAD_BEEF;
177        let location = 0xCAFE_BABE;
178
179        let rule = NQuin {
180            subject: 10,
181            predicate: 20,
182            object: 30,
183            context: 0,
184            metadata: 0,
185            parity: 0,
186        };
187        engine.register_trigger(region, rule);
188
189        let boundary = q_hash("spatial:boundary");
190        let location_point = q_hash("q42:locationPoint");
191
192        // Square region containing the point (0.5, 0.5)
193        let region_quins = [
194            boundary_quin(region, boundary, 0, (0.0, 0.0)),
195            boundary_quin(region, boundary, 1, (2.0, 0.0)),
196            boundary_quin(region, boundary, 2, (2.0, 2.0)),
197            boundary_quin(region, boundary, 3, (0.0, 2.0)),
198        ];
199
200        let mut loc_quin = NQuin {
201            subject: location,
202            predicate: location_point,
203            object: spatio_temporal::pack_point(0.5, 0.5),
204            context: 0,
205            metadata: 0,
206            parity: 0,
207        };
208        loc_quin.parity =
209            loc_quin.subject ^ loc_quin.predicate ^ loc_quin.object ^ loc_quin.context;
210
211        let mut arena: Vec<NQuin> = region_quins.to_vec();
212        arena.push(loc_quin);
213
214        let triggers = engine.fire_triggers_at(location, &arena);
215        assert_eq!(triggers.len(), 1);
216        assert_eq!(triggers[0].subject, 10);
217    }
218
219    fn boundary_quin(region: u64, pred: u64, seq: u32, pt: (f64, f64)) -> NQuin {
220        let mut q = NQuin {
221            subject: region,
222            predicate: pred,
223            object: spatio_temporal::pack_point(pt.0, pt.1),
224            context: 0,
225            metadata: seq as u64,
226            parity: 0,
227        };
228        q.parity = q.subject ^ q.predicate ^ q.object ^ q.context;
229        q
230    }
231}