Skip to main content

webizen_studio/render/
inspector_10d.rs

1//! Zero-Heap Live 10D / `EONT1` / `PROC1` / ABSM Inspector State (`inspector_10d.rs`)
2//!
3//! Implements Epic 9.3c of the QualiaDB Superior Game Engine architecture:
4//! - Zero-heap data model and live inspector state for inspecting and editing a selected scene node's:
5//!   1. [`Tensor10D`] (`[q, v, w, x, y, z, t, α, μ, σ]`) 10-dimensional manifold coordinate.
6//!   2. [`Epistemic10DSliceParams`] 4D/5D volumetric slice and EMF field visualization controls.
7//!   3. `.10d` `PROC1` [`ProceduralSynthesisHeader`] (cellular Voronoi, SDF smooth-fillet, allometric
8//!      power law $y = b \cdot x^k$, logarithmic spiral ODE, PGA motor harmonic oscillation, and
9//!      stress-cleavage fracture threshold).
10//!   4. `.10d` `EONT1` [`EntityOntologyMiniHeader`], [`AffordanceBinaryRecord`] table, and
11//!      [`DevelopmentalKeyframeRecord`] ontogenetic growth milestones.
12//!   5. Multi-layer ABSM animation layer weights & bone masks ([`AbsmLayerState`], up to 8 layers).
13
14use crate::render::gizmo_3d::Motor;
15
16/// Maximum affordances cached in the zero-heap studio node inspector.
17pub const MAX_INSPECTOR_AFFORDANCES: usize = 16;
18/// Maximum ontogenetic developmental keyframes cached in the zero-heap studio node inspector.
19pub const MAX_INSPECTOR_KEYFRAMES: usize = 8;
20/// Maximum ABSM animation blending layers per inspected character/entity.
21pub const MAX_INSPECTOR_ABSM_LAYERS: usize = 8;
22
23/// 10D Tensor coordinate `[q, v, w, x, y, z, t, α, μ, σ]` (40 bytes, `#[repr(C)]`).
24#[repr(C)]
25#[derive(Debug, Clone, Copy, PartialEq)]
26pub struct Tensor10D {
27    pub q: f32,
28    pub v: f32,
29    pub w: f32,
30    pub x: f32,
31    pub y: f32,
32    pub z: f32,
33    pub t: f32,
34    pub alpha: f32,
35    pub mu: f32,
36    pub sigma: f32,
37}
38
39impl Default for Tensor10D {
40    fn default() -> Self {
41        Self {
42            q: 0.0,
43            v: 0.0,
44            w: 0.0,
45            x: 0.0,
46            y: 0.0,
47            z: 0.0,
48            t: 0.0,
49            alpha: 1.0,
50            mu: 0.0,
51            sigma: 0.0,
52        }
53    }
54}
55
56impl Tensor10D {
57    #[inline]
58    pub const fn new(
59        q: f32,
60        v: f32,
61        w: f32,
62        x: f32,
63        y: f32,
64        z: f32,
65        t: f32,
66        alpha: f32,
67        mu: f32,
68        sigma: f32,
69    ) -> Self {
70        Self {
71            q,
72            v,
73            w,
74            x,
75            y,
76            z,
77            t,
78            alpha,
79            mu,
80            sigma,
81        }
82    }
83
84    /// Returns the 10 coordinates as a flat `[f32; 10]` array.
85    #[inline]
86    pub const fn to_array(self) -> [f32; 10] {
87        [
88            self.q, self.v, self.w, self.x, self.y, self.z, self.t, self.alpha, self.mu,
89            self.sigma,
90        ]
91    }
92}
93
94#[cfg(not(target_arch = "wasm32"))]
95impl From<qualia_core_db::tensor::Tensor10D> for Tensor10D {
96    #[inline]
97    fn from(t: qualia_core_db::tensor::Tensor10D) -> Self {
98        Self::new(t.q, t.v, t.w, t.x, t.y, t.z, t.t, t.alpha, t.mu, t.sigma)
99    }
100}
101
102#[cfg(not(target_arch = "wasm32"))]
103impl From<Tensor10D> for qualia_core_db::tensor::Tensor10D {
104    #[inline]
105    fn from(t: Tensor10D) -> Self {
106        Self::new(t.q, t.v, t.w, t.x, t.y, t.z, t.t, t.alpha, t.mu, t.sigma)
107    }
108}
109
110/// Volumetric 10D slice & EMF field visualization parameters (`Epistemic10D`).
111#[repr(C)]
112#[derive(Debug, Clone, Copy, PartialEq)]
113pub struct Epistemic10DSliceParams {
114    /// Active quantum superposition slice filter `q_slice` in `[0.0, 1.0]`.
115    pub q_slice: f32,
116    /// Active topological variety band `v_band` (`0=Euclidean, 1=Cyclic, 2=Hyperbolic, 3=Clique`).
117    pub v_band: f32,
118    /// Active domain manifold slice `w_manifold` (`0..=4`).
119    pub w_manifold: f32,
120    /// Coordinate time scrub position `t_scrub`.
121    pub t_scrub: f32,
122    /// Minimum salience threshold `alpha_cutoff` for volumetric raymarching.
123    pub alpha_cutoff: f32,
124    /// Spectral wavelength window `[sigma_min, sigma_max]` in nm / normalized class units.
125    pub sigma_window: [f32; 2],
126    /// Whether bilateral deontic standpoint pull (`T_pull`) is active in the viewport.
127    pub bilateral_pull_enabled: bool,
128}
129
130impl Default for Epistemic10DSliceParams {
131    fn default() -> Self {
132        Self {
133            q_slice: 0.0,
134            v_band: 0.0,
135            w_manifold: 0.0,
136            t_scrub: 0.0,
137            alpha_cutoff: 0.05,
138            sigma_window: [0.0, 1.0],
139            bilateral_pull_enabled: true,
140        }
141    }
142}
143
144/// 64-byte POD `.10d` `PROC1` (`MAGIC_PROC`) procedural synthesis header.
145#[repr(C)]
146#[derive(Debug, Clone, Copy, PartialEq)]
147pub struct ProceduralSynthesisHeader {
148    pub magic: [u8; 4],
149    pub version: u16,
150    pub flags: u16,
151    pub seed: u64,
152    pub voronoi_frequency: f32,
153    pub voronoi_jitter: f32,
154    pub fillet_blend_radius: f32,
155    pub fillet_threshold: f32,
156    pub allometry_exponent_k: f32,
157    pub allometry_base_b: f32,
158    pub spiral_growth_rate_k: f32,
159    pub spiral_initial_radius_a: f32,
160    pub motor_frequency_hz: f32,
161    pub motor_damping_ratio: f32,
162    pub critical_stress_threshold: f32,
163    pub reserved_f32: f32,
164}
165
166const _: [(); 64] = [(); core::mem::size_of::<ProceduralSynthesisHeader>()];
167
168impl Default for ProceduralSynthesisHeader {
169    fn default() -> Self {
170        Self {
171            magic: *b"PROC",
172            version: 1,
173            flags: 0x001F,
174            seed: 0x517C_C1B7_2722_0A95,
175            voronoi_frequency: 12.0,
176            voronoi_jitter: 0.8,
177            fillet_blend_radius: 0.15,
178            fillet_threshold: 0.05,
179            allometry_exponent_k: 1.25,
180            allometry_base_b: 1.0,
181            spiral_growth_rate_k: 0.18,
182            spiral_initial_radius_a: 0.10,
183            motor_frequency_hz: 1.8,
184            motor_damping_ratio: 0.12,
185            critical_stress_threshold: 50.0,
186            reserved_f32: 0.0,
187        }
188    }
189}
190
191#[cfg(not(target_arch = "wasm32"))]
192impl From<qualia_core_db::container_10d::procedural_synthesis::ProceduralSynthesisHeader>
193    for ProceduralSynthesisHeader
194{
195    #[inline]
196    fn from(
197        h: qualia_core_db::container_10d::procedural_synthesis::ProceduralSynthesisHeader,
198    ) -> Self {
199        Self {
200            magic: h.magic,
201            version: h.version,
202            flags: h.flags,
203            seed: h.seed,
204            voronoi_frequency: h.voronoi_frequency,
205            voronoi_jitter: h.voronoi_jitter,
206            fillet_blend_radius: h.fillet_blend_radius,
207            fillet_threshold: h.fillet_threshold,
208            allometry_exponent_k: h.allometry_exponent_k,
209            allometry_base_b: h.allometry_base_b,
210            spiral_growth_rate_k: h.spiral_growth_rate_k,
211            spiral_initial_radius_a: h.spiral_initial_radius_a,
212            motor_frequency_hz: h.motor_frequency_hz,
213            motor_damping_ratio: h.motor_damping_ratio,
214            critical_stress_threshold: h.critical_stress_threshold,
215            reserved_f32: h.reserved_f32,
216        }
217    }
218}
219
220#[cfg(not(target_arch = "wasm32"))]
221impl From<ProceduralSynthesisHeader>
222    for qualia_core_db::container_10d::procedural_synthesis::ProceduralSynthesisHeader
223{
224    #[inline]
225    fn from(h: ProceduralSynthesisHeader) -> Self {
226        Self {
227            magic: h.magic,
228            version: h.version,
229            flags: h.flags,
230            seed: h.seed,
231            voronoi_frequency: h.voronoi_frequency,
232            voronoi_jitter: h.voronoi_jitter,
233            fillet_blend_radius: h.fillet_blend_radius,
234            fillet_threshold: h.fillet_threshold,
235            allometry_exponent_k: h.allometry_exponent_k,
236            allometry_base_b: h.allometry_base_b,
237            spiral_growth_rate_k: h.spiral_growth_rate_k,
238            spiral_initial_radius_a: h.spiral_initial_radius_a,
239            motor_frequency_hz: h.motor_frequency_hz,
240            motor_damping_ratio: h.motor_damping_ratio,
241            critical_stress_threshold: h.critical_stress_threshold,
242            reserved_f32: h.reserved_f32,
243        }
244    }
245}
246
247/// 40-byte `.10d` `EONT1` (`MAGIC_EONT`) entity ontology mini-header.
248#[repr(C)]
249#[derive(Debug, Clone, Copy, PartialEq, Eq)]
250pub struct EntityOntologyMiniHeader {
251    pub magic: [u8; 4],
252    pub version: u16,
253    /// Developmental stage (`0=SeedOrSpore, 1=Juvenile, 2=Adult, 3=Senescent, 4=Deceased`).
254    pub stage: u8,
255    pub reserved_u8: u8,
256    pub entity_did_hash: u64,
257    pub taxon_iri_hash: u64,
258    pub energy_permill: u16,
259    pub damage_permill: u16,
260    pub hydration_permill: u16,
261    pub wear_permill: u16,
262    pub affordance_count: u32,
263    pub reserved_u32: u32,
264}
265
266const _: [(); 40] = [(); core::mem::size_of::<EntityOntologyMiniHeader>()];
267
268impl Default for EntityOntologyMiniHeader {
269    fn default() -> Self {
270        Self {
271            magic: *b"EONT",
272            version: 1,
273            stage: 2, // Adult
274            reserved_u8: 0,
275            entity_did_hash: 0,
276            taxon_iri_hash: 0,
277            energy_permill: 1000,
278            damage_permill: 0,
279            hydration_permill: 1000,
280            wear_permill: 0,
281            affordance_count: 0,
282            reserved_u32: 0,
283        }
284    }
285}
286
287/// 48-byte fixed-stride `.10d` `EONT1` affordance binary record.
288#[repr(C)]
289#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
290pub struct AffordanceBinaryRecord {
291    pub action_id: u64,
292    pub required_capability_hash: u64,
293    pub emitted_topic_hash: u64,
294    pub category: u8,
295    pub min_observer_status: u8,
296    pub min_energy_permill: u16,
297    pub max_damage_permill: u16,
298    pub min_hydration_permill: u16,
299    pub max_wear_permill: u16,
300    pub energy_delta: i16,
301    pub damage_delta: i16,
302    pub hydration_delta: i16,
303    pub wear_delta: i16,
304    pub reserved_u16: u16,
305    pub animation_clip_id: u32,
306}
307
308const _: [(); 48] = [(); core::mem::size_of::<AffordanceBinaryRecord>()];
309
310/// 32-byte fixed-stride `.10d` `EONT1` ontogenetic developmental keyframe record.
311#[repr(C)]
312#[derive(Debug, Clone, Copy, PartialEq)]
313pub struct DevelopmentalKeyframeRecord {
314    pub age_days: f32,
315    pub stage: u8,
316    pub reserved_u8: u8,
317    pub reserved_u16: u16,
318    pub allometric_crown_scale: f32,
319    pub allometric_trunk_scale: f32,
320    pub lai_multiplier: f32,
321    pub reserved_u32: u32,
322    pub mesh_asset_hash: u64,
323}
324
325const _: [(); 32] = [(); core::mem::size_of::<DevelopmentalKeyframeRecord>()];
326
327impl Default for DevelopmentalKeyframeRecord {
328    fn default() -> Self {
329        Self {
330            age_days: 0.0,
331            stage: 2,
332            reserved_u8: 0,
333            reserved_u16: 0,
334            allometric_crown_scale: 1.0,
335            allometric_trunk_scale: 1.0,
336            lai_multiplier: 1.0,
337            reserved_u32: 0,
338            mesh_asset_hash: 0,
339        }
340    }
341}
342
343/// ABSM (Animation Blending State Machine) layer inspector state.
344#[derive(Debug, Clone, Copy, PartialEq)]
345pub struct AbsmLayerInspectorState {
346    /// 128-bit bone mask (1 bit per skeleton joint).
347    pub bone_mask: u128,
348    /// Blend weight in `[0.0, 1.0]`.
349    pub weight: f32,
350    /// True if additive blending, false if override.
351    pub is_additive: bool,
352    /// Active state index in the layer's state machine.
353    pub active_state_id: u16,
354    /// Active 2D blend-space parameter `(param_x, param_y)`.
355    pub blend_space_uv: [f32; 2],
356}
357
358impl Default for AbsmLayerInspectorState {
359    fn default() -> Self {
360        Self {
361            bone_mask: u128::MAX,
362            weight: 1.0,
363            is_additive: false,
364            active_state_id: 0,
365            blend_space_uv: [0.0, 0.0],
366        }
367    }
368}
369
370/// Complete zero-heap live inspector state for a selected 10D scene node in `webizen-studio`.
371#[derive(Debug, Clone, Copy, PartialEq)]
372pub struct StudioNodeInspector10D {
373    /// Selected scene node ID.
374    pub node_id: u32,
375    /// Local PGA `Motor` transform.
376    pub local_motor: Motor,
377    /// Local 3D scale `[sx, sy, sz]`.
378    pub local_scale: [f32; 3],
379    /// 10D manifold coordinate `[q, v, w, x, y, z, t, α, μ, σ]`.
380    pub tensor_10d: Tensor10D,
381    /// Volumetric 10D slice & EMF field parameters.
382    pub slice_params: Epistemic10DSliceParams,
383    /// `.10d` `PROC1` procedural synthesis parameters.
384    pub proc_header: ProceduralSynthesisHeader,
385    /// `.10d` `EONT1` entity ontology header (stage + metabolic permills).
386    pub eont_header: EntityOntologyMiniHeader,
387    /// Active affordances (`[AffordanceBinaryRecord; MAX_INSPECTOR_AFFORDANCES]`).
388    pub affordances: [AffordanceBinaryRecord; MAX_INSPECTOR_AFFORDANCES],
389    pub affordance_count: usize,
390    /// Ontogenetic developmental keyframes (`[DevelopmentalKeyframeRecord; MAX_INSPECTOR_KEYFRAMES]`).
391    pub keyframes: [DevelopmentalKeyframeRecord; MAX_INSPECTOR_KEYFRAMES],
392    pub keyframe_count: usize,
393    /// Multi-layer ABSM animation layer states.
394    pub absm_layers: [AbsmLayerInspectorState; MAX_INSPECTOR_ABSM_LAYERS],
395    pub absm_layer_count: usize,
396}
397
398impl Default for StudioNodeInspector10D {
399    fn default() -> Self {
400        Self::new(0)
401    }
402}
403
404impl StudioNodeInspector10D {
405    /// Creates a new zero-heap inspector state for `node_id`.
406    pub fn new(node_id: u32) -> Self {
407        Self {
408            node_id,
409            local_motor: Motor::identity(),
410            local_scale: [1.0, 1.0, 1.0],
411            tensor_10d: Tensor10D::default(),
412            slice_params: Epistemic10DSliceParams::default(),
413            proc_header: ProceduralSynthesisHeader::default(),
414            eont_header: EntityOntologyMiniHeader::default(),
415            affordances: [AffordanceBinaryRecord::default(); MAX_INSPECTOR_AFFORDANCES],
416            affordance_count: 0,
417            keyframes: [DevelopmentalKeyframeRecord::default(); MAX_INSPECTOR_KEYFRAMES],
418            keyframe_count: 0,
419            absm_layers: [AbsmLayerInspectorState::default(); MAX_INSPECTOR_ABSM_LAYERS],
420            absm_layer_count: 1,
421        }
422    }
423
424    /// Evaluates the allometric crown & trunk scale multipliers from the node's current
425    /// `EONT1` developmental stage and `PROC1` Huxley power law $y = b \cdot x^k$.
426    #[inline]
427    pub fn evaluate_ontogenetic_allometric_scale(&self) -> [f32; 3] {
428        let stage_progress: f32 = match self.eont_header.stage {
429            0 => 0.15, // SeedOrSpore
430            1 => 0.55, // Juvenile
431            2 => 1.00, // Adult
432            3 => 0.95, // Senescent
433            _ => 0.80, // Deceased
434        };
435        let b = self.proc_header.allometry_base_b.max(0.05);
436        let k = self.proc_header.allometry_exponent_k.clamp(0.1, 3.0);
437        let allometric = b * stage_progress.powf(k);
438        let hydration_factor =
439            0.85 + 0.15 * (self.eont_header.hydration_permill.min(1000) as f32 / 1000.0);
440        [
441            self.local_scale[0] * allometric * hydration_factor,
442            self.local_scale[1] * allometric,
443            self.local_scale[2] * allometric * hydration_factor,
444        ]
445    }
446
447    /// Sets the blend weight for ABSM layer `layer_idx` in `[0.0, 1.0]`.
448    #[inline]
449    pub fn set_absm_layer_weight(&mut self, layer_idx: usize, weight: f32) -> bool {
450        if layer_idx >= MAX_INSPECTOR_ABSM_LAYERS {
451            return false;
452        }
453        if layer_idx >= self.absm_layer_count {
454            self.absm_layer_count = layer_idx + 1;
455        }
456        self.absm_layers[layer_idx].weight = weight.clamp(0.0, 1.0);
457        true
458    }
459}
460
461#[cfg(test)]
462mod tests {
463    use super::*;
464
465    #[test]
466    fn inspector_10d_evaluates_ontogenetic_allometry_and_absm_weights() {
467        let mut insp = StudioNodeInspector10D::new(42);
468        insp.eont_header.stage = 1; // Juvenile
469        let juv_scale = insp.evaluate_ontogenetic_allometric_scale();
470
471        insp.eont_header.stage = 2; // Adult
472        let adult_scale = insp.evaluate_ontogenetic_allometric_scale();
473
474        assert!(
475            adult_scale[1] > juv_scale[1],
476            "Adult allometric height ({}) must exceed juvenile ({})",
477            adult_scale[1],
478            juv_scale[1]
479        );
480
481        assert!(insp.set_absm_layer_weight(2, 0.75));
482        assert_eq!(insp.absm_layer_count, 3);
483        assert!((insp.absm_layers[2].weight - 0.75).abs() < 1e-6);
484    }
485}