qualia_core_db/container_10d/
procedural_synthesis.rs1use 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#[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 pub voronoi_frequency: f32,
40 pub voronoi_jitter: f32,
41 pub fillet_blend_radius: f32,
43 pub fillet_threshold: f32,
44 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 pub motor_frequency_hz: f32,
51 pub motor_damping_ratio: f32,
52 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
87pub 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
103pub 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#[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#[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#[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#[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 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 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#[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#[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); 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}