1use crate::frame_layout::DEFEATER_BIT;
12use crate::modalities::manifold::ManifoldCoordinate10D;
13use crate::modalities::spatio_temporal::TemporalOp;
14use crate::{q_hash, NQuin};
15
16pub const OP_SCENE_PLAY_PRESET: u8 = 0x70;
17pub const OP_SCENE_BLEND_SUBPART: u8 = 0x71;
18pub const OP_SCENE_PREDICATE_TRIGGER: u8 = 0x72;
19pub const OP_SCENE_DEFEATER_CANCEL: u8 = 0x73;
20
21pub const CBOR_LD_SCENE_MAGIC: [u8; 4] = [0xD9, 0x05, 0x01, 0xA4];
22
23#[derive(Clone, Copy, Debug, PartialEq)]
25pub enum SceneSliceScope {
26 WholeScene,
28 Topic(u64),
30 SubjectClass(u64),
32 ManifoldNeighborhood {
34 center: [f32; 3],
35 radius: f32,
36 min_epistemic_weight: f32,
37 },
38}
39
40#[repr(C)]
42#[derive(Clone, Copy, Debug, PartialEq)]
43pub struct AssetStateNode {
44 pub entity_did: u64,
45 pub class_hash: u64,
46 pub topic_hash: u64,
47 pub position: [f32; 3],
48 pub manifold: ManifoldCoordinate10D,
49 pub active_preset_hash: u64,
50 pub active_subpart_hash: u64,
51 pub remaining_duration_ms: u32,
52}
53
54#[repr(C)]
56#[derive(Clone, Copy, Debug, PartialEq)]
57pub struct PredicateTriggerRule {
58 pub trigger_event_hash: u64,
59 pub target_class_hash: u64,
60 pub target_topic_hash: u64,
61 pub target_subpart_hash: u64,
62 pub preset_hash: u64,
63 pub follow_up_preset_hash: u64,
64 pub temporal_op: TemporalOp,
65 pub max_radius_m: f32,
66 pub propagation_speed_mps: f32,
67 pub duration_ms: u16,
68 pub blend_in_ms: u8,
69 pub amplitude_u8: u8,
70}
71
72#[repr(C)]
74#[derive(Clone, Copy, Debug, PartialEq, Eq)]
75pub struct ScheduledPresetCommand {
76 pub entity_did: u64,
77 pub subpart_hash: u64,
78 pub preset_hash: u64,
79 pub follow_up_preset_hash: u64,
80 pub temporal_op: TemporalOp,
81 pub delay_ms: u32,
82 pub duration_ms: u16,
83 pub blend_in_ms: u8,
84 pub amplitude_u8: u8,
85 pub command_quin: NQuin,
86}
87
88#[repr(C)]
90#[derive(Clone, Copy, Debug, PartialEq, Eq)]
91pub struct P64ExtensionSlot {
92 pub vendor_model_hash: u64,
93 pub architecture_id: u32,
94 pub has_recurrent_state_seed: bool,
95 pub has_kv_prefix: bool,
96 pub has_ple_table: bool,
97 pub has_lora_weights: bool,
98 pub byte_offset: u64,
99 pub byte_len: u64,
100}
101
102#[derive(Clone, Copy, Debug, PartialEq, Eq)]
103pub enum SceneGraphError {
104 OutputBufferTooSmall,
105 InvalidCborLdHeader,
106 TruncatedCborLdPayload,
107}
108
109#[inline]
110fn dist_3d(a: [f32; 3], b: [f32; 3]) -> f32 {
111 let dx = a[0] - b[0];
112 let dy = a[1] - b[1];
113 let dz = a[2] - b[2];
114 (dx * dx + dy * dy + dz * dz).sqrt()
115}
116
117#[inline]
118fn temporal_op_code(op: TemporalOp) -> u8 {
119 match op {
120 TemporalOp::Before => 1,
121 TemporalOp::Meets => 2,
122 TemporalOp::Overlaps => 3,
123 TemporalOp::Starts => 4,
124 TemporalOp::During => 5,
125 TemporalOp::Finishes => 6,
126 TemporalOp::Equals => 7,
127 }
128}
129
130#[inline]
131fn temporal_op_from_code(code: u8) -> TemporalOp {
132 match code {
133 1 => TemporalOp::Before,
134 2 => TemporalOp::Meets,
135 3 => TemporalOp::Overlaps,
136 4 => TemporalOp::Starts,
137 5 => TemporalOp::During,
138 6 => TemporalOp::Finishes,
139 _ => TemporalOp::Equals,
140 }
141}
142
143#[must_use]
145pub fn pack_preset_command_quin(
146 entity_did: u64,
147 subpart_hash: u64,
148 preset_hash: u64,
149 temporal_op: TemporalOp,
150 duration_ms: u16,
151 blend_in_ms: u8,
152 amplitude_u8: u8,
153 scene_context_hash: u64,
154 lamport_clock: u32,
155) -> NQuin {
156 let subject = entity_did & 0x7FFF_FFFF_FFFF_FFFF;
157 let pred_hash = (subpart_hash & 0x007F_FFFF_FFFF_FFFF) << 16;
158 let t_code = (temporal_op_code(temporal_op) as u64) << 8;
159 let predicate = pred_hash | t_code | (OP_SCENE_PLAY_PRESET as u64);
160 let object = preset_hash & 0x0FFF_FFFF_FFFF_FFFF;
161 let context = scene_context_hash & 0x00FF_FFFF_FFFF_FFFF;
162 let payload = ((duration_ms as u64) << 16)
163 | ((blend_in_ms as u64) << 8)
164 | (amplitude_u8 as u64);
165 let clock = ((lamport_clock & 0x1FFF_FFFF) as u64) << 32;
166 let metadata = clock | payload;
167 let parity = subject ^ predicate ^ object ^ context;
168 NQuin {
169 subject,
170 predicate,
171 object,
172 context,
173 metadata,
174 parity,
175 }
176}
177
178#[must_use]
180pub fn pack_preset_defeater_quin(
181 entity_did: u64,
182 preset_hash: u64,
183 scene_context_hash: u64,
184 lamport_clock: u32,
185) -> NQuin {
186 let subject = entity_did & 0x7FFF_FFFF_FFFF_FFFF;
187 let predicate = DEFEATER_BIT | (OP_SCENE_DEFEATER_CANCEL as u64);
188 let object = preset_hash & 0x0FFF_FFFF_FFFF_FFFF;
189 let context = scene_context_hash & 0x00FF_FFFF_FFFF_FFFF;
190 let metadata = ((lamport_clock & 0x1FFF_FFFF) as u64) << 32;
191 let parity = subject ^ predicate ^ object ^ context;
192 NQuin {
193 subject,
194 predicate,
195 object,
196 context,
197 metadata,
198 parity,
199 }
200}
201
202pub fn slice_scene_state_graph(
204 assets: &[AssetStateNode],
205 scope: SceneSliceScope,
206 out_indices: &mut [usize],
207) -> Result<usize, SceneGraphError> {
208 let mut written = 0usize;
209 for (idx, asset) in assets.iter().enumerate() {
210 let matches = match scope {
211 SceneSliceScope::WholeScene => true,
212 SceneSliceScope::Topic(t) => t == 0 || asset.topic_hash == t,
213 SceneSliceScope::SubjectClass(c) => c == 0 || asset.class_hash == c,
214 SceneSliceScope::ManifoldNeighborhood {
215 center,
216 radius,
217 min_epistemic_weight,
218 } => {
219 dist_3d(asset.position, center) <= radius
220 && asset.manifold.epistemic_weight >= min_epistemic_weight
221 }
222 };
223 if matches {
224 if written >= out_indices.len() {
225 return Err(SceneGraphError::OutputBufferTooSmall);
226 }
227 out_indices[written] = idx;
228 written += 1;
229 }
230 }
231 Ok(written)
232}
233
234#[allow(clippy::too_many_arguments)]
237pub fn evaluate_predicate_triggers_zero_heap(
238 assets: &[AssetStateNode],
239 rules: &[PredicateTriggerRule],
240 defeater_quins: &[NQuin],
241 trigger_event_hash: u64,
242 trigger_origin: [f32; 3],
243 scene_context_hash: u64,
244 lamport_clock: u32,
245 out_commands: &mut [ScheduledPresetCommand],
246) -> Result<usize, SceneGraphError> {
247 let mut count = 0usize;
248 for rule in rules {
249 if rule.trigger_event_hash != 0 && rule.trigger_event_hash != trigger_event_hash {
250 continue;
251 }
252 for asset in assets {
253 if rule.target_class_hash != 0 && asset.class_hash != rule.target_class_hash {
254 continue;
255 }
256 if rule.target_topic_hash != 0 && asset.topic_hash != rule.target_topic_hash {
257 continue;
258 }
259 let d = dist_3d(asset.position, trigger_origin);
260 if rule.max_radius_m > 0.0 && d > rule.max_radius_m {
261 continue;
262 }
263 let masked_entity = asset.entity_did & 0x7FFF_FFFF_FFFF_FFFF;
264 let masked_preset = rule.preset_hash & 0x0FFF_FFFF_FFFF_FFFF;
265 let is_defeated = defeater_quins.iter().any(|q| {
266 (q.predicate & DEFEATER_BIT) != 0
267 && (q.subject & 0x7FFF_FFFF_FFFF_FFFF) == masked_entity
268 && (q.object == 0 || (q.object & 0x0FFF_FFFF_FFFF_FFFF) == masked_preset)
269 });
270 if is_defeated {
271 continue;
272 }
273 if count >= out_commands.len() {
274 return Err(SceneGraphError::OutputBufferTooSmall);
275 }
276 let delay_ms = if rule.propagation_speed_mps > 0.0 {
277 ((d / rule.propagation_speed_mps) * 1000.0).round() as u32
278 } else {
279 0
280 };
281 let command_quin = pack_preset_command_quin(
282 asset.entity_did,
283 rule.target_subpart_hash,
284 rule.preset_hash,
285 rule.temporal_op,
286 rule.duration_ms,
287 rule.blend_in_ms,
288 rule.amplitude_u8,
289 scene_context_hash,
290 lamport_clock,
291 );
292 out_commands[count] = ScheduledPresetCommand {
293 entity_did: asset.entity_did,
294 subpart_hash: rule.target_subpart_hash,
295 preset_hash: rule.preset_hash,
296 follow_up_preset_hash: rule.follow_up_preset_hash,
297 temporal_op: rule.temporal_op,
298 delay_ms,
299 duration_ms: rule.duration_ms,
300 blend_in_ms: rule.blend_in_ms,
301 amplitude_u8: rule.amplitude_u8,
302 command_quin,
303 };
304 count += 1;
305 }
306 }
307 Ok(count)
308}
309
310pub fn encode_scene_slice_cbor_ld_into(
313 assets: &[AssetStateNode],
314 slice_indices: &[usize],
315 out_bytes: &mut [u8],
316) -> Result<usize, SceneGraphError> {
317 const RECORD_BYTES: usize = 44;
318 let needed = 8 + slice_indices.len() * RECORD_BYTES;
319 if out_bytes.len() < needed {
320 return Err(SceneGraphError::OutputBufferTooSmall);
321 }
322 out_bytes[0..4].copy_from_slice(&CBOR_LD_SCENE_MAGIC);
323 out_bytes[4..8].copy_from_slice(&(slice_indices.len() as u32).to_le_bytes());
324 let mut off = 8usize;
325 for &idx in slice_indices {
326 let a = &assets[idx];
327 out_bytes[off..off + 8].copy_from_slice(&a.entity_did.to_le_bytes());
328 out_bytes[off + 8..off + 16].copy_from_slice(&a.class_hash.to_le_bytes());
329 out_bytes[off + 16..off + 24].copy_from_slice(&a.topic_hash.to_le_bytes());
330 out_bytes[off + 24..off + 28].copy_from_slice(&a.position[0].to_le_bytes());
331 out_bytes[off + 28..off + 32].copy_from_slice(&a.position[1].to_le_bytes());
332 out_bytes[off + 32..off + 36].copy_from_slice(&a.position[2].to_le_bytes());
333 out_bytes[off + 36..off + 44].copy_from_slice(&a.active_preset_hash.to_le_bytes());
334 off += RECORD_BYTES;
335 }
336 Ok(off)
337}
338
339pub fn decode_trigger_rules_cbor_ld_into(
341 src: &[u8],
342 out_rules: &mut [PredicateTriggerRule],
343) -> Result<usize, SceneGraphError> {
344 const RULE_BYTES: usize = 60;
345 if src.len() < 8 || src[0..4] != CBOR_LD_SCENE_MAGIC {
346 return Err(SceneGraphError::InvalidCborLdHeader);
347 }
348 let count = u32::from_le_bytes(src[4..8].try_into().unwrap_or([0; 4])) as usize;
349 if src.len() < 8 + count * RULE_BYTES {
350 return Err(SceneGraphError::TruncatedCborLdPayload);
351 }
352 if count > out_rules.len() {
353 return Err(SceneGraphError::OutputBufferTooSmall);
354 }
355 for i in 0..count {
356 let base = 8 + i * RULE_BYTES;
357 let u64_at = |o: usize| u64::from_le_bytes(src[base + o..base + o + 8].try_into().unwrap());
358 let f32_at = |o: usize| f32::from_le_bytes(src[base + o..base + o + 4].try_into().unwrap());
359 out_rules[i] = PredicateTriggerRule {
360 trigger_event_hash: u64_at(0),
361 target_class_hash: u64_at(8),
362 target_topic_hash: u64_at(16),
363 target_subpart_hash: u64_at(24),
364 preset_hash: u64_at(32),
365 follow_up_preset_hash: u64_at(40),
366 max_radius_m: f32_at(48),
367 propagation_speed_mps: f32_at(52),
368 duration_ms: u16::from_le_bytes(src[base + 56..base + 58].try_into().unwrap()),
369 blend_in_ms: src[base + 58],
370 amplitude_u8: temporal_op_code(temporal_op_from_code(src[base + 59])),
371 temporal_op: temporal_op_from_code(src[base + 59]),
372 };
373 }
374 Ok(count)
375}
376
377#[must_use]
380pub fn select_p64_vendor_slot<'a>(
381 slots: &'a [P64ExtensionSlot],
382 preferred_model_id: &str,
383 architecture_id: u32,
384) -> Option<&'a P64ExtensionSlot> {
385 let target_hash = q_hash(preferred_model_id);
386 if let Some(exact) = slots.iter().find(|s| s.vendor_model_hash == target_hash) {
387 return Some(exact);
388 }
389 slots
390 .iter()
391 .find(|s| s.architecture_id != 0 && s.architecture_id == architecture_id)
392}
393
394#[cfg(test)]
395mod tests {
396 use super::*;
397
398 #[test]
399 fn manifold_slice_and_predicate_broadcast_trigger_across_assets() {
400 let class_macropod = q_hash("Fauna:Macropod");
401 let class_tree = q_hash("Flora:Corymbia");
402 let topic_alert = q_hash("topic:acoustic_alert");
403 let event_thump = q_hash("event:hindfoot_alarm_thump");
404 let subpart_ears = q_hash("subpart:pinnae_both");
405 let preset_ear_swivel = q_hash("preset:ear_radar_swivel");
406 let preset_bound = q_hash("preset:saltatorial_bound");
407
408 let mut m_high = ManifoldCoordinate10D::default();
409 m_high.epistemic_weight = 0.9;
410
411 let assets = [
412 AssetStateNode {
413 entity_did: q_hash("did:q42:wallaby_01"),
414 class_hash: class_macropod,
415 topic_hash: topic_alert,
416 position: [10.0, 0.0, 0.0],
417 manifold: m_high,
418 active_preset_hash: 0,
419 active_subpart_hash: 0,
420 remaining_duration_ms: 0,
421 },
422 AssetStateNode {
423 entity_did: q_hash("did:q42:wallaby_02"),
424 class_hash: class_macropod,
425 topic_hash: topic_alert,
426 position: [34.3, 0.0, 0.0],
427 manifold: m_high,
428 active_preset_hash: 0,
429 active_subpart_hash: 0,
430 remaining_duration_ms: 0,
431 },
432 AssetStateNode {
433 entity_did: q_hash("did:q42:corymbia_01"),
434 class_hash: class_tree,
435 topic_hash: topic_alert,
436 position: [5.0, 0.0, 0.0],
437 manifold: m_high,
438 active_preset_hash: 0,
439 active_subpart_hash: 0,
440 remaining_duration_ms: 0,
441 },
442 ];
443
444 let mut slice_idx = [0usize; 8];
445 let n_sliced = slice_scene_state_graph(
446 &assets,
447 SceneSliceScope::ManifoldNeighborhood {
448 center: [0.0, 0.0, 0.0],
449 radius: 40.0,
450 min_epistemic_weight: 0.5,
451 },
452 &mut slice_idx,
453 )
454 .unwrap();
455 assert_eq!(n_sliced, 3);
456
457 let mut cbor_buf = [0u8; 256];
458 let bytes_written =
459 encode_scene_slice_cbor_ld_into(&assets, &slice_idx[..n_sliced], &mut cbor_buf)
460 .unwrap();
461 assert_eq!(bytes_written, 8 + 3 * 44);
462
463 let rules = [PredicateTriggerRule {
464 trigger_event_hash: event_thump,
465 target_class_hash: class_macropod,
466 target_topic_hash: topic_alert,
467 target_subpart_hash: subpart_ears,
468 preset_hash: preset_ear_swivel,
469 follow_up_preset_hash: preset_bound,
470 temporal_op: TemporalOp::Meets,
471 max_radius_m: 50.0,
472 propagation_speed_mps: 343.0,
473 duration_ms: 4000,
474 blend_in_ms: 120,
475 amplitude_u8: 255,
476 }];
477
478 let mut cmds = [ScheduledPresetCommand {
479 entity_did: 0,
480 subpart_hash: 0,
481 preset_hash: 0,
482 follow_up_preset_hash: 0,
483 temporal_op: TemporalOp::Equals,
484 delay_ms: 0,
485 duration_ms: 0,
486 blend_in_ms: 0,
487 amplitude_u8: 0,
488 command_quin: NQuin::default(),
489 }; 8];
490
491 let fired = evaluate_predicate_triggers_zero_heap(
492 &assets,
493 &rules,
494 &[],
495 event_thump,
496 [0.0, 0.0, 0.0],
497 q_hash("scene:bushland_01"),
498 1,
499 &mut cmds,
500 )
501 .unwrap();
502 assert_eq!(fired, 2);
503 assert_eq!(cmds[0].delay_ms, 29);
504 assert_eq!(cmds[1].delay_ms, 100);
505 assert_eq!(
506 cmds[0].command_quin.parity,
507 cmds[0].command_quin.subject
508 ^ cmds[0].command_quin.predicate
509 ^ cmds[0].command_quin.object
510 ^ cmds[0].command_quin.context
511 );
512
513 let defeater = [pack_preset_defeater_quin(
515 assets[1].entity_did,
516 preset_ear_swivel,
517 q_hash("scene:bushland_01"),
518 2,
519 )];
520 let fired_after_defeat = evaluate_predicate_triggers_zero_heap(
521 &assets,
522 &rules,
523 &defeater,
524 event_thump,
525 [0.0, 0.0, 0.0],
526 q_hash("scene:bushland_01"),
527 2,
528 &mut cmds,
529 )
530 .unwrap();
531 assert_eq!(fired_after_defeat, 1);
532 assert_eq!(cmds[0].entity_did, assets[0].entity_did);
533 }
534
535 #[test]
536 fn p64_vendor_slot_selection_and_tier0_fallback() {
537 let slots = [
538 P64ExtensionSlot {
539 vendor_model_hash: q_hash("qwen3.5:0.8b"),
540 architecture_id: 10,
541 has_recurrent_state_seed: true,
542 has_kv_prefix: true,
543 has_ple_table: false,
544 has_lora_weights: true,
545 byte_offset: 4096,
546 byte_len: 1048576,
547 },
548 P64ExtensionSlot {
549 vendor_model_hash: q_hash("gemma4:e4b"),
550 architecture_id: 20,
551 has_recurrent_state_seed: false,
552 has_kv_prefix: true,
553 has_ple_table: true,
554 has_lora_weights: false,
555 byte_offset: 2097152,
556 byte_len: 524288,
557 },
558 ];
559 let matched = select_p64_vendor_slot(&slots, "qwen3.5:0.8b", 10).unwrap();
560 assert!(matched.has_recurrent_state_seed);
561 assert!(select_p64_vendor_slot(&slots, "gemini:2.5-flash", 99).is_none());
562 }
563}