qualia_core_db/container_10d/
entity_ontology_section.rs1use bytemuck::{Pod, Zeroable};
10
11use crate::entity_view::entity_ontologies::EntityOntology;
12
13pub const ENTITY_ONTOLOGY_SECTION_VERSION: u16 = 1;
14pub const ENTITY_ONTOLOGY_MINI_HEADER_SIZE: usize = 40;
15pub const AFFORDANCE_RECORD_SIZE: usize = 48;
16pub const MAX_AFFORDANCES_PER_SECTION: usize = 256;
17pub const MAGIC_EONT: [u8; 4] = *b"EONT";
18
19pub const PERSONAL_ONTOLOGY_SECTION_VERSION: u16 = ENTITY_ONTOLOGY_SECTION_VERSION;
21pub const PERSONAL_ONTOLOGY_MINI_HEADER_SIZE: usize = ENTITY_ONTOLOGY_MINI_HEADER_SIZE;
22pub const MAGIC_PONT: [u8; 4] = MAGIC_EONT;
23
24pub use etalon_render::skeletal::OntogeneticStateHeader as EntityOntologyMiniHeader;
26const _: [(); ENTITY_ONTOLOGY_MINI_HEADER_SIZE] =
27 [(); core::mem::size_of::<EntityOntologyMiniHeader>()];
28
29pub type PersonalOntologyMiniHeader = EntityOntologyMiniHeader;
30
31#[repr(C)]
33#[derive(Debug, Clone, Copy, PartialEq, Eq, Pod, Zeroable)]
34pub struct AffordanceBinaryRecord {
35 pub action_id: u64,
36 pub required_capability_hash: u64,
37 pub emitted_topic_hash: u64,
38 pub category: u8,
39 pub min_observer_status: u8,
40 pub min_energy_permill: u16,
41 pub max_damage_permill: u16,
42 pub min_hydration_permill: u16,
43 pub max_wear_permill: u16,
44 pub energy_delta: i16,
45 pub damage_delta: i16,
46 pub hydration_delta: i16,
47 pub wear_delta: i16,
48 pub reserved_u16: u16,
49 pub animation_clip_id: u32,
50}
51const _: [(); AFFORDANCE_RECORD_SIZE] = [(); core::mem::size_of::<AffordanceBinaryRecord>()];
52
53pub const DEVELOPMENTAL_KEYFRAME_RECORD_SIZE: usize = 32;
54
55#[repr(C)]
57#[derive(Debug, Clone, Copy, PartialEq, Pod, Zeroable)]
58pub struct DevelopmentalKeyframeRecord {
59 pub age_days: f32,
61 pub stage: u8,
63 pub reserved_u8: u8,
64 pub reserved_u16: u16,
65 pub allometric_crown_scale: f32,
67 pub allometric_trunk_scale: f32,
69 pub lai_multiplier: f32,
71 pub reserved_u32: u32,
72 pub mesh_asset_hash: u64,
74}
75const _: [(); DEVELOPMENTAL_KEYFRAME_RECORD_SIZE] =
76 [(); core::mem::size_of::<DevelopmentalKeyframeRecord>()];
77
78#[derive(Debug, Clone, PartialEq, Eq)]
79pub enum EntityOntologySectionError {
80 PayloadTooShort {
81 need: usize,
82 have: usize,
83 },
84 BadMagic([u8; 4]),
85 UnsupportedVersion(u16),
86 TooManyAffordances {
87 count: usize,
88 max: usize,
89 },
90 BufferTooSmall {
91 need: usize,
92 have: usize,
93 },
94 LengthMismatch {
95 header_len: usize,
96 payload_len: usize,
97 },
98}
99
100pub type PersonalOntologySectionError = EntityOntologySectionError;
101
102impl std::fmt::Display for EntityOntologySectionError {
103 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
104 match self {
105 Self::PayloadTooShort { need, have } => {
106 write!(
107 f,
108 "entity ontology section too short: have {have}, need {need}"
109 )
110 }
111 Self::BadMagic(m) => write!(f, "bad entity ontology magic: {m:?}"),
112 Self::UnsupportedVersion(v) => write!(f, "unsupported entity ontology version {v}"),
113 Self::TooManyAffordances { count, max } => {
114 write!(f, "too many affordances: {count} > {max}")
115 }
116 Self::BufferTooSmall { need, have } => {
117 write!(f, "destination buffer too small: have {have}, need {need}")
118 }
119 Self::LengthMismatch {
120 header_len,
121 payload_len,
122 } => {
123 write!(
124 f,
125 "length mismatch: expected {header_len}, payload {payload_len}"
126 )
127 }
128 }
129 }
130}
131
132impl std::error::Error for EntityOntologySectionError {}
133
134#[inline]
136pub fn entity_ontology_encoded_len(affordance_count: usize) -> usize {
137 ENTITY_ONTOLOGY_MINI_HEADER_SIZE + (affordance_count * AFFORDANCE_RECORD_SIZE)
138}
139
140pub use entity_ontology_encoded_len as personal_ontology_encoded_len;
141
142pub fn encode_entity_ontology_section(
144 onto: &EntityOntology,
145 taxon_hash: u64,
146 out: &mut [u8],
147) -> Result<usize, EntityOntologySectionError> {
148 let count = onto.affordances.len();
149 if count > MAX_AFFORDANCES_PER_SECTION {
150 return Err(EntityOntologySectionError::TooManyAffordances {
151 count,
152 max: MAX_AFFORDANCES_PER_SECTION,
153 });
154 }
155
156 let needed = entity_ontology_encoded_len(count);
157 if out.len() < needed {
158 return Err(EntityOntologySectionError::BufferTooSmall {
159 need: needed,
160 have: out.len(),
161 });
162 }
163
164 let header = EntityOntologyMiniHeader {
165 magic: MAGIC_EONT,
166 version: ENTITY_ONTOLOGY_SECTION_VERSION,
167 stage: onto.stage as u8,
168 reserved_u8: 0,
169 entity_did_hash: onto.entity_id.0,
170 taxon_iri_hash: taxon_hash,
171 energy_permill: onto.energy_permill,
172 damage_permill: onto.damage_permill,
173 hydration_permill: onto.hydration_permill,
174 wear_permill: onto.wear_permill,
175 affordance_count: count as u32,
176 reserved_u32: 0,
177 };
178
179 let header_bytes = bytemuck::bytes_of(&header);
180 out[..ENTITY_ONTOLOGY_MINI_HEADER_SIZE].copy_from_slice(header_bytes);
181
182 let mut cursor = ENTITY_ONTOLOGY_MINI_HEADER_SIZE;
183 for aff in &onto.affordances {
184 let rec = AffordanceBinaryRecord {
185 action_id: aff.action_id,
186 required_capability_hash: aff.preconditions.required_capability_hash,
187 emitted_topic_hash: aff.effects.emitted_topic_hash,
188 category: aff.category as u8,
189 min_observer_status: aff.preconditions.min_observer_status as u8,
190 min_energy_permill: aff.preconditions.min_energy_permill,
191 max_damage_permill: aff.preconditions.max_damage_permill,
192 min_hydration_permill: aff.preconditions.min_hydration_permill,
193 max_wear_permill: aff.preconditions.max_wear_permill,
194 energy_delta: aff.effects.energy_delta,
195 damage_delta: aff.effects.damage_delta,
196 hydration_delta: aff.effects.hydration_delta,
197 wear_delta: aff.effects.wear_delta,
198 reserved_u16: 0,
199 animation_clip_id: aff.effects.animation_clip_id,
200 };
201 let rec_bytes = bytemuck::bytes_of(&rec);
202 out[cursor..cursor + AFFORDANCE_RECORD_SIZE].copy_from_slice(rec_bytes);
203 cursor += AFFORDANCE_RECORD_SIZE;
204 }
205
206 Ok(needed)
207}
208
209pub use encode_entity_ontology_section as encode_personal_ontology_section;
210
211pub fn decode_entity_ontology_section_into<'a>(
214 payload: &'a [u8],
215 out_records: &mut [AffordanceBinaryRecord],
216) -> Result<(EntityOntologyMiniHeader, usize), EntityOntologySectionError> {
217 if payload.len() < ENTITY_ONTOLOGY_MINI_HEADER_SIZE {
218 return Err(EntityOntologySectionError::PayloadTooShort {
219 need: ENTITY_ONTOLOGY_MINI_HEADER_SIZE,
220 have: payload.len(),
221 });
222 }
223
224 let header: EntityOntologyMiniHeader =
225 bytemuck::pod_read_unaligned(&payload[..ENTITY_ONTOLOGY_MINI_HEADER_SIZE]);
226
227 if header.magic != MAGIC_EONT && header.magic != *b"PONT" {
228 return Err(EntityOntologySectionError::BadMagic(header.magic));
229 }
230 if header.version != ENTITY_ONTOLOGY_SECTION_VERSION {
231 return Err(EntityOntologySectionError::UnsupportedVersion(
232 header.version,
233 ));
234 }
235
236 let count = header.affordance_count as usize;
237 if count > MAX_AFFORDANCES_PER_SECTION {
238 return Err(EntityOntologySectionError::TooManyAffordances {
239 count,
240 max: MAX_AFFORDANCES_PER_SECTION,
241 });
242 }
243
244 let expected_len = entity_ontology_encoded_len(count);
245 if payload.len() != expected_len {
246 return Err(EntityOntologySectionError::LengthMismatch {
247 header_len: expected_len,
248 payload_len: payload.len(),
249 });
250 }
251
252 if out_records.len() < count {
253 return Err(EntityOntologySectionError::BufferTooSmall {
254 need: count,
255 have: out_records.len(),
256 });
257 }
258
259 for (index, record) in out_records[..count].iter_mut().enumerate() {
260 let start = ENTITY_ONTOLOGY_MINI_HEADER_SIZE + index * AFFORDANCE_RECORD_SIZE;
261 *record = bytemuck::pod_read_unaligned(&payload[start..start + AFFORDANCE_RECORD_SIZE]);
262 }
263
264 Ok((header, count))
265}
266
267pub use decode_entity_ontology_section_into as decode_personal_ontology_section_into;
268
269#[cfg(test)]
270mod tests {
271 use super::*;
272 use crate::entity_view::entity_ontologies::{
273 ActionAffordance, AffordanceCategory, LifecycleStage,
274 };
275 use crate::entity_view::{EntityId, ObserverStatus};
276
277 #[test]
278 fn entity_ontology_section_roundtrips() {
279 let entity_id = EntityId::from_u64(0xFEED_FACE_CAFE_BEEF);
280 let mut onto = EntityOntology::new(entity_id, "qualia:TestEntity");
281 onto.stage = LifecycleStage::Juvenile;
282 onto.energy_permill = 950;
283 onto.damage_permill = 15;
284 onto.hydration_permill = 880;
285 onto.wear_permill = 40;
286
287 let mut a1 = ActionAffordance::new(
288 "graze",
289 "Consume pasture grass",
290 AffordanceCategory::Biological,
291 );
292 a1.preconditions.min_observer_status = ObserverStatus::Public;
293 a1.preconditions.min_energy_permill = 100;
294 a1.effects.energy_delta = 250;
295 a1.effects.animation_clip_id = 7;
296 onto.add_affordance(a1);
297
298 let mut a2 = ActionAffordance::new(
299 "flee",
300 "Emergency evasive sprint",
301 AffordanceCategory::Physical,
302 );
303 a2.preconditions.min_energy_permill = 300;
304 a2.effects.energy_delta = -200;
305 a2.effects.animation_clip_id = 12;
306 onto.add_affordance(a2);
307
308 let mut buffer = [0u8; 512];
309 let bytes_written =
310 encode_entity_ontology_section(&onto, 0x9988_7766, &mut buffer).unwrap();
311 assert_eq!(
312 bytes_written,
313 ENTITY_ONTOLOGY_MINI_HEADER_SIZE + 2 * AFFORDANCE_RECORD_SIZE
314 );
315
316 let mut decoded_records = [AffordanceBinaryRecord::zeroed(); 4];
317 let (header, count) =
318 decode_entity_ontology_section_into(&buffer[..bytes_written], &mut decoded_records)
319 .unwrap();
320 let mut unaligned = [0u8; 513];
321 unaligned[1..1 + bytes_written].copy_from_slice(&buffer[..bytes_written]);
322 assert_eq!(
323 decode_entity_ontology_section_into(
324 &unaligned[1..1 + bytes_written],
325 &mut decoded_records
326 )
327 .unwrap()
328 .1,
329 count
330 );
331
332 assert_eq!(header.magic, MAGIC_EONT);
333 assert_eq!(header.version, 1);
334 assert_eq!(header.stage, LifecycleStage::Juvenile as u8);
335 assert_eq!(header.entity_did_hash, 0xFEED_FACE_CAFE_BEEF);
336 assert_eq!(header.energy_permill, 950);
337 assert_eq!(header.damage_permill, 15);
338 assert_eq!(count, 2);
339
340 assert_eq!(decoded_records[0].action_id, onto.affordances[0].action_id);
341 assert_eq!(
342 decoded_records[0].category,
343 AffordanceCategory::Biological as u8
344 );
345 assert_eq!(decoded_records[0].energy_delta, 250);
346 assert_eq!(decoded_records[0].animation_clip_id, 7);
347
348 assert_eq!(decoded_records[1].action_id, onto.affordances[1].action_id);
349 assert_eq!(
350 decoded_records[1].category,
351 AffordanceCategory::Physical as u8
352 );
353 assert_eq!(decoded_records[1].energy_delta, -200);
354 assert_eq!(decoded_records[1].animation_clip_id, 12);
355 }
356}