Skip to main content

qualia_core_db/container_10d/
procedural_synthesis.rs

1//! Principled Procedural Geometry & Surface Synthesis for `.10d` Living Containers.
2//!
3//! Replaces massive static geometry and texture assets with compact mathematical
4//! recipes evaluated deterministically on the GPU / SIMD hot paths in zero heap:
5//!
6//! 1. **Cellular Voronoi Micro-Surfaces**: Organic scales, tree bark fissures, leaf venation,
7//!    cracked mud, and corrosion pitting synthesized directly from a 64-bit seed.
8//! 2. **Implicit SDF Smooth-Fillets**: Smooth-minimum blending $r$ for seamless branch-to-trunk
9//!    unions and structural welded joints without hand-modeled seam meshes.
10//! 3. **Allometric Growth Curves ($y = b \cdot x^k$) & Logarithmic Spirals ($r = a e^{k \theta}$)**:
11//!    Horns, tusks, antlers, shells, and ontogenetic proportion changes governed by ODEs.
12//! 4. **PGA Motor Oscillations**: Projective Geometric Algebra motors for secondary wind/motion
13//!    foliage rustle, tail wag, and vehicle chassis sway.
14//! 5. **CSG Stress-Tensor Cleavage**: Dynamic fracture along physical cleavage planes when
15//!    tensile stress exceeds $\sigma_{\text{crit}}$, avoiding duplicate pre-fractured mesh assets.
16
17use bytemuck::{Pod, Zeroable};
18
19pub const PROCEDURAL_SYNTHESIS_SECTION_VERSION: u16 = 1;
20pub const PROCEDURAL_SYNTHESIS_HEADER_SIZE: usize = 64;
21pub const MAGIC_PROC: [u8; 4] = *b"PROC";
22
23pub const FLAG_CELLULAR_VORONOI: u32 = 1 << 0;
24pub const FLAG_IMPLICIT_FILLET: u32 = 1 << 1;
25pub const FLAG_ALLOMETRIC_GROWTH: u32 = 1 << 2;
26pub const FLAG_LOG_SPIRAL_ODE: u32 = 1 << 3;
27pub const FLAG_PGA_MOTOR_DYNAMICS: u32 = 1 << 4;
28pub const FLAG_STRESS_FRACTURE: u32 = 1 << 5;
29
30/// 64-byte POD header encoding procedural synthesis recipes in SectionType::ProceduralSynthesis (18).
31#[repr(C)]
32#[derive(Debug, Clone, Copy, PartialEq, Pod, Zeroable)]
33pub struct ProceduralSynthesisHeader {
34    pub magic: [u8; 4],
35    pub version: u16,
36    pub flags: u16,
37    pub seed: u64,
38    // Cellular Voronoi params
39    pub voronoi_frequency: f32,
40    pub voronoi_jitter: f32,
41    // Implicit SDF fillet params
42    pub fillet_blend_radius: f32,
43    pub fillet_threshold: f32,
44    // Allometric & Spiral params
45    pub allometry_exponent_k: f32,
46    pub allometry_base_b: f32,
47    pub spiral_growth_rate_k: f32,
48    pub spiral_initial_radius_a: f32,
49    // PGA dynamics params
50    pub motor_frequency_hz: f32,
51    pub motor_damping_ratio: f32,
52    // Fracture params
53    pub critical_stress_threshold: f32,
54    pub reserved_f32: f32,
55}
56
57#[derive(Debug, Clone, PartialEq, Eq)]
58pub enum ProceduralSynthesisError {
59    PayloadTooShort { need: usize, have: usize },
60    BadMagic([u8; 4]),
61    UnsupportedVersion(u16),
62    BufferTooSmall { need: usize, have: usize },
63}
64
65impl std::fmt::Display for ProceduralSynthesisError {
66    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
67        match self {
68            Self::PayloadTooShort { need, have } => {
69                write!(
70                    f,
71                    "procedural synthesis payload too short: have {have}, need {need}"
72                )
73            }
74            Self::BadMagic(m) => write!(f, "bad procedural synthesis magic: {m:?}"),
75            Self::UnsupportedVersion(v) => {
76                write!(f, "unsupported procedural synthesis version {v}")
77            }
78            Self::BufferTooSmall { need, have } => {
79                write!(f, "buffer too small: have {have}, need {need}")
80            }
81        }
82    }
83}
84
85impl std::error::Error for ProceduralSynthesisError {}
86
87/// Encode procedural synthesis header into a caller-supplied byte slice.
88pub fn encode_procedural_synthesis_section(
89    header: &ProceduralSynthesisHeader,
90    out: &mut [u8],
91) -> Result<usize, ProceduralSynthesisError> {
92    if out.len() < PROCEDURAL_SYNTHESIS_HEADER_SIZE {
93        return Err(ProceduralSynthesisError::BufferTooSmall {
94            need: PROCEDURAL_SYNTHESIS_HEADER_SIZE,
95            have: out.len(),
96        });
97    }
98    let bytes = bytemuck::bytes_of(header);
99    out[..PROCEDURAL_SYNTHESIS_HEADER_SIZE].copy_from_slice(bytes);
100    Ok(PROCEDURAL_SYNTHESIS_HEADER_SIZE)
101}
102
103/// Decode procedural synthesis header from a byte slice. Zero heap.
104pub fn decode_procedural_synthesis_section(
105    payload: &[u8],
106) -> Result<ProceduralSynthesisHeader, ProceduralSynthesisError> {
107    if payload.len() < PROCEDURAL_SYNTHESIS_HEADER_SIZE {
108        return Err(ProceduralSynthesisError::PayloadTooShort {
109            need: PROCEDURAL_SYNTHESIS_HEADER_SIZE,
110            have: payload.len(),
111        });
112    }
113    let header: ProceduralSynthesisHeader =
114        *bytemuck::from_bytes(&payload[..PROCEDURAL_SYNTHESIS_HEADER_SIZE]);
115
116    if header.magic != MAGIC_PROC {
117        return Err(ProceduralSynthesisError::BadMagic(header.magic));
118    }
119    if header.version != PROCEDURAL_SYNTHESIS_SECTION_VERSION {
120        return Err(ProceduralSynthesisError::UnsupportedVersion(header.version));
121    }
122
123    Ok(header)
124}
125
126// ── Principled Zero-Heap Evaluators ─────────────────────────────────────────
127
128/// Evaluate allometric morphological dimension according to Huxley's power equation:
129/// $y = b \cdot x^k$, where $x$ is body size / developmental progress.
130#[inline]
131pub fn evaluate_allometric_dimension(body_scale: f32, base_b: f32, exponent_k: f32) -> f32 {
132    if body_scale <= 0.0 {
133        return 0.0;
134    }
135    base_b * body_scale.powf(exponent_k)
136}
137
138/// Evaluate logarithmic spiral ODE position $(x, y) = (r \cos\theta, r \sin\theta)$
139/// where $r = a \cdot e^{k \cdot \theta}$. Governs horns, tusks, and ammonite shells.
140#[inline]
141pub fn evaluate_log_spiral_2d(theta: f32, initial_a: f32, growth_k: f32) -> (f32, f32) {
142    let r = initial_a * (growth_k * theta).exp();
143    let x = r * theta.cos();
144    let y = r * theta.sin();
145    (x, y)
146}
147
148/// Polynomial smooth-minimum blending (SDF implicit fillet) between two distances $d_1$ and $d_2$:
149/// $smin(d_1, d_2, r) = \min(d_1, d_2) - \frac{h^2}{4r}$ where $h = \max(r - |d_1 - d_2|, 0)$.
150#[inline]
151pub fn evaluate_smooth_minimum_sdf(d1: f32, d2: f32, blend_radius: f32) -> f32 {
152    if blend_radius <= 0.0 {
153        return d1.min(d2);
154    }
155    let h = (blend_radius - (d1 - d2).abs()).max(0.0);
156    d1.min(d2) - (h * h) / (4.0 * blend_radius)
157}
158
159/// Zero-heap 2D Voronoi cellular distance perturbation for procedural micro-surfaces.
160/// Generates cell distance $F_1$ and cell hash from a coordinate and seed.
161#[inline]
162pub fn evaluate_voronoi_cellular_f1(u: f32, v: f32, seed: u64, frequency: f32) -> f32 {
163    let su = u * frequency;
164    let sv = v * frequency;
165    let iu = su.floor() as i32;
166    let iv = sv.floor() as i32;
167    let fu = su.fract();
168    let fv = sv.fract();
169
170    let mut min_dist_sq = 100.0f32;
171
172    // Search 3x3 local neighbor cells
173    let mut di = -1;
174    while di <= 1 {
175        let mut dj = -1;
176        while dj <= 1 {
177            let cell_x = iu + di;
178            let cell_y = iv + dj;
179
180            // Deterministic integer FNV-style pseudo-random offset
181            let h = ((cell_x as u64)
182                .wrapping_mul(0x517cc1b727220a95)
183                .wrapping_add((cell_y as u64).wrapping_mul(0x6c8e9cf570932b35))
184                .wrapping_add(seed))
185                ^ 0xbf58476d1ce4e5b9;
186
187            let rx = ((h & 0xFFFF) as f32) / 65535.0;
188            let ry = (((h >> 16) & 0xFFFF) as f32) / 65535.0;
189
190            let dx = (di as f32) + rx - fu;
191            let dy = (dj as f32) + ry - fv;
192            let d_sq = dx * dx + dy * dy;
193
194            if d_sq < min_dist_sq {
195                min_dist_sq = d_sq;
196            }
197            dj += 1;
198        }
199        di += 1;
200    }
201
202    min_dist_sq.sqrt().min(1.0)
203}
204
205/// Projective Geometric Algebra (PGA) rotor oscillation displacement for secondary dynamics.
206/// Evaluates dynamic sway vector from time, natural frequency, damping, and an external drive force.
207#[inline]
208pub fn evaluate_pga_motor_oscillation(
209    rest_offset: [f32; 3],
210    time_sec: f32,
211    freq_hz: f32,
212    damping: f32,
213    drive_direction: [f32; 3],
214) -> [f32; 3] {
215    let omega = 2.0 * std::f32::consts::PI * freq_hz;
216    let decay = (-damping * time_sec.max(0.0)).exp();
217    let phase = (omega * time_sec).sin() * decay;
218
219    [
220        rest_offset[0] + drive_direction[0] * phase,
221        rest_offset[1] + drive_direction[1] * phase,
222        rest_offset[2] + drive_direction[2] * phase,
223    ]
224}
225
226/// Evaluate structural fracture criterion under principal tensile stress $\sigma_1$.
227/// Returns true if $\sigma_1 \ge \sigma_{\text{crit}}$ and determines the cleavage partition sign.
228#[inline]
229pub fn evaluate_stress_cleavage_partition(
230    vertex_pos: [f32; 3],
231    cleavage_plane_normal: [f32; 3],
232    cleavage_plane_dist: f32,
233    tensile_stress: f32,
234    crit_threshold: f32,
235) -> Option<bool> {
236    if tensile_stress < crit_threshold {
237        return None;
238    }
239    let dot = vertex_pos[0] * cleavage_plane_normal[0]
240        + vertex_pos[1] * cleavage_plane_normal[1]
241        + vertex_pos[2] * cleavage_plane_normal[2];
242    Some(dot >= cleavage_plane_dist)
243}
244
245#[cfg(test)]
246mod tests {
247    use super::*;
248
249    #[test]
250    fn procedural_synthesis_header_roundtrips() {
251        let header = ProceduralSynthesisHeader {
252            magic: MAGIC_PROC,
253            version: 1,
254            flags: (FLAG_CELLULAR_VORONOI | FLAG_ALLOMETRIC_GROWTH | FLAG_LOG_SPIRAL_ODE) as u16,
255            seed: 0x1234_5678_9ABC_DEF0,
256            voronoi_frequency: 16.0,
257            voronoi_jitter: 0.85,
258            fillet_blend_radius: 0.15,
259            fillet_threshold: 0.05,
260            allometry_exponent_k: 1.35,
261            allometry_base_b: 0.42,
262            spiral_growth_rate_k: 0.18,
263            spiral_initial_radius_a: 0.10,
264            motor_frequency_hz: 2.5,
265            motor_damping_ratio: 0.12,
266            critical_stress_threshold: 45.0,
267            reserved_f32: 0.0,
268        };
269
270        let mut buffer = [0u8; 128];
271        let bytes_written = encode_procedural_synthesis_section(&header, &mut buffer).unwrap();
272        assert_eq!(bytes_written, PROCEDURAL_SYNTHESIS_HEADER_SIZE);
273
274        let decoded = decode_procedural_synthesis_section(&buffer[..bytes_written]).unwrap();
275        assert_eq!(decoded.magic, MAGIC_PROC);
276        assert_eq!(decoded.version, 1);
277        assert_eq!(decoded.seed, 0x1234_5678_9ABC_DEF0);
278        assert!((decoded.voronoi_frequency - 16.0).abs() < 1e-6);
279        assert!((decoded.allometry_exponent_k - 1.35).abs() < 1e-6);
280    }
281
282    #[test]
283    fn allometric_and_spiral_evaluations_are_deterministic() {
284        let dim = evaluate_allometric_dimension(2.0, 0.5, 2.0);
285        assert!((dim - 2.0).abs() < 1e-5); // 0.5 * 2^2 = 2.0
286
287        let (x, y) = evaluate_log_spiral_2d(0.0, 1.0, 0.2);
288        assert!((x - 1.0).abs() < 1e-5);
289        assert!(y.abs() < 1e-5);
290
291        let smin = evaluate_smooth_minimum_sdf(1.0, 2.0, 0.5);
292        assert!(smin <= 1.0);
293
294        let vor = evaluate_voronoi_cellular_f1(0.5, 0.5, 42, 10.0);
295        assert!(vor >= 0.0 && vor <= 1.0);
296
297        let pga = evaluate_pga_motor_oscillation([0.0, 1.0, 0.0], 0.25, 1.0, 0.0, [1.0, 0.0, 0.0]);
298        assert_ne!(pga[0], 0.0);
299        assert_eq!(pga[1], 1.0);
300    }
301}