Skip to main content

qualia_core_db/entity_view/
ethogram.rs

1//! Canonical Ethogram Registry & Behavioral State Machine Kernel (WP-2.1).
2//!
3//! Formalizes the binding between:
4//! 1. `EONT1` binary affordance tables ([`crate::container_10d::entity_ontology_section`])
5//! 2. `.vibe` HFSM behavioral rules (stimulus events, internal drive thresholds)
6//! 3. `SKL1` skeletal animation motor clips ([`crate::container_10d::skeletal_section`])
7//!
8//! Zero-heap on hot query and tick paths.
9
10use bytemuck::{Pod, Zeroable};
11use serde::{Deserialize, Serialize};
12
13/// Maximum behaviors registered in a single compact entity ethogram.
14pub const MAX_ETHOGRAM_BEHAVIORS: usize = 32;
15
16/// Stimulus topic categories driving animal ethology and plant tropisms.
17#[repr(u8)]
18#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
19pub enum StimulusCategory {
20    #[default]
21    AmbientProximity = 0,
22    PredatorAlert = 1,
23    PreyOrFoodDetected = 2,
24    MatingCall = 3,
25    WeatherDrought = 4,
26    WeatherDeluge = 5,
27    WildfireSmoke = 6,
28    PhysicalContact = 7,
29    HumanObserverApproaching = 8,
30}
31
32/// An incoming environmental or sensory stimulus event.
33#[repr(C)]
34#[derive(Debug, Clone, Copy, PartialEq, Pod, Zeroable, Serialize, Deserialize)]
35pub struct StimulusEvent {
36    pub topic_hash: u64,
37    pub source_did_hash: u64,
38    pub intensity_permill: u16,
39    pub category: u8,
40    pub reserved_u8: u8,
41    pub distance_meters: f32,
42}
43
44/// Dynamic physiological internal state meters of an active entity.
45#[repr(C)]
46#[derive(Debug, Clone, Copy, PartialEq, Eq, Pod, Zeroable, Serialize, Deserialize, Default)]
47pub struct EntityPhysiologicalState {
48    pub energy_permill: u16,
49    pub damage_permill: u16,
50    pub hydration_permill: u16,
51    pub wear_permill: u16,
52    pub active_state_id: u16,
53    pub lifecycle_stage: u8,
54    pub reserved_u8: u8,
55    pub active_motor_clip_id: u32,
56}
57
58/// A fixed-stride binary entry representing one state-transition behavior in the ethogram.
59#[repr(C)]
60#[derive(Debug, Clone, Copy, PartialEq, Eq, Pod, Zeroable, Serialize, Deserialize, Default)]
61pub struct EthogramBehaviorEntry {
62    /// Action identifier (e.g. `q_hash("action:flee")`).
63    pub action_id: u64,
64    /// Stimulus topic hash that triggers this behavior.
65    pub trigger_stimulus_hash: u64,
66    /// Target behavioral state ID upon transition.
67    pub target_state_id: u16,
68    /// Required precondition flags bitmask.
69    pub precondition_mask: u16,
70    /// Target SKL1 skeletal motor clip to play.
71    pub animation_clip_id: u32,
72    /// Energy change delta permill (+/-).
73    pub energy_delta_permill: i16,
74    /// Hydration change delta permill (+/-).
75    pub hydration_delta_permill: i16,
76    /// Damage change delta permill (+/-).
77    pub damage_delta_permill: i16,
78    /// Behavioral priority (higher values preempt lower priority behaviors).
79    pub priority: u8,
80    /// Category of affordance (Physiological, Locomotion, Social, etc.).
81    pub category: u8,
82}
83
84/// Evaluated transition verdict when a stimulus triggers a behavior.
85#[derive(Debug, Clone, Copy, PartialEq, Eq)]
86pub struct TransitionVerdict {
87    /// True when a behavior transition fired (vs. no matching rule).
88    pub triggered: bool,
89    /// State id entered after the transition (unchanged when not triggered).
90    pub target_state_id: u16,
91    /// Animation clip to play for the transition (0 = none).
92    pub animation_clip_id: u32,
93    /// Energy level after applying the behavior's delta (0..1000 permill).
94    pub new_energy_permill: u16,
95    /// Hydration level after the transition.
96    pub new_hydration_permill: u16,
97    /// Damage level after the transition.
98    pub new_damage_permill: u16,
99}
100
101/// A fixed-capacity, zero-heap Ethogram Registry for an entity or taxon family.
102#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
103pub struct EthogramRegistry {
104    /// `q_hash` of the taxon/entity-family IRI this registry describes.
105    pub taxon_iri_hash: u64,
106    /// Number of live entries in `behaviors` (≤ `MAX_ETHOGRAM_BEHAVIORS`).
107    pub behavior_count: usize,
108    /// Fixed-capacity entry table; only the first `behavior_count` are live.
109    pub behaviors: [EthogramBehaviorEntry; MAX_ETHOGRAM_BEHAVIORS],
110}
111
112impl Default for EthogramRegistry {
113    fn default() -> Self {
114        Self {
115            taxon_iri_hash: 0,
116            behavior_count: 0,
117            behaviors: [EthogramBehaviorEntry::default(); MAX_ETHOGRAM_BEHAVIORS],
118        }
119    }
120}
121
122impl EthogramRegistry {
123    /// Create an empty registry for a taxon (all `MAX_ETHOGRAM_BEHAVIORS`
124    /// slots zeroed); `const` so it can live in statics.
125    pub const fn new(taxon_iri_hash: u64) -> Self {
126        Self {
127            taxon_iri_hash,
128            behavior_count: 0,
129            behaviors: [EthogramBehaviorEntry {
130                action_id: 0,
131                trigger_stimulus_hash: 0,
132                target_state_id: 0,
133                precondition_mask: 0,
134                animation_clip_id: 0,
135                energy_delta_permill: 0,
136                hydration_delta_permill: 0,
137                damage_delta_permill: 0,
138                priority: 0,
139                category: 0,
140            }; MAX_ETHOGRAM_BEHAVIORS],
141        }
142    }
143
144    /// Add a behavior entry to the registry. Returns false if registry is full.
145    pub fn add_behavior(&mut self, entry: EthogramBehaviorEntry) -> bool {
146        if self.behavior_count >= MAX_ETHOGRAM_BEHAVIORS {
147            return false;
148        }
149        self.behaviors[self.behavior_count] = entry;
150        self.behavior_count += 1;
151        true
152    }
153
154    /// Evaluate an incoming stimulus against current state in $O(1)$ zero-heap time.
155    /// Updates `current_state` in-place and returns the transition verdict.
156    pub fn evaluate_stimulus(
157        &self,
158        stimulus: &StimulusEvent,
159        current_state: &mut EntityPhysiologicalState,
160    ) -> TransitionVerdict {
161        let mut best_idx: Option<usize> = None;
162        let mut best_priority = 0u8;
163
164        for i in 0..self.behavior_count {
165            let b = &self.behaviors[i];
166            if b.trigger_stimulus_hash == stimulus.topic_hash {
167                if best_idx.is_none() || b.priority >= best_priority {
168                    best_idx = Some(i);
169                    best_priority = b.priority;
170                }
171            }
172        }
173
174        if let Some(idx) = best_idx {
175            let b = &self.behaviors[idx];
176
177            let new_energy = apply_delta(current_state.energy_permill, b.energy_delta_permill);
178            let new_hydration =
179                apply_delta(current_state.hydration_permill, b.hydration_delta_permill);
180            let new_damage = apply_delta(current_state.damage_permill, b.damage_delta_permill);
181
182            current_state.energy_permill = new_energy;
183            current_state.hydration_permill = new_hydration;
184            current_state.damage_permill = new_damage;
185            current_state.active_state_id = b.target_state_id;
186            current_state.active_motor_clip_id = b.animation_clip_id;
187
188            TransitionVerdict {
189                triggered: true,
190                target_state_id: b.target_state_id,
191                animation_clip_id: b.animation_clip_id,
192                new_energy_permill: new_energy,
193                new_hydration_permill: new_hydration,
194                new_damage_permill: new_damage,
195            }
196        } else {
197            TransitionVerdict {
198                triggered: false,
199                target_state_id: current_state.active_state_id,
200                animation_clip_id: current_state.active_motor_clip_id,
201                new_energy_permill: current_state.energy_permill,
202                new_hydration_permill: current_state.hydration_permill,
203                new_damage_permill: current_state.damage_permill,
204            }
205        }
206    }
207}
208
209#[inline]
210fn apply_delta(base: u16, delta: i16) -> u16 {
211    let result = (base as i32) + (delta as i32);
212    if result < 0 {
213        0
214    } else if result > 1000 {
215        1000
216    } else {
217        result as u16
218    }
219}
220
221#[cfg(test)]
222mod tests {
223    use super::*;
224    use crate::entity_view::entity_ontologies::{AffordanceCategory, LifecycleStage};
225
226    #[test]
227    fn test_ethogram_behavior_evaluation() {
228        let mut ethogram = EthogramRegistry::new(12345);
229        ethogram.add_behavior(EthogramBehaviorEntry {
230            action_id: 101,
231            trigger_stimulus_hash: 999, // Predator detected
232            target_state_id: 3,         // Fleeing
233            precondition_mask: 0,
234            animation_clip_id: 12, // Gallop/flee clip
235            energy_delta_permill: -50,
236            hydration_delta_permill: -30,
237            damage_delta_permill: 0,
238            priority: 10,
239            category: AffordanceCategory::Physical as u8,
240        });
241
242        let mut state = EntityPhysiologicalState {
243            energy_permill: 800,
244            damage_permill: 50,
245            hydration_permill: 600,
246            wear_permill: 0,
247            active_state_id: 1, // Grazing
248            lifecycle_stage: LifecycleStage::Adult as u8,
249            reserved_u8: 0,
250            active_motor_clip_id: 2,
251        };
252
253        let stimulus = StimulusEvent {
254            topic_hash: 999,
255            source_did_hash: 777,
256            intensity_permill: 900,
257            category: StimulusCategory::PredatorAlert as u8,
258            reserved_u8: 0,
259            distance_meters: 15.0,
260        };
261
262        let verdict = ethogram.evaluate_stimulus(&stimulus, &mut state);
263        assert!(verdict.triggered);
264        assert_eq!(verdict.target_state_id, 3);
265        assert_eq!(verdict.animation_clip_id, 12);
266        assert_eq!(state.energy_permill, 750);
267        assert_eq!(state.hydration_permill, 570);
268        assert_eq!(state.active_state_id, 3);
269    }
270}