Skip to main content

qualia_core_db/render/
vertebrate_anatomy.rs

1//! Comparative Vertebrate Anatomy & 3-Layer Biomechanical Living Containers (`zoological_anatomy.rs`).
2//!
3//! Implements **Epic 2** (Scale 5 Comparative Vertebrate Anatomy) of the Biological Education Assets
4//! and Explorable World master plan (`docs/plans/biological-education-assets-and-explorable-world-plan.md`).
5//!
6//! Covers all 13 Australian fauna biomechanical archetypes across 3 inspectable anatomical layers:
7//! - **Layer 0 — Articulated Osteology** (8 regions including diprotodont rostrum, hypsodont dentition,
8//!   keeled carina sternum, furcula, and characteristic marsupial/monotreme **epipubic bones**!).
9//! - **Layer 1 — Major Myology & Tendons** (8 functional groups including the elastic
10//!   **Achilles tendon spring** energy-recovery store, massive flight pectorals, and fossorial deltoids).
11//! - **Layer 2 — External Integument** (high-resolution outer skin, pelage, plumage, or squamation).
12//!
13//! Generates >= 1,800 vertex high-resolution meshes bound to `FaunaSkeletalRig10d` (18 PGA joints),
14//! seals them into `.10d` Living Containers with `MAT4`, `UV01`, `FNRM`, `SRD1`, `PROC1`, `EONT1`,
15//! `MRP1` (costal respiration, gular vocalization, Achilles tendon strain), and `PROV`.
16//! Also provides zero-heap layer peeling and exploded-view cross-fading.
17
18use bytemuck;
19use serde::{Deserialize, Serialize};
20
21use crate::container_10d::entity_ontology_section::{
22    AffordanceBinaryRecord, DevelopmentalKeyframeRecord, EntityOntologyMiniHeader,
23    AFFORDANCE_RECORD_SIZE, DEVELOPMENTAL_KEYFRAME_RECORD_SIZE, ENTITY_ONTOLOGY_MINI_HEADER_SIZE,
24    ENTITY_ONTOLOGY_SECTION_VERSION, MAGIC_EONT,
25};
26use crate::container_10d::header::{Container10dHeader, MAX_SECTION_COUNT};
27use crate::container_10d::integrity::seal_whole_file_crc32c;
28use crate::container_10d::material_container::attach_material_section;
29use crate::container_10d::material_section::{
30    MaterialRecord, OpacityMode, ShadingModel, SubmeshRange,
31};
32use crate::container_10d::morph_section::{
33    encode_morph_section, morph_section_encoded_len, quantize_morph_delta, MorphSectionHeader,
34    QuantizedMorphDelta, FLAG_MORPH_HAS_NORMALS, FLAG_MORPH_ONTOGENETIC_BIND, FLAG_MORPH_SPARSE,
35    MAGIC_MRP1, MORPH_SECTION_VERSION,
36};
37use crate::container_10d::procedural_synthesis::{
38    encode_procedural_synthesis_section, ProceduralSynthesisHeader, FLAG_ALLOMETRIC_GROWTH,
39    FLAG_CELLULAR_VORONOI, FLAG_IMPLICIT_FILLET, FLAG_PGA_MOTOR_DYNAMICS, MAGIC_PROC,
40    PROCEDURAL_SYNTHESIS_HEADER_SIZE, PROCEDURAL_SYNTHESIS_SECTION_VERSION,
41};
42use crate::container_10d::provenance_section::ProvenanceSidecar;
43#[path = "vertebrate_skin_seal.rs"]
44mod vertebrate_skin_seal;
45#[path = "vertebrate_authored_skin.rs"]
46pub mod authored_skin;
47use crate::container_10d::section::{
48    encode_container, parse_section_table, AlignmentTier, SectionInput, SectionTableError,
49    SectionType,
50};
51use crate::container_10d::texture_coordinate_container::attach_texture_coordinate_section;
52use crate::q_hash;
53use crate::render::assets::Mesh;
54use crate::render::compile_10d::{compile_mesh_to_10d_with_extras_and_frames, Compile10dExtras};
55
56use crate::render::skeletal::fauna_rig::{
57    FaunaBiomechanicalArchetype, FaunaSkeletalRig10d, JOINT_CHEST, JOINT_HEAD, JOINT_JAW,
58    JOINT_LEFT_ANKLE, JOINT_LEFT_ELBOW, JOINT_LEFT_HIP, JOINT_LEFT_KNEE, JOINT_LEFT_SHOULDER,
59    JOINT_LEFT_WRIST_WING, JOINT_NECK, JOINT_PELVIS_ROOT, JOINT_RIGHT_ANKLE, JOINT_RIGHT_HIP,
60    JOINT_RIGHT_KNEE, JOINT_SPINE, JOINT_TAIL_BASE, JOINT_TAIL_MID, JOINT_TAIL_TIP,
61};
62
63// ── Anatomical Layers ────────────────────────────────────────────────────────
64
65/// 3 Primary Comparative Anatomical Layers for Scale 5 vertebrate dissection.
66#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
67pub enum ZoologicalAnatomicalLayer {
68    /// Layer 0: Articulated skeleton.
69    Osteology,
70    /// Layer 1: Functional muscle groups & elastic energy-recovery tendons.
71    MyologyAndTendons,
72    /// Layer 2: Pelage, plumage, squamation, or amphibian skin.
73    ExternalIntegument,
74}
75
76// ── Osteology Regions ────────────────────────────────────────────────────────
77
78/// 8 Comparative Vertebrate Osteology Regions (Layer 0).
79#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
80pub enum VertebrateOsteologyRegion {
81    /// Cranium & Rostrum (diprotodont diastema / monotreme electrosensory bill / raptor beak / lizard diapsid).
82    CraniumAndRostrum,
83    /// Mandible & Dentition (procumbent lower incisors / hypsodont molars / toothless keratinous pads).
84    MandibleAndDentition,
85    /// Cervical, Thoracic & Lumbar vertebral column (axial spine support).
86    CervicalThoracicLumbarVertebrae,
87    /// Ribcage & Sternum (including avian keeled carina & furcula wishbone).
88    RibcageAndSternum,
89    /// Pectoral Girdle & Forelimb (scapula, humerus, radius, ulna, carpals, pentadactyl digits / fossorial claws).
90    PectoralGirdleAndForelimb,
91    /// Pelvic Girdle & Epipubic Bones (ilium, ischium, pubis + characteristic marsupial/monotreme epipubic bones!).
92    PelvicGirdleAndEpipubicBones,
93    /// Hindlimb & Syndactyl Pes (femur, elongated tibia/fibula, calcaneum, elongated 4th metatarsal, syndactyl grooming digits II & III).
94    HindlimbAndSyndactylPes,
95    /// Caudal Vertebral Chain (muscular counterbalance/pentapedal fifth-limb tail in macropods; flattened rudder tail in platypus).
96    CaudalVertebralChain,
97}
98
99impl VertebrateOsteologyRegion {
100    pub const ALL: [Self; 8] = [
101        Self::CraniumAndRostrum,
102        Self::MandibleAndDentition,
103        Self::CervicalThoracicLumbarVertebrae,
104        Self::RibcageAndSternum,
105        Self::PectoralGirdleAndForelimb,
106        Self::PelvicGirdleAndEpipubicBones,
107        Self::HindlimbAndSyndactylPes,
108        Self::CaudalVertebralChain,
109    ];
110
111    pub const fn name(&self) -> &'static str {
112        match self {
113            Self::CraniumAndRostrum => "Cranium & Rostrum",
114            Self::MandibleAndDentition => "Mandible & Dentition",
115            Self::CervicalThoracicLumbarVertebrae => "Cervical, Thoracic & Lumbar Vertebrae",
116            Self::RibcageAndSternum => "Ribcage & Sternum (Carina / Furcula)",
117            Self::PectoralGirdleAndForelimb => "Pectoral Girdle & Forelimb",
118            Self::PelvicGirdleAndEpipubicBones => "Pelvic Girdle & Epipubic Bones",
119            Self::HindlimbAndSyndactylPes => "Hindlimb & Syndactyl Pes",
120            Self::CaudalVertebralChain => "Caudal Vertebral Chain",
121        }
122    }
123}
124
125// ── Myology Groups ───────────────────────────────────────────────────────────
126
127/// 8 Comparative Vertebrate Functional Myology Groups & Tendon Springs (Layer 1).
128#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
129pub enum VertebrateMyologyGroup {
130    /// Gastrocnemius & Plantaris (power calf propulsion).
131    GastrocnemiusAndPlantaris,
132    /// Elastic Achilles Tendon Spring (stores and returns up to 65% metabolic work per hop/stride).
133    ElasticAchillesTendonSpring,
134    /// Gluteus & Biceps Femoris (massive thigh hip-extensor mass).
135    GluteusAndBicepsFemoris,
136    /// Iliopsoas & Caudofemoralis (deep hip flexor & tail-to-femur retractor).
137    IliopsoasAndCaudofemoralis,
138    /// Pectoralis Major & Supracoracoideus (massive chest flight/forelimb adductor).
139    PectoralisMajorAndSupracoracoideus,
140    /// Deltoid & Triceps Fossorial (powerful digging/climbing shoulder abductors).
141    DeltoidAndTricepsFossorial,
142    /// Masseter & Temporalis (jaw mastication muscles powering diprotodont shearing).
143    MasseterAndTemporalis,
144    /// Intercostals & Diaphragm (thoracic respiratory expansion & costal ventilation).
145    IntercostalsAndDiaphragm,
146}
147
148impl VertebrateMyologyGroup {
149    pub const ALL: [Self; 8] = [
150        Self::GastrocnemiusAndPlantaris,
151        Self::ElasticAchillesTendonSpring,
152        Self::GluteusAndBicepsFemoris,
153        Self::IliopsoasAndCaudofemoralis,
154        Self::PectoralisMajorAndSupracoracoideus,
155        Self::DeltoidAndTricepsFossorial,
156        Self::MasseterAndTemporalis,
157        Self::IntercostalsAndDiaphragm,
158    ];
159
160    pub const fn name(&self) -> &'static str {
161        match self {
162            Self::GastrocnemiusAndPlantaris => "Gastrocnemius & Plantaris",
163            Self::ElasticAchillesTendonSpring => "Elastic Achilles Tendon Spring",
164            Self::GluteusAndBicepsFemoris => "Gluteus & Biceps Femoris",
165            Self::IliopsoasAndCaudofemoralis => "Iliopsoas & Caudofemoralis",
166            Self::PectoralisMajorAndSupracoracoideus => "Pectoralis Major & Supracoracoideus",
167            Self::DeltoidAndTricepsFossorial => "Deltoid & Triceps Fossorial",
168            Self::MasseterAndTemporalis => "Masseter & Temporalis",
169            Self::IntercostalsAndDiaphragm => "Intercostals & Diaphragm",
170        }
171    }
172}
173
174// ── Compiled Vertebrate Anatomy Container ────────────────────────────────────
175
176/// Complete 3-Layer Comparative Anatomical Twin sealed into a `.10d` Living Container.
177#[derive(Clone, Debug)]
178pub struct CompiledVertebrateAnatomy10d {
179    /// Biomechanical archetype.
180    pub archetype: FaunaBiomechanicalArchetype,
181    /// Baseline archetype controls. Use `authored_skin` when present for the sealed rig.
182    pub rig: FaunaSkeletalRig10d,
183    /// Species-authored bind and appended bilateral forelimbs, matching sealed SKL1.
184    pub authored_skin: Option<authored_skin::AuthoredSkinBinding>,
185    /// Fully sealed and CRC-32C verified `.10d` living container binary.
186    pub container_bytes: Vec<u8>,
187    /// Total vertices across all 3 layers (>= 1,800).
188    pub vertex_count: usize,
189    /// Total triangles across all 3 layers.
190    pub triangle_count: usize,
191    /// Index range for Osteology (Layer 0).
192    pub osteology_vertex_range: std::ops::Range<usize>,
193    /// Index range for Myology (Layer 1).
194    pub myology_vertex_range: std::ops::Range<usize>,
195    /// Index range for External Integument (Layer 2).
196    pub integument_vertex_range: std::ops::Range<usize>,
197    /// CPU vertex positions [x, y, z] in rest pose.
198    pub positions: Vec<[f32; 3]>,
199    /// CPU vertex normals [nx, ny, nz].
200    pub normals: Vec<[f32; 3]>,
201    /// CPU RGBA8 surface readings / colors [r, g, b, a].
202    pub colors: Vec<[f32; 4]>,
203    /// CPU texture coordinates [u, v].
204    pub uvs: Vec<[f32; 2]>,
205    /// Contiguous index stream for all submeshes.
206    pub indices: Vec<u32>,
207    /// 17 PBR material records (8 osteology, 8 myology, 1 integument).
208    pub materials: Vec<MaterialRecord>,
209    /// 17 submesh index intervals.
210    pub submesh_ranges: Vec<SubmeshRange>,
211    /// GPU joint indices (up to 4 joints per vertex).
212    pub skin_joint_indices: Vec<[u16; 4]>,
213    /// GPU joint blending weights (summing to 1.0).
214    pub skin_weights: Vec<[f32; 4]>,
215    /// Per-vertex anatomical layer classification.
216    pub layer_tags: Vec<ZoologicalAnatomicalLayer>,
217}
218
219// ── Zero-Heap Layer Peeling & Exploded View ──────────────────────────────────
220
221/// Evaluates interactive layer peeling and exploded-view displacement between
222/// `ExternalIntegument`, `MyologyAndTendons`, and `Osteology` in zero heap allocations.
223///
224/// Modulates alpha opacity and radially displaces muscles and integument outward along
225/// surface normals, revealing deeper anatomical layers without allocating memory.
226///
227/// Returns the number of vertices evaluated.
228#[inline]
229pub fn evaluate_anatomical_layer_peel_zero_heap(
230    in_positions: &[[f32; 3]],
231    in_normals: &[[f32; 3]],
232    in_layer_tags: &[ZoologicalAnatomicalLayer],
233    osteology_vis_01: f32,
234    myology_vis_01: f32,
235    integument_vis_01: f32,
236    explode_displacement_01: f32,
237    out_positions: &mut [[f32; 3]],
238    out_alphas: &mut [f32],
239) -> usize {
240    let count = in_positions
241        .len()
242        .min(in_normals.len())
243        .min(in_layer_tags.len())
244        .min(out_positions.len())
245        .min(out_alphas.len());
246
247    let ost_vis = osteology_vis_01.clamp(0.0, 1.0);
248    let myo_vis = myology_vis_01.clamp(0.0, 1.0);
249    let int_vis = integument_vis_01.clamp(0.0, 1.0);
250    let explode = explode_displacement_01.clamp(0.0, 1.0);
251
252    for i in 0..count {
253        let p = in_positions[i];
254        let n = in_normals[i];
255        let layer = in_layer_tags[i];
256
257        let (alpha, disp_dist) = match layer {
258            ZoologicalAnatomicalLayer::Osteology => (ost_vis, 0.0),
259            ZoologicalAnatomicalLayer::MyologyAndTendons => (myo_vis, explode * 0.08),
260            ZoologicalAnatomicalLayer::ExternalIntegument => (int_vis, explode * 0.18),
261        };
262
263        out_positions[i] = [
264            p[0] + n[0] * disp_dist,
265            p[1] + n[1] * disp_dist,
266            p[2] + n[2] * disp_dist,
267        ];
268        out_alphas[i] = alpha;
269    }
270
271    count
272}
273
274// ── Mesh Accumulator & Anatomical Loft Generators ────────────────────────────
275
276/// Single cross-section ring station for multi-station anatomical lofting in `AnatomyMeshAccumulator`.
277#[derive(Clone, Copy, Debug)]
278pub struct AnatomicalLoftRing {
279    /// Station 3D center `[x, y, z]`.
280    pub center: [f32; 3],
281    /// Lateral half-width (`rx`) and dorsoventral half-height (`ry`).
282    pub radii: [f32; 2],
283    /// Dorsal color (top of cross-section).
284    pub dorsal_color: [f32; 4],
285    /// Mid-flank color (sides of cross-section).
286    pub flank_color: [f32; 4],
287    /// Ventral color (underside of cross-section).
288    pub ventral_color: [f32; 4],
289    /// Primary skeletal joint index.
290    pub primary_joint: usize,
291    /// Secondary skeletal joint index.
292    pub secondary_joint: usize,
293    /// Primary skeletal joint weight `[0.0, 1.0]`.
294    pub primary_weight: f32,
295}
296
297#[inline]
298fn lerp_rgba(a: [f32; 4], b: [f32; 4], t: f32) -> [f32; 4] {
299    let u = t.clamp(0.0, 1.0);
300    [
301        a[0] + (b[0] - a[0]) * u,
302        a[1] + (b[1] - a[1]) * u,
303        a[2] + (b[2] - a[2]) * u,
304        a[3] + (b[3] - a[3]) * u,
305    ]
306}
307
308#[inline]
309fn sample_countershade(
310    dorsal: [f32; 4],
311    flank: [f32; 4],
312    ventral: [f32; 4],
313    sin_theta: f32,
314) -> [f32; 4] {
315    if sin_theta >= 0.0 {
316        lerp_rgba(flank, dorsal, sin_theta.clamp(0.0, 1.0).powf(0.75))
317    } else {
318        lerp_rgba(flank, ventral, (-sin_theta).clamp(0.0, 1.0).powf(0.70))
319    }
320}
321
322/// High-resolution anatomical mesh accumulator supporting multi-station elliptical lofts,
323/// bicondylar long bones, curved costal rib arches, fusiform muscle bellies with tendons,
324/// internal viscera, and countershaded integument envelopes.
325pub struct AnatomyMeshAccumulator {
326    pub authored_skin: Option<authored_skin::AuthoredSkinBinding>,
327    pub positions: Vec<[f32; 3]>,
328    pub normals: Vec<[f32; 3]>,
329    pub colors: Vec<[f32; 4]>,
330    pub uvs: Vec<[f32; 2]>,
331    pub indices: Vec<u32>,
332    pub layer_tags: Vec<ZoologicalAnatomicalLayer>,
333    pub joint_indices: Vec<[u16; 4]>,
334    pub joint_weights: Vec<[f32; 4]>,
335}
336
337type MeshAccumulator = AnatomyMeshAccumulator;
338
339impl AnatomyMeshAccumulator {
340    pub fn new() -> Self {
341        Self {
342            authored_skin: None,
343            positions: Vec::with_capacity(6400),
344            normals: Vec::with_capacity(6400),
345            colors: Vec::with_capacity(6400),
346            uvs: Vec::with_capacity(6400),
347            indices: Vec::with_capacity(14400),
348            layer_tags: Vec::with_capacity(6400),
349            joint_indices: Vec::with_capacity(6400),
350            joint_weights: Vec::with_capacity(6400),
351        }
352    }
353
354    /// Sweeps a multi-station anatomical loft with smooth Bishop-like frames, analytical normals,
355    /// end caps, and dorsal–flank–ventral countershading.
356    pub fn push_countershaded_loft(
357        &mut self,
358        stations: &[AnatomicalLoftRing],
359        radial_segs: usize,
360        layer: ZoologicalAnatomicalLayer,
361        cap_ends: bool,
362    ) {
363        if stations.len() < 2 {
364            return;
365        }
366        let r_segs = radial_segs.max(6);
367        let n_st = stations.len();
368        let stride = (r_segs + 1) as u32;
369        let base_idx = self.positions.len() as u32;
370
371        // Keep the historical first ring orientation, then transport it along
372        // the path. Re-selecting an up vector at each station can rotate a
373        // ring by almost 180 degrees at a bent knee and fold the connecting
374        // triangles, even though their indices remain connected.
375        use crate::specialized_libs::computational_geometry::{
376            compute_bishop_frames, math_geometry::AffineFrame3, Point3,
377        };
378        let path: Vec<Point3> = stations.iter().map(|s| Point3::new(
379            s.center[0] as f64, s.center[1] as f64, s.center[2] as f64,
380        )).collect();
381        let d = [path[1].x-path[0].x, path[1].y-path[0].y, path[1].z-path[0].z];
382        let len = (d[0]*d[0]+d[1]*d[1]+d[2]*d[2]).sqrt();
383        let t = if len > 1e-12 { [d[0]/len,d[1]/len,d[2]/len] } else { [0.0,0.0,0.0] };
384        let up = if t[1].abs() < 0.92 { [0.0,1.0,0.0] } else { [0.0,0.0,if t[1]>=0.0 {-1.0} else {1.0}] };
385        let initial = Point3::new(up[1]*t[2]-up[2]*t[1],up[2]*t[0]-up[0]*t[2],up[0]*t[1]-up[1]*t[0]);
386        let zero = Point3::new(0.0,0.0,0.0);
387        let mut frames = vec![AffineFrame3 { origin: zero, e0: zero, e1: zero, e2: zero }; n_st];
388        // Preserve the prior behaviour for invalid/degenerate legacy paths.
389        let transported = compute_bishop_frames(&path, Some(initial), &mut frames).is_ok();
390
391        for (si, st) in stations.iter().enumerate() {
392            let prev = if si > 0 {
393                stations[si - 1].center
394            } else {
395                stations[0].center
396            };
397            let next = if si + 1 < n_st {
398                stations[si + 1].center
399            } else {
400                stations[n_st - 1].center
401            };
402            let mut tx = next[0] - prev[0];
403            let mut ty = next[1] - prev[1];
404            let mut tz = next[2] - prev[2];
405            let tlen = (tx * tx + ty * ty + tz * tz).sqrt().max(1e-5);
406            tx /= tlen;
407            ty /= tlen;
408            tz /= tlen;
409
410            let ref_up = if ty.abs() < 0.92 {
411                [0.0_f32, 1.0_f32, 0.0_f32]
412            } else {
413                [0.0_f32, 0.0_f32, if ty >= 0.0 { -1.0_f32 } else { 1.0_f32 }]
414            };
415            let mut ux = ref_up[1] * tz - ref_up[2] * ty;
416            let mut uy = ref_up[2] * tx - ref_up[0] * tz;
417            let mut uz = ref_up[0] * ty - ref_up[1] * tx;
418            let ulen = (ux * ux + uy * uy + uz * uz).sqrt().max(1e-5);
419            ux /= ulen;
420            uy /= ulen;
421            uz /= ulen;
422
423            let (vx, vy, vz) = if transported {
424                let f = &frames[si];
425                ux = f.e0.x as f32;
426                uy = f.e0.y as f32;
427                uz = f.e0.z as f32;
428                (f.e1.x as f32, f.e1.y as f32, f.e1.z as f32)
429            } else {
430                (ty * uz - tz * uy, tz * ux - tx * uz, tx * uy - ty * ux)
431            };
432
433            let rx = st.radii[0].max(1e-4);
434            let ry = st.radii[1].max(1e-4);
435            let w1 = st.primary_weight.clamp(0.0, 1.0);
436            let w2 = 1.0 - w1;
437            let v_uv = si as f32 / (n_st - 1) as f32;
438
439            for s in 0..=r_segs {
440                let u_uv = s as f32 / r_segs as f32;
441                let theta = u_uv * core::f32::consts::TAU;
442                let ct = theta.cos();
443                let st_sin = theta.sin();
444
445                let px = st.center[0] + ux * (rx * ct) + vx * (ry * st_sin);
446                let py = st.center[1] + uy * (rx * ct) + vy * (ry * st_sin);
447                let pz = st.center[2] + uz * (rx * ct) + vz * (ry * st_sin);
448
449                let nx = ux * (ct / rx) + vx * (st_sin / ry);
450                let ny = uy * (ct / rx) + vy * (st_sin / ry);
451                let nz = uz * (ct / rx) + vz * (st_sin / ry);
452                let nlen = (nx * nx + ny * ny + nz * nz).sqrt().max(1e-5);
453
454                let col =
455                    sample_countershade(st.dorsal_color, st.flank_color, st.ventral_color, st_sin);
456
457                self.positions.push([px, py, pz]);
458                self.normals.push([nx / nlen, ny / nlen, nz / nlen]);
459                self.colors.push(col);
460                self.uvs.push([u_uv, v_uv]);
461                self.layer_tags.push(layer);
462                self.joint_indices
463                    .push([st.primary_joint as u16, st.secondary_joint as u16, 0, 0]);
464                self.joint_weights.push([w1, w2, 0.0, 0.0]);
465            }
466        }
467
468        for si in 0..(n_st - 1) as u32 {
469            for s in 0..r_segs as u32 {
470                let i00 = base_idx + si * stride + s;
471                let i10 = i00 + stride;
472                let i01 = i00 + 1;
473                let i11 = i10 + 1;
474                self.indices
475                    .extend_from_slice(&[i00, i10, i11, i00, i11, i01]);
476            }
477        }
478
479        if cap_ends {
480            let first = &stations[0];
481            let c0_idx = self.positions.len() as u32;
482            self.positions.push(first.center);
483            self.normals.push([0.0, 0.0, -1.0]);
484            self.colors.push(first.flank_color);
485            self.uvs.push([0.5, 0.0]);
486            self.layer_tags.push(layer);
487            self.joint_indices.push([
488                first.primary_joint as u16,
489                first.secondary_joint as u16,
490                0,
491                0,
492            ]);
493            self.joint_weights
494                .push([first.primary_weight, 1.0 - first.primary_weight, 0.0, 0.0]);
495            for s in 0..r_segs as u32 {
496                self.indices
497                    .extend_from_slice(&[c0_idx, base_idx + s + 1, base_idx + s]);
498            }
499
500            let last = &stations[n_st - 1];
501            let last_ring = base_idx + ((n_st - 1) as u32) * stride;
502            let c1_idx = self.positions.len() as u32;
503            self.positions.push(last.center);
504            self.normals.push([0.0, 0.0, 1.0]);
505            self.colors.push(last.dorsal_color);
506            self.uvs.push([0.5, 1.0]);
507            self.layer_tags.push(layer);
508            self.joint_indices
509                .push([last.primary_joint as u16, last.secondary_joint as u16, 0, 0]);
510            self.joint_weights
511                .push([last.primary_weight, 1.0 - last.primary_weight, 0.0, 0.0]);
512            for s in 0..r_segs as u32 {
513                self.indices
514                    .extend_from_slice(&[c1_idx, last_ring + s, last_ring + s + 1]);
515            }
516        }
517    }
518
519    /// Builds an anatomical long bone with flared proximal/distal epiphyses (condyles),
520    /// curved cortical diaphysis shaft, and periosteal shading.
521    #[allow(clippy::too_many_arguments)]
522    pub fn push_long_bone_with_epiphyses(
523        &mut self,
524        prox: [f32; 3],
525        dist: [f32; 3],
526        shaft_r: f32,
527        condyle_r: f32,
528        bow_offset: [f32; 3],
529        bone_color: [f32; 4],
530        layer: ZoologicalAnatomicalLayer,
531        primary_joint: usize,
532        secondary_joint: usize,
533    ) {
534        let cartilage_tint = [
535            (bone_color[0] * 1.04).min(0.96),
536            (bone_color[1] * 1.04).min(0.95),
537            (bone_color[2] * 1.06).min(0.94),
538            bone_color[3],
539        ];
540        let shaft_shade = [
541            bone_color[0] * 0.94,
542            bone_color[1] * 0.93,
543            bone_color[2] * 0.91,
544            bone_color[3],
545        ];
546        let mut rings = [AnatomicalLoftRing {
547            center: prox,
548            radii: [condyle_r, condyle_r],
549            dorsal_color: cartilage_tint,
550            flank_color: bone_color,
551            ventral_color: shaft_shade,
552            primary_joint,
553            secondary_joint,
554            primary_weight: 0.9,
555        }; 6];
556
557        let ts = [0.0_f32, 0.14, 0.38, 0.62, 0.86, 1.0];
558        let r_scales = [
559            (condyle_r * 1.05, condyle_r * 0.92),
560            (condyle_r * 0.82, condyle_r * 0.78),
561            (shaft_r, shaft_r * 0.94),
562            (shaft_r * 0.96, shaft_r * 0.92),
563            (condyle_r * 0.80, condyle_r * 0.76),
564            (condyle_r * 1.02, condyle_r * 0.88),
565        ];
566
567        for i in 0..6 {
568            let t = ts[i];
569            let arch = (t * core::f32::consts::PI).sin();
570            let col = if !(0.2..=0.8).contains(&t) {
571                cartilage_tint
572            } else {
573                bone_color
574            };
575            rings[i] = AnatomicalLoftRing {
576                center: [
577                    prox[0] + (dist[0] - prox[0]) * t + bow_offset[0] * arch,
578                    prox[1] + (dist[1] - prox[1]) * t + bow_offset[1] * arch,
579                    prox[2] + (dist[2] - prox[2]) * t + bow_offset[2] * arch,
580                ],
581                radii: [r_scales[i].0, r_scales[i].1],
582                dorsal_color: col,
583                flank_color: bone_color,
584                ventral_color: shaft_shade,
585                primary_joint,
586                secondary_joint,
587                primary_weight: 1.0 - 0.75 * t,
588            };
589        }
590        self.push_countershaded_loft(&rings, 8, layer, true);
591    }
592
593    /// Sweeps an anatomically curved costal rib arch from a thoracic vertebra around the barrel
594    /// to the ventral sternum, transitioning from dorsal bone to ventral costal cartilage.
595    #[allow(clippy::too_many_arguments)]
596    pub fn push_curved_rib_arch(
597        &mut self,
598        spine_p: [f32; 3],
599        sternum_p: [f32; 3],
600        lateral_span: f32,
601        rib_r: f32,
602        bone_color: [f32; 4],
603        cartilage_color: [f32; 4],
604        layer: ZoologicalAnatomicalLayer,
605        primary_joint: usize,
606        secondary_joint: usize,
607    ) {
608        let mut rings = [AnatomicalLoftRing {
609            center: spine_p,
610            radii: [rib_r, rib_r],
611            dorsal_color: bone_color,
612            flank_color: bone_color,
613            ventral_color: bone_color,
614            primary_joint,
615            secondary_joint,
616            primary_weight: 0.75,
617        }; 6];
618
619        for (i, ring) in rings.iter_mut().enumerate() {
620            let t = i as f32 / 5.0;
621            let arch_x = (t * core::f32::consts::PI).sin() * lateral_span;
622            let arch_z = (t * core::f32::consts::PI).sin() * (-0.015);
623            let col = if t > 0.68 {
624                lerp_rgba(bone_color, cartilage_color, (t - 0.68) / 0.32)
625            } else {
626                bone_color
627            };
628            *ring = AnatomicalLoftRing {
629                center: [
630                    spine_p[0] + (sternum_p[0] - spine_p[0]) * t + arch_x,
631                    spine_p[1] + (sternum_p[1] - spine_p[1]) * t.powf(0.85),
632                    spine_p[2] + (sternum_p[2] - spine_p[2]) * t + arch_z,
633                ],
634                radii: [rib_r * (0.85 + 0.25 * (1.0 - t)), rib_r * 0.68],
635                dorsal_color: col,
636                flank_color: col,
637                ventral_color: col,
638                primary_joint,
639                secondary_joint,
640                primary_weight: 0.75,
641            };
642        }
643        self.push_countershaded_loft(&rings, 6, layer, false);
644    }
645
646    /// Builds a fusiform skeletal muscle belly with tapered ivory collagen tendon attachments
647    /// at origin and insertion and a swollen striated crimson belly in the middle.
648    #[allow(clippy::too_many_arguments)]
649    pub fn push_fusiform_muscle(
650        &mut self,
651        origin: [f32; 3],
652        insertion: [f32; 3],
653        belly_rx: f32,
654        belly_ry: f32,
655        belly_bow: [f32; 3],
656        muscle_color: [f32; 4],
657        tendon_color: [f32; 4],
658        layer: ZoologicalAnatomicalLayer,
659        primary_joint: usize,
660        secondary_joint: usize,
661    ) {
662        let dark_fascia = [
663            muscle_color[0] * 0.78,
664            muscle_color[1] * 0.75,
665            muscle_color[2] * 0.75,
666            muscle_color[3],
667        ];
668        let mut rings = [AnatomicalLoftRing {
669            center: origin,
670            radii: [belly_rx * 0.22, belly_ry * 0.22],
671            dorsal_color: tendon_color,
672            flank_color: tendon_color,
673            ventral_color: tendon_color,
674            primary_joint,
675            secondary_joint,
676            primary_weight: 0.85,
677        }; 7];
678
679        for (i, ring) in rings.iter_mut().enumerate() {
680            let t = i as f32 / 6.0;
681            let fusiform = (t * core::f32::consts::PI).sin().max(0.0).powf(0.75);
682            let r_scale = 0.18 + 0.82 * fusiform;
683            let tendon_blend = if t < 0.20 {
684                1.0 - (t / 0.20)
685            } else if t > 0.80 {
686                (t - 0.80) / 0.20
687            } else {
688                0.0
689            };
690            let dorsal_c = lerp_rgba(muscle_color, tendon_color, tendon_blend);
691            let ventral_c = lerp_rgba(dark_fascia, tendon_color, tendon_blend);
692
693            *ring = AnatomicalLoftRing {
694                center: [
695                    origin[0] + (insertion[0] - origin[0]) * t + belly_bow[0] * fusiform,
696                    origin[1] + (insertion[1] - origin[1]) * t + belly_bow[1] * fusiform,
697                    origin[2] + (insertion[2] - origin[2]) * t + belly_bow[2] * fusiform,
698                ],
699                radii: [belly_rx * r_scale, belly_ry * r_scale],
700                dorsal_color: dorsal_c,
701                flank_color: dorsal_c,
702                ventral_color: ventral_c,
703                primary_joint,
704                secondary_joint,
705                primary_weight: 1.0 - 0.70 * t,
706            };
707        }
708        self.push_countershaded_loft(&rings, 8, layer, true);
709    }
710
711    pub fn push_cylinder(
712        &mut self,
713        p1: [f32; 3],
714        p2: [f32; 3],
715        r1: f32,
716        r2: f32,
717        radial_segs: usize,
718        height_segs: usize,
719        color: [f32; 4],
720        layer: ZoologicalAnatomicalLayer,
721        primary_joint: usize,
722        secondary_joint: usize,
723        primary_weight: f32,
724    ) {
725        let base_idx = self.positions.len() as u32;
726        let axis = [p2[0] - p1[0], p2[1] - p1[1], p2[2] - p1[2]];
727        let height = (axis[0] * axis[0] + axis[1] * axis[1] + axis[2] * axis[2])
728            .sqrt()
729            .max(1e-5);
730        let dir = [axis[0] / height, axis[1] / height, axis[2] / height];
731
732        let up = if dir[1].abs() < 0.95 {
733            [0.0, 1.0, 0.0]
734        } else {
735            [1.0, 0.0, 0.0]
736        };
737        let side = [
738            dir[1] * up[2] - dir[2] * up[1],
739            dir[2] * up[0] - dir[0] * up[2],
740            dir[0] * up[1] - dir[1] * up[0],
741        ];
742        let side_len = (side[0] * side[0] + side[1] * side[1] + side[2] * side[2])
743            .sqrt()
744            .max(1e-5);
745        let u_vec = [side[0] / side_len, side[1] / side_len, side[2] / side_len];
746        let v_vec = [
747            dir[1] * u_vec[2] - dir[2] * u_vec[1],
748            dir[2] * u_vec[0] - dir[0] * u_vec[2],
749            dir[0] * u_vec[1] - dir[1] * u_vec[0],
750        ];
751
752        let r_segs = radial_segs.max(6);
753        let h_segs = height_segs.max(1);
754
755        for h in 0..=h_segs {
756            let t = h as f32 / h_segs as f32;
757            let center = [
758                p1[0] + dir[0] * height * t,
759                p1[1] + dir[1] * height * t,
760                p1[2] + dir[2] * height * t,
761            ];
762            let radius = r1 + (r2 - r1) * t;
763            let w1 = primary_weight;
764            let w2 = 1.0 - w1;
765
766            for s in 0..=r_segs {
767                let theta = (s as f32 / r_segs as f32) * core::f32::consts::TAU;
768                let cos_t = theta.cos();
769                let sin_t = theta.sin();
770
771                let normal = [
772                    u_vec[0] * cos_t + v_vec[0] * sin_t,
773                    u_vec[1] * cos_t + v_vec[1] * sin_t,
774                    u_vec[2] * cos_t + v_vec[2] * sin_t,
775                ];
776                let pos = [
777                    center[0] + normal[0] * radius,
778                    center[1] + normal[1] * radius,
779                    center[2] + normal[2] * radius,
780                ];
781
782                self.positions.push(pos);
783                self.normals.push(normal);
784                self.colors.push(color);
785                self.uvs.push([s as f32 / r_segs as f32, t]);
786                self.layer_tags.push(layer);
787                self.joint_indices
788                    .push([primary_joint as u16, secondary_joint as u16, 0, 0]);
789                self.joint_weights.push([w1, w2, 0.0, 0.0]);
790            }
791        }
792
793        let stride = (r_segs + 1) as u32;
794        for h in 0..h_segs as u32 {
795            for s in 0..r_segs as u32 {
796                let i00 = base_idx + h * stride + s;
797                let i10 = i00 + stride;
798                let i01 = i00 + 1;
799                let i11 = i10 + 1;
800
801                self.indices
802                    .extend_from_slice(&[i00, i10, i11, i00, i11, i01]);
803            }
804        }
805    }
806
807    pub fn push_ellipsoid(
808        &mut self,
809        center: [f32; 3],
810        radii: [f32; 3],
811        u_segs: usize,
812        v_segs: usize,
813        color: [f32; 4],
814        layer: ZoologicalAnatomicalLayer,
815        primary_joint: usize,
816        secondary_joint: usize,
817        primary_weight: f32,
818    ) {
819        let base_idx = self.positions.len() as u32;
820        let u_n = u_segs.max(8);
821        let v_n = v_segs.max(6);
822
823        for v in 0..=v_n {
824            let phi = (v as f32 / v_n as f32) * core::f32::consts::PI;
825            let sin_phi = phi.sin();
826            let cos_phi = phi.cos();
827
828            for u in 0..=u_n {
829                let theta = (u as f32 / u_n as f32) * core::f32::consts::TAU;
830                let cos_theta = theta.cos();
831                let sin_theta = theta.sin();
832
833                let nx = sin_phi * cos_theta;
834                let ny = cos_phi;
835                let nz = sin_phi * sin_theta;
836
837                let px = center[0] + radii[0] * nx;
838                let py = center[1] + radii[1] * ny;
839                let pz = center[2] + radii[2] * nz;
840
841                let normal = [
842                    nx / radii[0].max(1e-4),
843                    ny / radii[1].max(1e-4),
844                    nz / radii[2].max(1e-4),
845                ];
846                let n_len = (normal[0] * normal[0] + normal[1] * normal[1] + normal[2] * normal[2])
847                    .sqrt()
848                    .max(1e-5);
849                let unit_normal = [normal[0] / n_len, normal[1] / n_len, normal[2] / n_len];
850
851                self.positions.push([px, py, pz]);
852                self.normals.push(unit_normal);
853                self.colors.push(color);
854                self.uvs
855                    .push([u as f32 / u_n as f32, v as f32 / v_n as f32]);
856                self.layer_tags.push(layer);
857                self.joint_indices
858                    .push([primary_joint as u16, secondary_joint as u16, 0, 0]);
859                self.joint_weights
860                    .push([primary_weight, 1.0 - primary_weight, 0.0, 0.0]);
861            }
862        }
863
864        let stride = (u_n + 1) as u32;
865        for v in 0..v_n as u32 {
866            for u in 0..u_n as u32 {
867                let i00 = base_idx + v * stride + u;
868                let i10 = i00 + stride;
869                let i01 = i00 + 1;
870                let i11 = i10 + 1;
871
872                self.indices
873                    .extend_from_slice(&[i00, i10, i11, i00, i11, i01]);
874            }
875        }
876    }
877
878    pub fn push_box(
879        &mut self,
880        min: [f32; 3],
881        max: [f32; 3],
882        color: [f32; 4],
883        layer: ZoologicalAnatomicalLayer,
884        primary_joint: usize,
885    ) {
886        let base_idx = self.positions.len() as u32;
887
888        let corners = [
889            [min[0], min[1], min[2]],
890            [max[0], min[1], min[2]],
891            [max[0], max[1], min[2]],
892            [min[0], max[1], min[2]],
893            [min[0], min[1], max[2]],
894            [max[0], min[1], max[2]],
895            [max[0], max[1], max[2]],
896            [min[0], max[1], max[2]],
897        ];
898
899        let center = [
900            (min[0] + max[0]) * 0.5,
901            (min[1] + max[1]) * 0.5,
902            (min[2] + max[2]) * 0.5,
903        ];
904
905        for c in corners {
906            let n = [c[0] - center[0], c[1] - center[1], c[2] - center[2]];
907            let len = (n[0] * n[0] + n[1] * n[1] + n[2] * n[2]).sqrt().max(1e-5);
908            self.positions.push(c);
909            self.normals.push([n[0] / len, n[1] / len, n[2] / len]);
910            self.colors.push(color);
911            self.uvs.push([0.5, 0.5]);
912            self.layer_tags.push(layer);
913            self.joint_indices.push([primary_joint as u16, 0, 0, 0]);
914            self.joint_weights.push([1.0, 0.0, 0.0, 0.0]);
915        }
916
917        let face_indices = [
918            0, 2, 1, 0, 3, 2, // -Z
919            4, 5, 6, 4, 6, 7, // +Z
920            0, 1, 5, 0, 5, 4, // -Y
921            3, 6, 2, 3, 7, 6, // +Y
922            0, 4, 7, 0, 7, 3, // -X
923            1, 2, 6, 1, 6, 5, // +X
924        ];
925
926        for &idx in &face_indices {
927            self.indices.push(base_idx + idx);
928        }
929    }
930}
931
932// ── PBR Material Builder Helpers ─────────────────────────────────────────────
933
934pub fn make_pbr_material(
935    id_str: &str,
936    base_color: [f32; 4],
937    roughness: f32,
938    metallic: f32,
939) -> MaterialRecord {
940    let mut mat = MaterialRecord::legacy_default();
941    mat.id = q_hash(id_str);
942    mat.shading_model = ShadingModel::MetallicRoughness;
943    mat.opacity_mode = OpacityMode::Opaque;
944    mat.base_color = base_color;
945    mat.roughness = roughness;
946    mat.metallic = metallic;
947    mat
948}
949
950// ── Main Anatomical 10D Builder ──────────────────────────────────────────────
951
952/// Silhouette-level comparative profile for the broad fauna rigs. Ratios are
953/// authored presentation defaults, not validated species measurements.
954#[derive(Clone, Copy)]
955struct ArchetypeMorphology {
956    trunk: f32,
957    body_width: f32,
958    neck: f32,
959    head: f32,
960    tail: f32,
961    forelimb: f32,
962    hindlimb: f32,
963    shoulder_span: f32,
964    patagium: f32,
965}
966
967impl ArchetypeMorphology {
968    fn for_archetype(archetype: FaunaBiomechanicalArchetype) -> Self {
969        use FaunaBiomechanicalArchetype as A;
970        match archetype {
971            A::MacropodSaltatorial => Self {
972                trunk: 1.05,
973                body_width: 1.05,
974                neck: 0.9,
975                head: 0.95,
976                tail: 1.55,
977                forelimb: 0.72,
978                hindlimb: 1.32,
979                shoulder_span: 0.9,
980                patagium: 0.0,
981            },
982            A::VombatidFossorial => Self {
983                trunk: 1.05,
984                body_width: 1.42,
985                neck: 0.72,
986                head: 1.12,
987                tail: 0.35,
988                forelimb: 0.82,
989                hindlimb: 0.82,
990                shoulder_span: 0.95,
991                patagium: 0.0,
992            },
993            A::PhascolarctidArboreal => Self {
994                trunk: 0.95,
995                body_width: 1.08,
996                neck: 0.88,
997                head: 1.05,
998                tail: 0.62,
999                forelimb: 1.12,
1000                hindlimb: 0.96,
1001                shoulder_span: 1.02,
1002                patagium: 0.0,
1003            },
1004            A::PetauridGlider => Self {
1005                trunk: 0.92,
1006                body_width: 0.82,
1007                neck: 0.88,
1008                head: 0.92,
1009                tail: 1.3,
1010                forelimb: 1.15,
1011                hindlimb: 0.98,
1012                shoulder_span: 1.12,
1013                patagium: 0.72,
1014            },
1015            A::DasyuridPredator => Self {
1016                trunk: 0.96,
1017                body_width: 0.82,
1018                neck: 1.05,
1019                head: 0.9,
1020                tail: 1.12,
1021                forelimb: 0.98,
1022                hindlimb: 1.12,
1023                shoulder_span: 0.92,
1024                patagium: 0.0,
1025            },
1026            A::PteropodidChiroptera => Self {
1027                trunk: 0.82,
1028                body_width: 0.9,
1029                neck: 0.76,
1030                head: 0.84,
1031                tail: 0.42,
1032                forelimb: 1.62,
1033                hindlimb: 0.72,
1034                shoulder_span: 1.55,
1035                patagium: 1.0,
1036            },
1037            A::MarinePinnipedCetacean => Self {
1038                trunk: 1.48,
1039                body_width: 0.86,
1040                neck: 0.64,
1041                head: 1.08,
1042                tail: 1.0,
1043                forelimb: 1.16,
1044                hindlimb: 0.28,
1045                shoulder_span: 1.1,
1046                patagium: 0.0,
1047            },
1048            A::RatiteBipedal => Self {
1049                trunk: 1.12,
1050                body_width: 0.86,
1051                neck: 1.42,
1052                head: 0.78,
1053                tail: 0.42,
1054                forelimb: 0.58,
1055                hindlimb: 1.34,
1056                shoulder_span: 0.82,
1057                patagium: 0.0,
1058            },
1059            A::RaptorSoaring => Self {
1060                trunk: 0.98,
1061                body_width: 0.88,
1062                neck: 1.08,
1063                head: 0.92,
1064                tail: 0.82,
1065                forelimb: 1.38,
1066                hindlimb: 0.82,
1067                shoulder_span: 1.42,
1068                patagium: 0.0,
1069            },
1070            A::PasserinePsittacine => Self {
1071                trunk: 0.82,
1072                body_width: 0.82,
1073                neck: 0.9,
1074                head: 0.88,
1075                tail: 0.88,
1076                forelimb: 1.18,
1077                hindlimb: 0.9,
1078                shoulder_span: 1.16,
1079                patagium: 0.0,
1080            },
1081            A::SquamateSprawling => Self {
1082                trunk: 1.28,
1083                body_width: 0.92,
1084                neck: 0.78,
1085                head: 0.92,
1086                tail: 1.34,
1087                forelimb: 0.72,
1088                hindlimb: 0.72,
1089                shoulder_span: 1.0,
1090                patagium: 0.0,
1091            },
1092            A::SerpentineUndulatory => Self {
1093                trunk: 1.62,
1094                body_width: 0.62,
1095                neck: 0.68,
1096                head: 0.72,
1097                tail: 1.45,
1098                forelimb: 0.18,
1099                hindlimb: 0.18,
1100                shoulder_span: 0.8,
1101                patagium: 0.0,
1102            },
1103            A::MonotremeTeleostAmphibian => Self {
1104                trunk: 1.08,
1105                body_width: 1.08,
1106                neck: 0.72,
1107                head: 1.0,
1108                tail: 0.9,
1109                forelimb: 0.88,
1110                hindlimb: 0.88,
1111                shoulder_span: 1.0,
1112                patagium: 0.0,
1113            },
1114        }
1115    }
1116}
1117
1118/// Builds a high-resolution, 3-layer Comparative Vertebrate Anatomical Digital Twin
1119/// bound to `FaunaSkeletalRig10d` (18 PGA joints) and sealed into a `.10d` Living Container.
1120///
1121/// Features:
1122/// - >= 1,800 vertices across 8 Osteology regions, 8 Myology groups, and External Integument.
1123/// - Distinct submesh ranges for all 17 anatomical structures.
1124/// - Valid `.10d` container with `MAT4`, `UV01`, `FNRM`, `SRD1`, `PROC1`, `EONT1`, `MRP1`, and `PROV`.
1125/// - 3 Morph Targets: Costal Respiration, Gular Vocalization, and Achilles Tendon Strain.
1126pub fn build_scale5_vertebrate_anatomy_10d(
1127    archetype: FaunaBiomechanicalArchetype,
1128    osteology_vis_01: f32,
1129    myology_vis_01: f32,
1130    integument_vis_01: f32,
1131    explode_layer_01: f32,
1132) -> CompiledVertebrateAnatomy10d {
1133    let (base_body_len, hip_height) = archetype.default_dimensions();
1134    let morphology = ArchetypeMorphology::for_archetype(archetype);
1135    let body_len = base_body_len * morphology.trunk;
1136
1137    let mut acc = MeshAccumulator::new();
1138    let mut submesh_ranges = Vec::with_capacity(17);
1139    let mut materials = Vec::with_capacity(17);
1140
1141    // Anatomical proportions
1142    let spine_len = (body_len * 0.32).max(0.10);
1143    let neck_len = (body_len * 0.18 * morphology.neck).max(0.06);
1144    let head_len = (body_len * 0.22 * morphology.head).max(0.08);
1145    let tail_len = (body_len * 0.40 * morphology.tail).max(0.12);
1146    let half_width = (body_len * 0.14 * morphology.body_width).max(0.04);
1147    let femur_len = (hip_height * 0.48 * morphology.hindlimb).max(0.025);
1148    let tibia_len = (hip_height * 0.54 * morphology.hindlimb).max(0.025);
1149
1150    // ── LAYER 0: OSTEOLOGY (8 Regions) ───────────────────────────────────────
1151    let ost_start_v = acc.positions.len();
1152    let bone_ivory = [0.89, 0.87, 0.81, 1.0];
1153    let bone_dense = [0.85, 0.83, 0.77, 1.0];
1154    let cartilage_blue = [0.82, 0.85, 0.86, 1.0];
1155    let enamel_white = [0.95, 0.94, 0.91, 1.0];
1156    let tendon_ivory = [0.92, 0.90, 0.85, 1.0];
1157
1158    let is_monotreme = archetype == FaunaBiomechanicalArchetype::MonotremeTeleostAmphibian;
1159    let is_avian = matches!(
1160        archetype,
1161        FaunaBiomechanicalArchetype::RaptorSoaring
1162            | FaunaBiomechanicalArchetype::PasserinePsittacine
1163            | FaunaBiomechanicalArchetype::RatiteBipedal
1164    );
1165
1166    // 1. Cranium & Rostrum (Multi-Station Sculpted Neurocranium, Nasal Bridge, Rostrum & Zygomatic Arches)
1167    let cranium_start = acc.indices.len() as u32;
1168    let cranium_head_pos = [0.0, hip_height + neck_len * 0.6, spine_len * 0.7 + neck_len];
1169    let rostrum_tip = [
1170        0.0,
1171        cranium_head_pos[1] - 0.025,
1172        cranium_head_pos[2] + head_len,
1173    ];
1174
1175    let rostrum_rx = if is_monotreme {
1176        half_width * 0.44
1177    } else if is_avian {
1178        half_width * 0.08
1179    } else {
1180        half_width * 0.20
1181    };
1182    let rostrum_ry = if is_monotreme {
1183        half_width * 0.10
1184    } else if is_avian {
1185        half_width * 0.08
1186    } else {
1187        half_width * 0.18
1188    };
1189
1190    let cranium_loft = [
1191        AnatomicalLoftRing {
1192            center: [
1193                0.0,
1194                cranium_head_pos[1] - 0.01,
1195                cranium_head_pos[2] - head_len * 0.34,
1196            ],
1197            radii: [half_width * 0.38, half_width * 0.36],
1198            dorsal_color: bone_ivory,
1199            flank_color: bone_dense,
1200            ventral_color: bone_dense,
1201            primary_joint: JOINT_HEAD,
1202            secondary_joint: JOINT_NECK,
1203            primary_weight: 0.75,
1204        },
1205        AnatomicalLoftRing {
1206            center: cranium_head_pos,
1207            radii: [half_width * 0.56, half_width * 0.50],
1208            dorsal_color: bone_ivory,
1209            flank_color: bone_ivory,
1210            ventral_color: bone_dense,
1211            primary_joint: JOINT_HEAD,
1212            secondary_joint: JOINT_NECK,
1213            primary_weight: 0.90,
1214        },
1215        AnatomicalLoftRing {
1216            center: [
1217                0.0,
1218                cranium_head_pos[1] + 0.005,
1219                cranium_head_pos[2] + head_len * 0.32,
1220            ],
1221            radii: [half_width * 0.44, half_width * 0.38],
1222            dorsal_color: bone_ivory,
1223            flank_color: bone_dense,
1224            ventral_color: bone_dense,
1225            primary_joint: JOINT_HEAD,
1226            secondary_joint: JOINT_JAW,
1227            primary_weight: 0.92,
1228        },
1229        AnatomicalLoftRing {
1230            center: [
1231                0.0,
1232                cranium_head_pos[1] - 0.012,
1233                cranium_head_pos[2] + head_len * 0.68,
1234            ],
1235            radii: [
1236                (half_width * 0.32).max(rostrum_rx),
1237                (half_width * 0.25).max(rostrum_ry),
1238            ],
1239            dorsal_color: bone_ivory,
1240            flank_color: bone_dense,
1241            ventral_color: bone_dense,
1242            primary_joint: JOINT_HEAD,
1243            secondary_joint: JOINT_JAW,
1244            primary_weight: 0.95,
1245        },
1246        AnatomicalLoftRing {
1247            center: rostrum_tip,
1248            radii: [rostrum_rx, rostrum_ry],
1249            dorsal_color: bone_ivory,
1250            flank_color: bone_dense,
1251            ventral_color: bone_dense,
1252            primary_joint: JOINT_HEAD,
1253            secondary_joint: JOINT_JAW,
1254            primary_weight: 0.98,
1255        },
1256    ];
1257    acc.push_countershaded_loft(
1258        &cranium_loft,
1259        12,
1260        ZoologicalAnatomicalLayer::Osteology,
1261        true,
1262    );
1263
1264    // Sculpted Zygomatic Arches & Supraorbital Ridges (L+R)
1265    for side in [-1.0_f32, 1.0_f32] {
1266        acc.push_long_bone_with_epiphyses(
1267            [
1268                side * half_width * 0.44,
1269                cranium_head_pos[1] - 0.02,
1270                cranium_head_pos[2] - 0.03,
1271            ],
1272            [
1273                side * half_width * 0.38,
1274                cranium_head_pos[1] - 0.01,
1275                cranium_head_pos[2] + head_len * 0.42,
1276            ],
1277            0.008,
1278            0.012,
1279            [side * half_width * 0.14, -0.008, 0.0],
1280            bone_ivory,
1281            ZoologicalAnatomicalLayer::Osteology,
1282            JOINT_HEAD,
1283            JOINT_NECK,
1284        );
1285    }
1286
1287    let cranium_mat = make_pbr_material("mat_ost_cranium", bone_ivory, 0.45, 0.05);
1288    materials.push(cranium_mat);
1289    submesh_ranges.push(SubmeshRange {
1290        first_index: cranium_start,
1291        index_count: acc.indices.len() as u32 - cranium_start,
1292        material_id: cranium_mat.id,
1293        semantic_id: q_hash("urn:qualia:bio:submesh:cranium_rostrum"),
1294    });
1295
1296    // 2. Mandible & Dentition (Curved Mandibular Rami, Coronoid Process, Procumbent Incisors & Molars)
1297    let mandible_start = acc.indices.len() as u32;
1298    let jaw_joint_l = [
1299        -half_width * 0.40,
1300        cranium_head_pos[1] - 0.04,
1301        cranium_head_pos[2],
1302    ];
1303    let jaw_joint_r = [
1304        half_width * 0.40,
1305        cranium_head_pos[1] - 0.04,
1306        cranium_head_pos[2],
1307    ];
1308    let chin_pos = [0.0, cranium_head_pos[1] - 0.07, rostrum_tip[2] - 0.02];
1309
1310    for (side, jaw_j) in [(-1.0_f32, jaw_joint_l), (1.0_f32, jaw_joint_r)] {
1311        // Mandibular ramus & body with masseteric curvature
1312        acc.push_long_bone_with_epiphyses(
1313            jaw_j,
1314            chin_pos,
1315            half_width * 0.11,
1316            half_width * 0.16,
1317            [side * half_width * 0.08, -0.018, 0.0],
1318            bone_ivory,
1319            ZoologicalAnatomicalLayer::Osteology,
1320            JOINT_JAW,
1321            JOINT_HEAD,
1322        );
1323        // Ascending coronoid process
1324        acc.push_cylinder(
1325            [jaw_j[0] * 0.88, jaw_j[1] - 0.01, jaw_j[2] + head_len * 0.14],
1326            [
1327                jaw_j[0] * 0.84,
1328                jaw_j[1] + 0.032,
1329                jaw_j[2] + head_len * 0.10,
1330            ],
1331            0.009,
1332            0.004,
1333            6,
1334            2,
1335            bone_dense,
1336            ZoologicalAnatomicalLayer::Osteology,
1337            JOINT_JAW,
1338            JOINT_HEAD,
1339            0.90,
1340        );
1341        // Row of 4 bilophodont/hypsodont cheek molars along each dentary
1342        for m in 0..4 {
1343            let mt = 0.35 + (m as f32) * 0.14;
1344            let mx = jaw_j[0] * (1.0 - mt) + chin_pos[0] * mt;
1345            let my = jaw_j[1] * (1.0 - mt) + chin_pos[1] * mt + 0.014;
1346            let mz = jaw_j[2] * (1.0 - mt) + chin_pos[2] * mt;
1347            acc.push_ellipsoid(
1348                [mx, my, mz],
1349                [0.007, 0.009, 0.008],
1350                6,
1351                4,
1352                enamel_white,
1353                ZoologicalAnatomicalLayer::Osteology,
1354                JOINT_JAW,
1355                JOINT_HEAD,
1356                0.95,
1357            );
1358        }
1359    }
1360
1361    // Procumbent lower incisors (characteristic of Diprotodontia)
1362    let incisor_tip = [0.0, chin_pos[1] + 0.016, chin_pos[2] + 0.038];
1363    acc.push_cylinder(
1364        chin_pos,
1365        incisor_tip,
1366        0.008,
1367        0.004,
1368        8,
1369        2,
1370        enamel_white,
1371        ZoologicalAnatomicalLayer::Osteology,
1372        JOINT_JAW,
1373        JOINT_HEAD,
1374        0.95,
1375    );
1376
1377    let mandible_mat = make_pbr_material("mat_ost_mandible", [0.90, 0.88, 0.82, 1.0], 0.32, 0.02);
1378    materials.push(mandible_mat);
1379    submesh_ranges.push(SubmeshRange {
1380        first_index: mandible_start,
1381        index_count: acc.indices.len() as u32 - mandible_start,
1382        material_id: mandible_mat.id,
1383        semantic_id: q_hash("urn:qualia:bio:submesh:mandible_dentition"),
1384    });
1385
1386    // 3. Cervical, Thoracic & Lumbar Vertebrae (Segmented Centra, Neural Spines & Transverse Processes)
1387    let vert_start = acc.indices.len() as u32;
1388    let pelvis_pos = [0.0, hip_height, 0.0];
1389    let chest_pos = [0.0, hip_height + 0.05, spine_len * 0.7];
1390
1391    // Cervical vertebral loft (S-curved neck column)
1392    let cervical_loft = [
1393        AnatomicalLoftRing {
1394            center: chest_pos,
1395            radii: [half_width * 0.21, half_width * 0.19],
1396            dorsal_color: bone_dense,
1397            flank_color: bone_ivory,
1398            ventral_color: cartilage_blue,
1399            primary_joint: JOINT_CHEST,
1400            secondary_joint: JOINT_NECK,
1401            primary_weight: 0.65,
1402        },
1403        AnatomicalLoftRing {
1404            center: [
1405                0.0,
1406                (chest_pos[1] + cranium_head_pos[1]) * 0.46,
1407                (chest_pos[2] + cranium_head_pos[2]) * 0.52,
1408            ],
1409            radii: [half_width * 0.19, half_width * 0.17],
1410            dorsal_color: bone_ivory,
1411            flank_color: bone_dense,
1412            ventral_color: cartilage_blue,
1413            primary_joint: JOINT_NECK,
1414            secondary_joint: JOINT_CHEST,
1415            primary_weight: 0.80,
1416        },
1417        AnatomicalLoftRing {
1418            center: cranium_head_pos,
1419            radii: [half_width * 0.17, half_width * 0.16],
1420            dorsal_color: bone_ivory,
1421            flank_color: bone_dense,
1422            ventral_color: bone_dense,
1423            primary_joint: JOINT_NECK,
1424            secondary_joint: JOINT_HEAD,
1425            primary_weight: 0.75,
1426        },
1427    ];
1428    acc.push_countershaded_loft(
1429        &cervical_loft,
1430        8,
1431        ZoologicalAnatomicalLayer::Osteology,
1432        false,
1433    );
1434
1435    // Thoracic & Lumbar vertebral column with curved dorsal neural spines and lateral transverse processes
1436    acc.push_cylinder(
1437        pelvis_pos,
1438        chest_pos,
1439        half_width * 0.24,
1440        half_width * 0.20,
1441        8,
1442        7,
1443        bone_dense,
1444        ZoologicalAnatomicalLayer::Osteology,
1445        JOINT_SPINE,
1446        JOINT_CHEST,
1447        0.55,
1448    );
1449
1450    for s in 1..=7 {
1451        let t = s as f32 / 8.0;
1452        let c = [
1453            pelvis_pos[0] + (chest_pos[0] - pelvis_pos[0]) * t,
1454            pelvis_pos[1] + (chest_pos[1] - pelvis_pos[1]) * t,
1455            pelvis_pos[2] + (chest_pos[2] - pelvis_pos[2]) * t,
1456        ];
1457        // Dorsal spinous process (taller over withers/thorax, angling caudally)
1458        let spine_h = half_width * (0.34 + 0.22 * (t * core::f32::consts::PI).sin());
1459        let tilt_z = if t > 0.45 { -0.018 } else { 0.008 };
1460        acc.push_cylinder(
1461            [c[0], c[1] + half_width * 0.14, c[2]],
1462            [c[0], c[1] + half_width * 0.14 + spine_h, c[2] + tilt_z],
1463            0.008,
1464            0.004,
1465            6,
1466            2,
1467            bone_ivory,
1468            ZoologicalAnatomicalLayer::Osteology,
1469            JOINT_SPINE,
1470            JOINT_CHEST,
1471            1.0 - t * 0.6,
1472        );
1473        // Paired lumbar/thoracic transverse processes
1474        let tp_span = half_width * (0.42 - 0.14 * t);
1475        acc.push_cylinder(
1476            [-tp_span, c[1] - 0.004, c[2]],
1477            [tp_span, c[1] - 0.004, c[2]],
1478            0.006,
1479            0.006,
1480            6,
1481            2,
1482            bone_dense,
1483            ZoologicalAnatomicalLayer::Osteology,
1484            JOINT_SPINE,
1485            JOINT_CHEST,
1486            1.0 - t * 0.6,
1487        );
1488    }
1489
1490    let vert_mat = make_pbr_material("mat_ost_vertebrae", bone_dense, 0.50, 0.02);
1491    materials.push(vert_mat);
1492    submesh_ranges.push(SubmeshRange {
1493        first_index: vert_start,
1494        index_count: acc.indices.len() as u32 - vert_start,
1495        material_id: vert_mat.id,
1496        semantic_id: q_hash("urn:qualia:bio:submesh:vertebrae"),
1497    });
1498
1499    // 4. Ribcage & Sternum (8 Pairs of Anatomically Curved Costal Rib Arches, Sternebrae / Carina & Furcula)
1500    let rib_start = acc.indices.len() as u32;
1501    let sternum_y = chest_pos[1] - half_width * 0.78;
1502    let sternum_pos = [0.0, sternum_y, chest_pos[2] * 0.80];
1503
1504    for r in 1..=8 {
1505        let t = r as f32 / 9.0;
1506        let spine_p = [
1507            pelvis_pos[0] + (chest_pos[0] - pelvis_pos[0]) * (0.24 + 0.70 * t),
1508            pelvis_pos[1] + (chest_pos[1] - pelvis_pos[1]) * (0.24 + 0.70 * t),
1509            pelvis_pos[2] + (chest_pos[2] - pelvis_pos[2]) * (0.24 + 0.70 * t),
1510        ];
1511        let sternum_p = [
1512            sternum_pos[0],
1513            sternum_pos[1] + 0.01 * (1.0 - (t * core::f32::consts::PI).sin()),
1514            sternum_pos[2] + (t - 0.5) * spine_len * 0.48,
1515        ];
1516        let barrel_bulge = half_width * (0.58 + 0.34 * (t * core::f32::consts::PI).sin());
1517        acc.push_curved_rib_arch(
1518            spine_p,
1519            sternum_p,
1520            -barrel_bulge,
1521            0.007,
1522            bone_ivory,
1523            cartilage_blue,
1524            ZoologicalAnatomicalLayer::Osteology,
1525            JOINT_CHEST,
1526            JOINT_SPINE,
1527        );
1528        acc.push_curved_rib_arch(
1529            spine_p,
1530            sternum_p,
1531            barrel_bulge,
1532            0.007,
1533            bone_ivory,
1534            cartilage_blue,
1535            ZoologicalAnatomicalLayer::Osteology,
1536            JOINT_CHEST,
1537            JOINT_SPINE,
1538        );
1539    }
1540
1541    // Sternum / Keeled Carina loft
1542    let carina_depth = if is_avian {
1543        half_width * 0.58
1544    } else {
1545        half_width * 0.14
1546    };
1547    let sternum_loft = [
1548        AnatomicalLoftRing {
1549            center: [
1550                0.0,
1551                sternum_pos[1] - carina_depth * 0.3,
1552                sternum_pos[2] - spine_len * 0.25,
1553            ],
1554            radii: [0.012, carina_depth * 0.45],
1555            dorsal_color: bone_dense,
1556            flank_color: bone_ivory,
1557            ventral_color: cartilage_blue,
1558            primary_joint: JOINT_CHEST,
1559            secondary_joint: JOINT_SPINE,
1560            primary_weight: 0.85,
1561        },
1562        AnatomicalLoftRing {
1563            center: [0.0, sternum_pos[1] - carina_depth * 0.5, sternum_pos[2]],
1564            radii: [0.014, carina_depth * 0.65],
1565            dorsal_color: bone_ivory,
1566            flank_color: bone_ivory,
1567            ventral_color: bone_dense,
1568            primary_joint: JOINT_CHEST,
1569            secondary_joint: JOINT_SPINE,
1570            primary_weight: 0.90,
1571        },
1572        AnatomicalLoftRing {
1573            center: [
1574                0.0,
1575                sternum_pos[1] - carina_depth * 0.2,
1576                sternum_pos[2] + spine_len * 0.26,
1577            ],
1578            radii: [0.016, carina_depth * 0.35],
1579            dorsal_color: bone_ivory,
1580            flank_color: bone_dense,
1581            ventral_color: bone_dense,
1582            primary_joint: JOINT_CHEST,
1583            secondary_joint: JOINT_NECK,
1584            primary_weight: 0.92,
1585        },
1586    ];
1587    acc.push_countershaded_loft(&sternum_loft, 8, ZoologicalAnatomicalLayer::Osteology, true);
1588
1589    let rib_mat = make_pbr_material("mat_ost_ribcage", [0.83, 0.81, 0.75, 1.0], 0.42, 0.02);
1590    materials.push(rib_mat);
1591    submesh_ranges.push(SubmeshRange {
1592        first_index: rib_start,
1593        index_count: acc.indices.len() as u32 - rib_start,
1594        material_id: rib_mat.id,
1595        semantic_id: q_hash("urn:qualia:bio:submesh:ribcage_sternum"),
1596    });
1597
1598    // 5. Pectoral Girdle & Forelimb (Sculpted Scapular Blades, Humerus, Radius/Ulna & Digits)
1599    let pect_start = acc.indices.len() as u32;
1600    let shoulder_l = [
1601        -half_width * 0.70 * morphology.shoulder_span,
1602        chest_pos[1] - 0.02,
1603        chest_pos[2] * 0.9,
1604    ];
1605    let shoulder_r = [
1606        half_width * 0.70 * morphology.shoulder_span,
1607        chest_pos[1] - 0.02,
1608        chest_pos[2] * 0.9,
1609    ];
1610    let elbow_l = [
1611        -half_width * 0.80 * morphology.shoulder_span,
1612        chest_pos[1] - femur_len * 0.55 * morphology.forelimb,
1613        shoulder_l[2] - 0.04,
1614    ];
1615    let elbow_r = [
1616        half_width * 0.80 * morphology.shoulder_span,
1617        chest_pos[1] - femur_len * 0.55 * morphology.forelimb,
1618        shoulder_r[2] - 0.04,
1619    ];
1620    let wrist_l = [
1621        -half_width * 0.75 * morphology.shoulder_span,
1622        chest_pos[1] - femur_len * 0.95 * morphology.forelimb,
1623        elbow_l[2] + 0.08,
1624    ];
1625    let wrist_r = [
1626        half_width * 0.75 * morphology.shoulder_span,
1627        chest_pos[1] - femur_len * 0.95 * morphology.forelimb,
1628        elbow_r[2] + 0.08,
1629    ];
1630
1631    for (side, sh, el, wr) in [
1632        (-1.0_f32, shoulder_l, elbow_l, wrist_l),
1633        (1.0_f32, shoulder_r, elbow_r, wrist_r),
1634    ] {
1635        // Flared triangular scapular blade with scapular spine
1636        let scap_loft = [
1637            AnatomicalLoftRing {
1638                center: sh,
1639                radii: [0.014, 0.020],
1640                dorsal_color: cartilage_blue,
1641                flank_color: bone_ivory,
1642                ventral_color: bone_dense,
1643                primary_joint: JOINT_LEFT_SHOULDER,
1644                secondary_joint: JOINT_CHEST,
1645                primary_weight: 0.85,
1646            },
1647            AnatomicalLoftRing {
1648                center: [
1649                    sh[0] * 0.88,
1650                    sh[1] + half_width * 0.34,
1651                    sh[2] - spine_len * 0.12,
1652                ],
1653                radii: [0.010, 0.042],
1654                dorsal_color: bone_ivory,
1655                flank_color: bone_ivory,
1656                ventral_color: bone_dense,
1657                primary_joint: JOINT_LEFT_SHOULDER,
1658                secondary_joint: JOINT_CHEST,
1659                primary_weight: 0.70,
1660            },
1661            AnatomicalLoftRing {
1662                center: [
1663                    sh[0] * 0.72,
1664                    sh[1] + half_width * 0.56,
1665                    sh[2] - spine_len * 0.22,
1666                ],
1667                radii: [0.008, 0.056],
1668                dorsal_color: cartilage_blue,
1669                flank_color: bone_ivory,
1670                ventral_color: bone_dense,
1671                primary_joint: JOINT_CHEST,
1672                secondary_joint: JOINT_LEFT_SHOULDER,
1673                primary_weight: 0.65,
1674            },
1675        ];
1676        acc.push_countershaded_loft(&scap_loft, 8, ZoologicalAnatomicalLayer::Osteology, true);
1677
1678        // Humerus with proximal head and distal trochlear condyles
1679        acc.push_long_bone_with_epiphyses(
1680            sh,
1681            el,
1682            half_width * 0.11,
1683            half_width * 0.16,
1684            [side * 0.008, 0.0, 0.008],
1685            bone_ivory,
1686            ZoologicalAnatomicalLayer::Osteology,
1687            JOINT_LEFT_SHOULDER,
1688            JOINT_LEFT_ELBOW,
1689        );
1690        // Radius & Ulna with olecranon process
1691        acc.push_long_bone_with_epiphyses(
1692            [el[0], el[1] + 0.012, el[2] - 0.014],
1693            wr,
1694            half_width * 0.085,
1695            half_width * 0.12,
1696            [0.0, -0.006, 0.006],
1697            bone_ivory,
1698            ZoologicalAnatomicalLayer::Osteology,
1699            JOINT_LEFT_ELBOW,
1700            JOINT_LEFT_WRIST_WING,
1701        );
1702        // Metacarpals & phalanges
1703        for d in -1..=1 {
1704            let dx = (d as f32) * 0.010;
1705            acc.push_cylinder(
1706                [wr[0] + dx, wr[1], wr[2]],
1707                [wr[0] + dx * 1.3, wr[1] - 0.025, wr[2] + 0.035],
1708                0.006,
1709                0.003,
1710                6,
1711                2,
1712                bone_dense,
1713                ZoologicalAnatomicalLayer::Osteology,
1714                JOINT_LEFT_WRIST_WING,
1715                JOINT_LEFT_ELBOW,
1716                0.95,
1717            );
1718        }
1719    }
1720
1721    let pect_mat = make_pbr_material("mat_ost_pectoral", bone_ivory, 0.40, 0.02);
1722    materials.push(pect_mat);
1723    submesh_ranges.push(SubmeshRange {
1724        first_index: pect_start,
1725        index_count: acc.indices.len() as u32 - pect_start,
1726        material_id: pect_mat.id,
1727        semantic_id: q_hash("urn:qualia:bio:submesh:pectoral_forelimb"),
1728    });
1729
1730    // 6. Pelvic Girdle & EPIPUBIC BONES (Sculpted Ilium, Ischium, Pubis & Paired Ossa Epipubica)
1731    let pelvis_start = acc.indices.len() as u32;
1732    let ilium_l = [
1733        -half_width * 0.62,
1734        pelvis_pos[1] + 0.045,
1735        pelvis_pos[2] + 0.07,
1736    ];
1737    let ilium_r = [
1738        half_width * 0.62,
1739        pelvis_pos[1] + 0.045,
1740        pelvis_pos[2] + 0.07,
1741    ];
1742    let ischium_l = [
1743        -half_width * 0.52,
1744        pelvis_pos[1] - 0.035,
1745        pelvis_pos[2] - 0.075,
1746    ];
1747    let ischium_r = [
1748        half_width * 0.52,
1749        pelvis_pos[1] - 0.035,
1750        pelvis_pos[2] - 0.075,
1751    ];
1752    let pubis_pos = [0.0, pelvis_pos[1] - half_width * 0.45, pelvis_pos[2] + 0.04];
1753
1754    for (il, isch, hip_j) in [
1755        (ilium_l, ischium_l, JOINT_LEFT_HIP),
1756        (ilium_r, ischium_r, JOINT_RIGHT_HIP),
1757    ] {
1758        // Ilium -> Acetabulum -> Ischium sculpted pelvic wing
1759        acc.push_long_bone_with_epiphyses(
1760            il,
1761            isch,
1762            half_width * 0.14,
1763            half_width * 0.21,
1764            [0.0, 0.012, 0.0],
1765            bone_ivory,
1766            ZoologicalAnatomicalLayer::Osteology,
1767            JOINT_PELVIS_ROOT,
1768            hip_j,
1769        );
1770        // Pubic ramus arch
1771        acc.push_long_bone_with_epiphyses(
1772            pubis_pos,
1773            il,
1774            half_width * 0.09,
1775            half_width * 0.13,
1776            [0.0, -0.010, 0.0],
1777            bone_dense,
1778            ZoologicalAnatomicalLayer::Osteology,
1779            JOINT_PELVIS_ROOT,
1780            hip_j,
1781        );
1782    }
1783
1784    // ── EPIPUBIC BONES (Ossa Epipubica) ──
1785    let epipubic_len = half_width * 0.85;
1786    let epipubic_tip_l = [
1787        -half_width * 0.24,
1788        pubis_pos[1] + epipubic_len * 0.40,
1789        pubis_pos[2] + epipubic_len * 0.90,
1790    ];
1791    let epipubic_tip_r = [
1792        half_width * 0.24,
1793        pubis_pos[1] + epipubic_len * 0.40,
1794        pubis_pos[2] + epipubic_len * 0.90,
1795    ];
1796
1797    acc.push_long_bone_with_epiphyses(
1798        [-0.02, pubis_pos[1], pubis_pos[2]],
1799        epipubic_tip_l,
1800        0.008,
1801        0.012,
1802        [-0.006, 0.005, 0.0],
1803        bone_ivory,
1804        ZoologicalAnatomicalLayer::Osteology,
1805        JOINT_PELVIS_ROOT,
1806        JOINT_SPINE,
1807    );
1808    acc.push_long_bone_with_epiphyses(
1809        [0.02, pubis_pos[1], pubis_pos[2]],
1810        epipubic_tip_r,
1811        0.008,
1812        0.012,
1813        [0.006, 0.005, 0.0],
1814        bone_ivory,
1815        ZoologicalAnatomicalLayer::Osteology,
1816        JOINT_PELVIS_ROOT,
1817        JOINT_SPINE,
1818    );
1819
1820    let pelvis_mat = make_pbr_material(
1821        "mat_ost_pelvis_epipubic",
1822        [0.87, 0.85, 0.79, 1.0],
1823        0.44,
1824        0.02,
1825    );
1826    materials.push(pelvis_mat);
1827    submesh_ranges.push(SubmeshRange {
1828        first_index: pelvis_start,
1829        index_count: acc.indices.len() as u32 - pelvis_start,
1830        material_id: pelvis_mat.id,
1831        semantic_id: q_hash("urn:qualia:bio:submesh:pelvic_epipubic_bones"),
1832    });
1833
1834    // 7. Hindlimb & Syndactyl Pes (Bicondylar Femur, Tibia/Fibula, Calcaneum & Syndactyl Digits)
1835    let hind_start = acc.indices.len() as u32;
1836    let hip_l = [-half_width * 0.65, pelvis_pos[1] - 0.02, pelvis_pos[2]];
1837    let hip_r = [half_width * 0.65, pelvis_pos[1] - 0.02, pelvis_pos[2]];
1838    let knee_l = [
1839        -half_width * 0.72,
1840        pelvis_pos[1] - femur_len,
1841        pelvis_pos[2] + femur_len * 0.45,
1842    ];
1843    let knee_r = [
1844        half_width * 0.72,
1845        pelvis_pos[1] - femur_len,
1846        pelvis_pos[2] + femur_len * 0.45,
1847    ];
1848    let ankle_l = [
1849        -half_width * 0.58,
1850        knee_l[1] - tibia_len,
1851        pelvis_pos[2] - 0.04,
1852    ];
1853    let ankle_r = [
1854        half_width * 0.58,
1855        knee_r[1] - tibia_len,
1856        pelvis_pos[2] - 0.04,
1857    ];
1858    let pes_tip_l = [ankle_l[0], ankle_l[1], ankle_l[2] + half_width * 1.4];
1859    let pes_tip_r = [ankle_r[0], ankle_r[1], ankle_r[2] + half_width * 1.4];
1860
1861    for (side, hip_p, knee_p, ankle_p, pes_p, j_hip, j_knee, j_ankle) in [
1862        (
1863            -1.0_f32,
1864            hip_l,
1865            knee_l,
1866            ankle_l,
1867            pes_tip_l,
1868            JOINT_LEFT_HIP,
1869            JOINT_LEFT_KNEE,
1870            JOINT_LEFT_ANKLE,
1871        ),
1872        (
1873            1.0_f32,
1874            hip_r,
1875            knee_r,
1876            ankle_r,
1877            pes_tip_r,
1878            JOINT_RIGHT_HIP,
1879            JOINT_RIGHT_KNEE,
1880            JOINT_RIGHT_ANKLE,
1881        ),
1882    ] {
1883        // Femur with greater trochanter & distal condyles
1884        acc.push_long_bone_with_epiphyses(
1885            hip_p,
1886            knee_p,
1887            half_width * 0.14,
1888            half_width * 0.22,
1889            [side * 0.010, 0.012, 0.010],
1890            bone_ivory,
1891            ZoologicalAnatomicalLayer::Osteology,
1892            j_hip,
1893            j_knee,
1894        );
1895        // Tibia & Fibula with cnemial crest
1896        acc.push_long_bone_with_epiphyses(
1897            knee_p,
1898            ankle_p,
1899            half_width * 0.11,
1900            half_width * 0.17,
1901            [0.0, 0.0, -0.012],
1902            bone_ivory,
1903            ZoologicalAnatomicalLayer::Osteology,
1904            j_knee,
1905            j_ankle,
1906        );
1907        // Calcaneum heel lever
1908        acc.push_long_bone_with_epiphyses(
1909            ankle_p,
1910            [
1911                ankle_p[0],
1912                ankle_p[1] + 0.018,
1913                ankle_p[2] - half_width * 0.36,
1914            ],
1915            0.012,
1916            0.018,
1917            [0.0, 0.004, 0.0],
1918            bone_dense,
1919            ZoologicalAnatomicalLayer::Osteology,
1920            j_ankle,
1921            j_knee,
1922        );
1923        // Elongated 4th Metatarsal & Hopping Digit IV
1924        acc.push_long_bone_with_epiphyses(
1925            ankle_p,
1926            pes_p,
1927            half_width * 0.09,
1928            half_width * 0.13,
1929            [0.0, 0.006, 0.0],
1930            bone_ivory,
1931            ZoologicalAnatomicalLayer::Osteology,
1932            j_ankle,
1933            j_knee,
1934        );
1935        // Syndactyl grooming digits II & III (paired medial digits)
1936        acc.push_cylinder(
1937            [ankle_p[0] - side * 0.015, ankle_p[1], ankle_p[2] + 0.02],
1938            [pes_p[0] - side * 0.015, pes_p[1], pes_p[2] * 0.75],
1939            0.005,
1940            0.003,
1941            6,
1942            2,
1943            bone_ivory,
1944            ZoologicalAnatomicalLayer::Osteology,
1945            j_ankle,
1946            j_knee,
1947            0.95,
1948        );
1949    }
1950
1951    let hind_mat = make_pbr_material("mat_ost_hindlimb_pes", bone_ivory, 0.42, 0.02);
1952    materials.push(hind_mat);
1953    submesh_ranges.push(SubmeshRange {
1954        first_index: hind_start,
1955        index_count: acc.indices.len() as u32 - hind_start,
1956        material_id: hind_mat.id,
1957        semantic_id: q_hash("urn:qualia:bio:submesh:hindlimb_syndactyl_pes"),
1958    });
1959
1960    // 8. Caudal Vertebral Chain (Articulated Caudal Centra, Transverse Processes & Haemal Chevrons)
1961    let tail_start = acc.indices.len() as u32;
1962    let tail_base = [0.0, pelvis_pos[1] - 0.02, -spine_len * 0.1];
1963    let tail_mid = [0.0, pelvis_pos[1] - femur_len * 0.45, -tail_len * 0.55];
1964    let tail_tip = [0.0, ankle_l[1] + 0.02, -tail_len];
1965
1966    let caudal_loft = [
1967        AnatomicalLoftRing {
1968            center: tail_base,
1969            radii: [half_width * 0.24, half_width * 0.22],
1970            dorsal_color: bone_ivory,
1971            flank_color: bone_dense,
1972            ventral_color: bone_dense,
1973            primary_joint: JOINT_TAIL_BASE,
1974            secondary_joint: JOINT_PELVIS_ROOT,
1975            primary_weight: 0.80,
1976        },
1977        AnatomicalLoftRing {
1978            center: tail_mid,
1979            radii: [half_width * 0.16, half_width * 0.15],
1980            dorsal_color: bone_ivory,
1981            flank_color: bone_dense,
1982            ventral_color: bone_dense,
1983            primary_joint: JOINT_TAIL_MID,
1984            secondary_joint: JOINT_TAIL_BASE,
1985            primary_weight: 0.80,
1986        },
1987        AnatomicalLoftRing {
1988            center: tail_tip,
1989            radii: [half_width * 0.05, half_width * 0.05],
1990            dorsal_color: bone_dense,
1991            flank_color: bone_dense,
1992            ventral_color: bone_dense,
1993            primary_joint: JOINT_TAIL_TIP,
1994            secondary_joint: JOINT_TAIL_MID,
1995            primary_weight: 0.90,
1996        },
1997    ];
1998    acc.push_countershaded_loft(&caudal_loft, 8, ZoologicalAnatomicalLayer::Osteology, true);
1999
2000    for c in 1..=5 {
2001        let t = c as f32 / 6.0;
2002        let pos = [
2003            tail_base[0] + (tail_mid[0] - tail_base[0]) * t,
2004            tail_base[1] + (tail_mid[1] - tail_base[1]) * t - 0.014,
2005            tail_base[2] + (tail_mid[2] - tail_base[2]) * t,
2006        ];
2007        acc.push_cylinder(
2008            [pos[0], pos[1], pos[2]],
2009            [pos[0], pos[1] - 0.022 * (1.0 - t * 0.4), pos[2] - 0.008],
2010            0.006,
2011            0.003,
2012            6,
2013            2,
2014            bone_dense,
2015            ZoologicalAnatomicalLayer::Osteology,
2016            JOINT_TAIL_BASE,
2017            JOINT_TAIL_MID,
2018            1.0 - t * 0.5,
2019        );
2020    }
2021
2022    if archetype == FaunaBiomechanicalArchetype::MarinePinnipedCetacean {
2023        acc.push_ellipsoid(
2024            tail_tip,
2025            [half_width * 0.72, 0.035, half_width * 0.24],
2026            12,
2027            6,
2028            bone_dense,
2029            ZoologicalAnatomicalLayer::Osteology,
2030            JOINT_TAIL_TIP,
2031            JOINT_TAIL_MID,
2032            0.8,
2033        );
2034    }
2035
2036    let tail_mat = make_pbr_material("mat_ost_caudal", bone_dense, 0.48, 0.02);
2037    materials.push(tail_mat);
2038    submesh_ranges.push(SubmeshRange {
2039        first_index: tail_start,
2040        index_count: acc.indices.len() as u32 - tail_start,
2041        material_id: tail_mat.id,
2042        semantic_id: q_hash("urn:qualia:bio:submesh:caudal_vertebrae"),
2043    });
2044
2045    let ost_end_v = acc.positions.len();
2046
2047    // ── LAYER 1: MYOLOGY, TENDONS & VISCERA (8 Functional Submeshes) ─────────
2048    let myo_start_v = acc.positions.len();
2049
2050    // 9. Gastrocnemius & Plantaris (Lateral & Medial Fusiform Calf Bellies)
2051    let gast_start = acc.indices.len() as u32;
2052    let gastro_center_l = [
2053        knee_l[0] * 1.02,
2054        (knee_l[1] + ankle_l[1]) * 0.58,
2055        knee_l[2] - half_width * 0.15,
2056    ];
2057    let gastro_center_r = [
2058        knee_r[0] * 1.02,
2059        (knee_r[1] + ankle_r[1]) * 0.58,
2060        knee_r[2] - half_width * 0.15,
2061    ];
2062    let myotendinous_l = [
2063        ankle_l[0],
2064        (knee_l[1] + ankle_l[1]) * 0.36,
2065        ankle_l[2] - half_width * 0.22,
2066    ];
2067    let myotendinous_r = [
2068        ankle_r[0],
2069        (knee_r[1] + ankle_r[1]) * 0.36,
2070        ankle_r[2] - half_width * 0.22,
2071    ];
2072
2073    acc.push_fusiform_muscle(
2074        knee_l,
2075        myotendinous_l,
2076        half_width * 0.24,
2077        half_width * 0.22,
2078        [-0.012, 0.0, -half_width * 0.16],
2079        [0.58, 0.17, 0.17, 1.0],
2080        tendon_ivory,
2081        ZoologicalAnatomicalLayer::MyologyAndTendons,
2082        JOINT_LEFT_KNEE,
2083        JOINT_LEFT_ANKLE,
2084    );
2085    acc.push_fusiform_muscle(
2086        knee_r,
2087        myotendinous_r,
2088        half_width * 0.24,
2089        half_width * 0.22,
2090        [0.012, 0.0, -half_width * 0.16],
2091        [0.58, 0.17, 0.17, 1.0],
2092        tendon_ivory,
2093        ZoologicalAnatomicalLayer::MyologyAndTendons,
2094        JOINT_RIGHT_KNEE,
2095        JOINT_RIGHT_ANKLE,
2096    );
2097
2098    let gast_mat = make_pbr_material("mat_myo_gastrocnemius", [0.55, 0.18, 0.18, 1.0], 0.65, 0.0);
2099    materials.push(gast_mat);
2100    submesh_ranges.push(SubmeshRange {
2101        first_index: gast_start,
2102        index_count: acc.indices.len() as u32 - gast_start,
2103        material_id: gast_mat.id,
2104        semantic_id: q_hash("urn:qualia:bio:submesh:gastrocnemius_plantaris"),
2105    });
2106
2107    // 10. ELASTIC ACHILLES TENDON SPRING (Stores & Returns up to 65% Metabolic Work)
2108    let ach_start = acc.indices.len() as u32;
2109    let achilles_start_l = [
2110        gastro_center_l[0],
2111        gastro_center_l[1] - tibia_len * 0.22,
2112        gastro_center_l[2],
2113    ];
2114    let achilles_start_r = [
2115        gastro_center_r[0],
2116        gastro_center_r[1] - tibia_len * 0.22,
2117        gastro_center_r[2],
2118    ];
2119    let calcaneus_l = [
2120        ankle_l[0],
2121        ankle_l[1] + 0.012,
2122        ankle_l[2] - half_width * 0.30,
2123    ];
2124    let calcaneus_r = [
2125        ankle_r[0],
2126        ankle_r[1] + 0.012,
2127        ankle_r[2] - half_width * 0.30,
2128    ];
2129    let plantar_l = [
2130        ankle_l[0],
2131        ankle_l[1] - 0.008,
2132        ankle_l[2] + half_width * 0.90,
2133    ];
2134    let plantar_r = [
2135        ankle_r[0],
2136        ankle_r[1] - 0.008,
2137        ankle_r[2] + half_width * 0.90,
2138    ];
2139
2140    for (a_start, calc_p, plant_p, j_ank, j_kn) in [
2141        (
2142            achilles_start_l,
2143            calcaneus_l,
2144            plantar_l,
2145            JOINT_LEFT_ANKLE,
2146            JOINT_LEFT_KNEE,
2147        ),
2148        (
2149            achilles_start_r,
2150            calcaneus_r,
2151            plantar_r,
2152            JOINT_RIGHT_ANKLE,
2153            JOINT_RIGHT_KNEE,
2154        ),
2155    ] {
2156        let tendon_rings = [
2157            AnatomicalLoftRing {
2158                center: a_start,
2159                radii: [half_width * 0.068, half_width * 0.055],
2160                dorsal_color: tendon_ivory,
2161                flank_color: tendon_ivory,
2162                ventral_color: tendon_ivory,
2163                primary_joint: j_kn,
2164                secondary_joint: j_ank,
2165                primary_weight: 0.65,
2166            },
2167            AnatomicalLoftRing {
2168                center: calc_p,
2169                radii: [half_width * 0.056, half_width * 0.048],
2170                dorsal_color: tendon_ivory,
2171                flank_color: tendon_ivory,
2172                ventral_color: tendon_ivory,
2173                primary_joint: j_ank,
2174                secondary_joint: j_kn,
2175                primary_weight: 0.90,
2176            },
2177            AnatomicalLoftRing {
2178                center: plant_p,
2179                radii: [half_width * 0.048, half_width * 0.028],
2180                dorsal_color: tendon_ivory,
2181                flank_color: tendon_ivory,
2182                ventral_color: tendon_ivory,
2183                primary_joint: j_ank,
2184                secondary_joint: j_kn,
2185                primary_weight: 0.95,
2186            },
2187        ];
2188        acc.push_countershaded_loft(
2189            &tendon_rings,
2190            8,
2191            ZoologicalAnatomicalLayer::MyologyAndTendons,
2192            true,
2193        );
2194    }
2195
2196    let ach_mat = make_pbr_material("mat_myo_achilles_tendon", tendon_ivory, 0.22, 0.08);
2197    materials.push(ach_mat);
2198    submesh_ranges.push(SubmeshRange {
2199        first_index: ach_start,
2200        index_count: acc.indices.len() as u32 - ach_start,
2201        material_id: ach_mat.id,
2202        semantic_id: q_hash("urn:qualia:bio:submesh:achilles_tendon_spring"),
2203    });
2204
2205    // 11. Gluteus, Biceps Femoris & Quadriceps Vastus Lateralis (Fusiform Thigh Extensors)
2206    let glut_start = acc.indices.len() as u32;
2207    for (side, il_p, isch_p, hip_p, kn_p, j_hip, j_kn) in [
2208        (
2209            -1.0_f32,
2210            ilium_l,
2211            ischium_l,
2212            hip_l,
2213            knee_l,
2214            JOINT_LEFT_HIP,
2215            JOINT_LEFT_KNEE,
2216        ),
2217        (
2218            1.0_f32,
2219            ilium_r,
2220            ischium_r,
2221            hip_r,
2222            knee_r,
2223            JOINT_RIGHT_HIP,
2224            JOINT_RIGHT_KNEE,
2225        ),
2226    ] {
2227        // Biceps femoris & gluteus superficialis
2228        acc.push_fusiform_muscle(
2229            isch_p,
2230            kn_p,
2231            half_width * 0.28,
2232            half_width * 0.32,
2233            [side * half_width * 0.14, 0.02, -0.02],
2234            [0.54, 0.16, 0.16, 1.0],
2235            tendon_ivory,
2236            ZoologicalAnatomicalLayer::MyologyAndTendons,
2237            j_hip,
2238            j_kn,
2239        );
2240        // Quadriceps vastus lateralis & rectus femoris
2241        acc.push_fusiform_muscle(
2242            il_p,
2243            kn_p,
2244            half_width * 0.24,
2245            half_width * 0.26,
2246            [side * half_width * 0.10, 0.03, 0.03],
2247            [0.58, 0.19, 0.18, 1.0],
2248            tendon_ivory,
2249            ZoologicalAnatomicalLayer::MyologyAndTendons,
2250            j_hip,
2251            j_kn,
2252        );
2253        let _ = hip_p;
2254    }
2255
2256    let glut_mat = make_pbr_material("mat_myo_gluteus", [0.52, 0.16, 0.16, 1.0], 0.62, 0.0);
2257    materials.push(glut_mat);
2258    submesh_ranges.push(SubmeshRange {
2259        first_index: glut_start,
2260        index_count: acc.indices.len() as u32 - glut_start,
2261        material_id: glut_mat.id,
2262        semantic_id: q_hash("urn:qualia:bio:submesh:gluteus_biceps_femoris"),
2263    });
2264
2265    // 12. Iliopsoas, Caudofemoralis & Epaxial/Hypaxial Spinal/Caudal Bundles
2266    let ilio_start = acc.indices.len() as u32;
2267    for (side, hip_p, j_hip) in [
2268        (-1.0_f32, hip_l, JOINT_LEFT_HIP),
2269        (1.0_f32, hip_r, JOINT_RIGHT_HIP),
2270    ] {
2271        // Caudofemoralis (tail base to femur retractor)
2272        acc.push_fusiform_muscle(
2273            tail_mid,
2274            hip_p,
2275            half_width * 0.20,
2276            half_width * 0.22,
2277            [side * half_width * 0.12, -0.01, 0.0],
2278            [0.50, 0.15, 0.15, 1.0],
2279            tendon_ivory,
2280            ZoologicalAnatomicalLayer::MyologyAndTendons,
2281            JOINT_TAIL_BASE,
2282            j_hip,
2283        );
2284        // Dorsal epaxial (longissimus dorsi) muscle bundle spanning pelvis to chest
2285        acc.push_fusiform_muscle(
2286            [
2287                side * half_width * 0.22,
2288                pelvis_pos[1] + 0.03,
2289                pelvis_pos[2],
2290            ],
2291            [side * half_width * 0.20, chest_pos[1] + 0.03, chest_pos[2]],
2292            half_width * 0.18,
2293            half_width * 0.16,
2294            [side * 0.01, 0.02, 0.0],
2295            [0.53, 0.16, 0.16, 1.0],
2296            tendon_ivory,
2297            ZoologicalAnatomicalLayer::MyologyAndTendons,
2298            JOINT_SPINE,
2299            JOINT_CHEST,
2300        );
2301    }
2302
2303    let ilio_mat = make_pbr_material("mat_myo_iliopsoas", [0.50, 0.15, 0.15, 1.0], 0.60, 0.0);
2304    materials.push(ilio_mat);
2305    submesh_ranges.push(SubmeshRange {
2306        first_index: ilio_start,
2307        index_count: acc.indices.len() as u32 - ilio_start,
2308        material_id: ilio_mat.id,
2309        semantic_id: q_hash("urn:qualia:bio:submesh:iliopsoas_caudofemoralis"),
2310    });
2311
2312    // 13. Pectoralis Major, Supracoracoideus & Latissimus Dorsi (Chest & Back Fan Muscles)
2313    let pect_myo_start = acc.indices.len() as u32;
2314    for (side, sh_p) in [(-1.0_f32, shoulder_l), (1.0_f32, shoulder_r)] {
2315        // Pectoralis major fan from sternum/carina to humerus deltopectoral crest
2316        acc.push_fusiform_muscle(
2317            [0.0, sternum_pos[1], sternum_pos[2]],
2318            sh_p,
2319            half_width * 0.30,
2320            half_width * 0.24,
2321            [side * half_width * 0.12, -0.02, 0.03],
2322            [0.58, 0.20, 0.20, 1.0],
2323            tendon_ivory,
2324            ZoologicalAnatomicalLayer::MyologyAndTendons,
2325            JOINT_CHEST,
2326            JOINT_LEFT_SHOULDER,
2327        );
2328        // Latissimus dorsi from mid-thoracic fascia to proximal humerus
2329        acc.push_fusiform_muscle(
2330            [
2331                0.0,
2332                (pelvis_pos[1] + chest_pos[1]) * 0.52,
2333                (pelvis_pos[2] + chest_pos[2]) * 0.45,
2334            ],
2335            sh_p,
2336            half_width * 0.20,
2337            half_width * 0.24,
2338            [side * half_width * 0.26, 0.0, 0.0],
2339            [0.54, 0.18, 0.18, 1.0],
2340            tendon_ivory,
2341            ZoologicalAnatomicalLayer::MyologyAndTendons,
2342            JOINT_CHEST,
2343            JOINT_SPINE,
2344        );
2345    }
2346
2347    let pect_myo_mat = make_pbr_material("mat_myo_pectoralis", [0.58, 0.20, 0.20, 1.0], 0.64, 0.0);
2348    materials.push(pect_myo_mat);
2349    submesh_ranges.push(SubmeshRange {
2350        first_index: pect_myo_start,
2351        index_count: acc.indices.len() as u32 - pect_myo_start,
2352        material_id: pect_myo_mat.id,
2353        semantic_id: q_hash("urn:qualia:bio:submesh:pectoralis_supracoracoideus"),
2354    });
2355
2356    // 14. Deltoid, Triceps Brachii & Biceps Brachii (Fossorial/Brachial Musculature)
2357    let delt_start = acc.indices.len() as u32;
2358    for (side, sh_p, el_p, wr_p) in [
2359        (-1.0_f32, shoulder_l, elbow_l, wrist_l),
2360        (1.0_f32, shoulder_r, elbow_r, wrist_r),
2361    ] {
2362        // Deltoid & Triceps brachii
2363        acc.push_fusiform_muscle(
2364            sh_p,
2365            el_p,
2366            half_width * 0.19,
2367            half_width * 0.21,
2368            [side * 0.015, 0.0, -0.018],
2369            [0.54, 0.17, 0.17, 1.0],
2370            tendon_ivory,
2371            ZoologicalAnatomicalLayer::MyologyAndTendons,
2372            JOINT_LEFT_SHOULDER,
2373            JOINT_LEFT_ELBOW,
2374        );
2375        // Antebrachial flexors/extensors
2376        acc.push_fusiform_muscle(
2377            el_p,
2378            wr_p,
2379            half_width * 0.13,
2380            half_width * 0.14,
2381            [side * 0.008, 0.0, 0.010],
2382            [0.52, 0.16, 0.16, 1.0],
2383            tendon_ivory,
2384            ZoologicalAnatomicalLayer::MyologyAndTendons,
2385            JOINT_LEFT_ELBOW,
2386            JOINT_LEFT_WRIST_WING,
2387        );
2388    }
2389
2390    let delt_mat = make_pbr_material("mat_myo_deltoid", [0.54, 0.17, 0.17, 1.0], 0.63, 0.0);
2391    materials.push(delt_mat);
2392    submesh_ranges.push(SubmeshRange {
2393        first_index: delt_start,
2394        index_count: acc.indices.len() as u32 - delt_start,
2395        material_id: delt_mat.id,
2396        semantic_id: q_hash("urn:qualia:bio:submesh:deltoid_triceps"),
2397    });
2398
2399    // 15. Masseter, Temporalis & Cervical Splenius/Sternocleidomastoid
2400    let mass_start = acc.indices.len() as u32;
2401    for (side, jaw_j) in [(-1.0_f32, jaw_joint_l), (1.0_f32, jaw_joint_r)] {
2402        acc.push_fusiform_muscle(
2403            [
2404                side * half_width * 0.42,
2405                cranium_head_pos[1] + 0.01,
2406                cranium_head_pos[2] + head_len * 0.12,
2407            ],
2408            [
2409                jaw_j[0] * 0.75,
2410                chin_pos[1] + 0.01,
2411                (jaw_j[2] + chin_pos[2]) * 0.5,
2412            ],
2413            half_width * 0.15,
2414            half_width * 0.20,
2415            [side * 0.012, 0.0, 0.0],
2416            [0.48, 0.16, 0.16, 1.0],
2417            tendon_ivory,
2418            ZoologicalAnatomicalLayer::MyologyAndTendons,
2419            JOINT_HEAD,
2420            JOINT_JAW,
2421        );
2422        // Splenius / sternocleidomastoid neck strap
2423        acc.push_fusiform_muscle(
2424            [side * half_width * 0.24, chest_pos[1], chest_pos[2]],
2425            [
2426                side * half_width * 0.30,
2427                cranium_head_pos[1],
2428                cranium_head_pos[2] - 0.02,
2429            ],
2430            half_width * 0.15,
2431            half_width * 0.16,
2432            [side * 0.01, 0.01, 0.0],
2433            [0.52, 0.17, 0.17, 1.0],
2434            tendon_ivory,
2435            ZoologicalAnatomicalLayer::MyologyAndTendons,
2436            JOINT_NECK,
2437            JOINT_HEAD,
2438        );
2439    }
2440
2441    let mass_mat = make_pbr_material("mat_myo_masseter", [0.48, 0.16, 0.16, 1.0], 0.62, 0.0);
2442    materials.push(mass_mat);
2443    submesh_ranges.push(SubmeshRange {
2444        first_index: mass_start,
2445        index_count: acc.indices.len() as u32 - mass_start,
2446        material_id: mass_mat.id,
2447        semantic_id: q_hash("urn:qualia:bio:submesh:masseter_temporalis"),
2448    });
2449
2450    // 16. Intercostals, Diaphragm & Internal VISCERA (Bilobed Lungs, Bronchial Tree,
2451    //     4-Chambered Heart with Aortic Arch, Lobulated Liver, Stomach & Coiled Intestines)
2452    let inter_start = acc.indices.len() as u32;
2453    let thorax_y = (chest_pos[1] + sternum_pos[1]) * 0.52;
2454    let thorax_z = chest_pos[2] * 0.78;
2455
2456    // Cartilaginous Trachea & Bifurcating Primary Bronchi
2457    acc.push_cylinder(
2458        [0.0, cranium_head_pos[1] - 0.05, cranium_head_pos[2] - 0.02],
2459        [0.0, thorax_y + 0.03, thorax_z + spine_len * 0.14],
2460        0.012,
2461        0.012,
2462        8,
2463        4,
2464        cartilage_blue,
2465        ZoologicalAnatomicalLayer::MyologyAndTendons,
2466        JOINT_NECK,
2467        JOINT_CHEST,
2468        0.65,
2469    );
2470
2471    // Bilobed Left & Right Lungs with Primary Bronchial Branches
2472    let lung_coral = [0.82, 0.44, 0.46, 1.0];
2473    for side in [-1.0_f32, 1.0_f32] {
2474        let lung_c = [side * half_width * 0.34, thorax_y + 0.01, thorax_z];
2475        acc.push_cylinder(
2476            [0.0, thorax_y + 0.03, thorax_z + spine_len * 0.14],
2477            lung_c,
2478            0.009,
2479            0.007,
2480            6,
2481            2,
2482            cartilage_blue,
2483            ZoologicalAnatomicalLayer::MyologyAndTendons,
2484            JOINT_CHEST,
2485            JOINT_SPINE,
2486            0.85,
2487        );
2488        // Cranial & caudal pulmonary lobes
2489        acc.push_ellipsoid(
2490            [lung_c[0], lung_c[1] + 0.01, lung_c[2] + spine_len * 0.08],
2491            [half_width * 0.24, half_width * 0.26, spine_len * 0.16],
2492            10,
2493            6,
2494            lung_coral,
2495            ZoologicalAnatomicalLayer::MyologyAndTendons,
2496            JOINT_CHEST,
2497            JOINT_SPINE,
2498            0.85,
2499        );
2500        acc.push_ellipsoid(
2501            [
2502                lung_c[0] * 1.05,
2503                lung_c[1] - 0.01,
2504                lung_c[2] - spine_len * 0.09,
2505            ],
2506            [half_width * 0.27, half_width * 0.30, spine_len * 0.20],
2507            10,
2508            6,
2509            lung_coral,
2510            ZoologicalAnatomicalLayer::MyologyAndTendons,
2511            JOINT_CHEST,
2512            JOINT_SPINE,
2513            0.80,
2514        );
2515    }
2516
2517    // 4-Chambered Heart & Systemic Aortic Arch
2518    let heart_pos = [
2519        -half_width * 0.06,
2520        sternum_pos[1] + half_width * 0.26,
2521        thorax_z + 0.02,
2522    ];
2523    acc.push_ellipsoid(
2524        heart_pos,
2525        [half_width * 0.18, half_width * 0.22, half_width * 0.19],
2526        10,
2527        6,
2528        [0.68, 0.12, 0.16, 1.0],
2529        ZoologicalAnatomicalLayer::MyologyAndTendons,
2530        JOINT_CHEST,
2531        JOINT_SPINE,
2532        0.90,
2533    );
2534    // Curving Aortic Arch
2535    acc.push_curved_rib_arch(
2536        [heart_pos[0], heart_pos[1] + half_width * 0.16, heart_pos[2]],
2537        [0.0, chest_pos[1] - 0.02, thorax_z - spine_len * 0.20],
2538        0.022,
2539        0.009,
2540        [0.78, 0.16, 0.18, 1.0],
2541        [0.72, 0.14, 0.16, 1.0],
2542        ZoologicalAnatomicalLayer::MyologyAndTendons,
2543        JOINT_CHEST,
2544        JOINT_SPINE,
2545    );
2546
2547    // Lobulated Liver (caudal to diaphragm)
2548    let liver_pos = [half_width * 0.10, thorax_y - 0.02, spine_len * 0.42];
2549    acc.push_ellipsoid(
2550        liver_pos,
2551        [half_width * 0.36, half_width * 0.26, spine_len * 0.16],
2552        10,
2553        6,
2554        [0.44, 0.15, 0.14, 1.0],
2555        ZoologicalAnatomicalLayer::MyologyAndTendons,
2556        JOINT_SPINE,
2557        JOINT_CHEST,
2558        0.75,
2559    );
2560
2561    // Sacciform Stomach
2562    let stomach_pos = [-half_width * 0.18, thorax_y - 0.04, spine_len * 0.30];
2563    acc.push_ellipsoid(
2564        stomach_pos,
2565        [half_width * 0.26, half_width * 0.22, spine_len * 0.18],
2566        10,
2567        6,
2568        [0.74, 0.50, 0.42, 1.0],
2569        ZoologicalAnatomicalLayer::MyologyAndTendons,
2570        JOINT_SPINE,
2571        JOINT_PELVIS_ROOT,
2572        0.75,
2573    );
2574
2575    // Coiled Small & Large Intestinal Tract
2576    let gut_pink = [0.78, 0.56, 0.48, 1.0];
2577    let mut gut_rings = [AnatomicalLoftRing {
2578        center: stomach_pos,
2579        radii: [0.018, 0.018],
2580        dorsal_color: gut_pink,
2581        flank_color: gut_pink,
2582        ventral_color: gut_pink,
2583        primary_joint: JOINT_SPINE,
2584        secondary_joint: JOINT_PELVIS_ROOT,
2585        primary_weight: 0.70,
2586    }; 8];
2587    for (gi, ring) in gut_rings.iter_mut().enumerate() {
2588        let gt = gi as f32 / 7.0;
2589        let coil_angle = gt * core::f32::consts::TAU * 2.0;
2590        *ring = AnatomicalLoftRing {
2591            center: [
2592                coil_angle.cos() * half_width * 0.24,
2593                pelvis_pos[1] - half_width * 0.18 + coil_angle.sin() * half_width * 0.12,
2594                spine_len * (0.28 - gt * 0.24),
2595            ],
2596            radii: [half_width * 0.13, half_width * 0.13],
2597            dorsal_color: gut_pink,
2598            flank_color: gut_pink,
2599            ventral_color: [0.70, 0.48, 0.42, 1.0],
2600            primary_joint: JOINT_SPINE,
2601            secondary_joint: JOINT_PELVIS_ROOT,
2602            primary_weight: 0.65,
2603        };
2604    }
2605    acc.push_countershaded_loft(
2606        &gut_rings,
2607        8,
2608        ZoologicalAnatomicalLayer::MyologyAndTendons,
2609        true,
2610    );
2611
2612    let inter_mat = make_pbr_material("mat_myo_intercostals", [0.46, 0.15, 0.15, 1.0], 0.68, 0.0);
2613    materials.push(inter_mat);
2614    submesh_ranges.push(SubmeshRange {
2615        first_index: inter_start,
2616        index_count: acc.indices.len() as u32 - inter_start,
2617        material_id: inter_mat.id,
2618        semantic_id: q_hash("urn:qualia:bio:submesh:intercostals_diaphragm"),
2619    });
2620
2621    let myo_end_v = acc.positions.len();
2622
2623    // ── LAYER 2: EXTERNAL INTEGUMENT (Multi-Station Countershaded Pelage / Plumage / Skin) ──
2624    let int_start_v = acc.positions.len();
2625    let int_start_idx = acc.indices.len() as u32;
2626
2627    let integument_color = match archetype {
2628        FaunaBiomechanicalArchetype::MacropodSaltatorial => [0.48, 0.40, 0.32, 1.0],
2629        FaunaBiomechanicalArchetype::VombatidFossorial => [0.34, 0.28, 0.22, 1.0],
2630        FaunaBiomechanicalArchetype::PhascolarctidArboreal => [0.55, 0.52, 0.48, 1.0],
2631        FaunaBiomechanicalArchetype::PetauridGlider => [0.60, 0.58, 0.56, 1.0],
2632        FaunaBiomechanicalArchetype::DasyuridPredator => [0.42, 0.30, 0.22, 1.0],
2633        FaunaBiomechanicalArchetype::PteropodidChiroptera => [0.22, 0.18, 0.16, 1.0],
2634        FaunaBiomechanicalArchetype::MarinePinnipedCetacean => [0.32, 0.36, 0.42, 1.0],
2635        FaunaBiomechanicalArchetype::RatiteBipedal => [0.18, 0.17, 0.18, 1.0],
2636        FaunaBiomechanicalArchetype::RaptorSoaring => [0.28, 0.22, 0.16, 1.0],
2637        FaunaBiomechanicalArchetype::PasserinePsittacine => [0.38, 0.52, 0.28, 1.0],
2638        FaunaBiomechanicalArchetype::SquamateSprawling => [0.44, 0.42, 0.34, 1.0],
2639        FaunaBiomechanicalArchetype::SerpentineUndulatory => [0.20, 0.18, 0.20, 1.0],
2640        FaunaBiomechanicalArchetype::MonotremeTeleostAmphibian => [0.36, 0.26, 0.20, 1.0],
2641    };
2642    let flank_tint: [f32; 4] = [
2643        (integument_color[0] * 1.22_f32).min(0.92),
2644        (integument_color[1] * 1.20_f32).min(0.90),
2645        (integument_color[2] * 1.18_f32).min(0.86),
2646        1.0,
2647    ];
2648    let ventral_cream: [f32; 4] = [
2649        (integument_color[0] * 0.55_f32 + 0.42).min(0.95),
2650        (integument_color[1] * 0.55_f32 + 0.40).min(0.93),
2651        (integument_color[2] * 0.52_f32 + 0.36).min(0.89),
2652        1.0,
2653    ];
2654    let charcoal_dark = [0.14, 0.12, 0.12, 1.0];
2655
2656    // Multi-Station Continuous Head -> Neck -> Thorax -> Abdomen -> Pelvis -> Tail Integument Loft
2657    let axial_integument_loft = [
2658        AnatomicalLoftRing {
2659            center: tail_tip,
2660            radii: [half_width * 0.10, half_width * 0.10],
2661            dorsal_color: charcoal_dark,
2662            flank_color: integument_color,
2663            ventral_color: integument_color,
2664            primary_joint: JOINT_TAIL_TIP,
2665            secondary_joint: JOINT_TAIL_MID,
2666            primary_weight: 0.90,
2667        },
2668        AnatomicalLoftRing {
2669            center: tail_mid,
2670            radii: [half_width * 0.24, half_width * 0.22],
2671            dorsal_color: integument_color,
2672            flank_color: flank_tint,
2673            ventral_color: ventral_cream,
2674            primary_joint: JOINT_TAIL_MID,
2675            secondary_joint: JOINT_TAIL_BASE,
2676            primary_weight: 0.80,
2677        },
2678        AnatomicalLoftRing {
2679            center: tail_base,
2680            radii: [half_width * 0.38, half_width * 0.36],
2681            dorsal_color: integument_color,
2682            flank_color: flank_tint,
2683            ventral_color: ventral_cream,
2684            primary_joint: JOINT_TAIL_BASE,
2685            secondary_joint: JOINT_PELVIS_ROOT,
2686            primary_weight: 0.75,
2687        },
2688        AnatomicalLoftRing {
2689            center: [0.0, pelvis_pos[1] + 0.01, pelvis_pos[2] + spine_len * 0.08],
2690            radii: [half_width * 0.96, half_width * 0.90],
2691            dorsal_color: integument_color,
2692            flank_color: flank_tint,
2693            ventral_color: ventral_cream,
2694            primary_joint: JOINT_PELVIS_ROOT,
2695            secondary_joint: JOINT_SPINE,
2696            primary_weight: 0.75,
2697        },
2698        AnatomicalLoftRing {
2699            center: [0.0, hip_height + 0.03, spine_len * 0.42],
2700            radii: [half_width * 0.94, half_width * 0.88],
2701            dorsal_color: integument_color,
2702            flank_color: flank_tint,
2703            ventral_color: ventral_cream,
2704            primary_joint: JOINT_SPINE,
2705            secondary_joint: JOINT_CHEST,
2706            primary_weight: 0.65,
2707        },
2708        AnatomicalLoftRing {
2709            center: [0.0, chest_pos[1], chest_pos[2]],
2710            radii: [half_width * 0.82, half_width * 0.78],
2711            dorsal_color: integument_color,
2712            flank_color: flank_tint,
2713            ventral_color: ventral_cream,
2714            primary_joint: JOINT_CHEST,
2715            secondary_joint: JOINT_NECK,
2716            primary_weight: 0.75,
2717        },
2718        AnatomicalLoftRing {
2719            center: [
2720                0.0,
2721                (chest_pos[1] + cranium_head_pos[1]) * 0.52,
2722                (chest_pos[2] + cranium_head_pos[2]) * 0.52,
2723            ],
2724            radii: [half_width * 0.46, half_width * 0.44],
2725            dorsal_color: integument_color,
2726            flank_color: flank_tint,
2727            ventral_color: ventral_cream,
2728            primary_joint: JOINT_NECK,
2729            secondary_joint: JOINT_HEAD,
2730            primary_weight: 0.75,
2731        },
2732        AnatomicalLoftRing {
2733            center: cranium_head_pos,
2734            radii: [half_width * 0.62, half_width * 0.56],
2735            dorsal_color: integument_color,
2736            flank_color: flank_tint,
2737            ventral_color: ventral_cream,
2738            primary_joint: JOINT_HEAD,
2739            secondary_joint: JOINT_NECK,
2740            primary_weight: 0.88,
2741        },
2742        AnatomicalLoftRing {
2743            center: [
2744                0.0,
2745                cranium_head_pos[1] - 0.02,
2746                cranium_head_pos[2] + head_len * 0.55,
2747            ],
2748            radii: [half_width * 0.38, half_width * 0.32],
2749            dorsal_color: integument_color,
2750            flank_color: flank_tint,
2751            ventral_color: ventral_cream,
2752            primary_joint: JOINT_HEAD,
2753            secondary_joint: JOINT_JAW,
2754            primary_weight: 0.90,
2755        },
2756        AnatomicalLoftRing {
2757            center: [rostrum_tip[0], rostrum_tip[1], rostrum_tip[2] + 0.015],
2758            radii: [rostrum_rx * 1.15, rostrum_ry * 1.15],
2759            dorsal_color: charcoal_dark,
2760            flank_color: charcoal_dark,
2761            ventral_color: charcoal_dark,
2762            primary_joint: JOINT_HEAD,
2763            secondary_joint: JOINT_JAW,
2764            primary_weight: 0.95,
2765        },
2766    ];
2767    acc.push_countershaded_loft(
2768        &axial_integument_loft,
2769        16,
2770        ZoologicalAnatomicalLayer::ExternalIntegument,
2771        true,
2772    );
2773
2774    // Multi-Station Countershaded Hindlimbs & Forelimbs Integument
2775    for (hip_p, knee_p, ankle_p, pes_p, j_hip, j_knee, j_ankle) in [
2776        (
2777            hip_l,
2778            knee_l,
2779            ankle_l,
2780            pes_tip_l,
2781            JOINT_LEFT_HIP,
2782            JOINT_LEFT_KNEE,
2783            JOINT_LEFT_ANKLE,
2784        ),
2785        (
2786            hip_r,
2787            knee_r,
2788            ankle_r,
2789            pes_tip_r,
2790            JOINT_RIGHT_HIP,
2791            JOINT_RIGHT_KNEE,
2792            JOINT_RIGHT_ANKLE,
2793        ),
2794    ] {
2795        let hind_loft = [
2796            AnatomicalLoftRing {
2797                center: hip_p,
2798                radii: [half_width * 0.42, half_width * 0.44],
2799                dorsal_color: integument_color,
2800                flank_color: flank_tint,
2801                ventral_color: ventral_cream,
2802                primary_joint: j_hip,
2803                secondary_joint: JOINT_PELVIS_ROOT,
2804                primary_weight: 0.80,
2805            },
2806            AnatomicalLoftRing {
2807                center: knee_p,
2808                radii: [half_width * 0.28, half_width * 0.30],
2809                dorsal_color: integument_color,
2810                flank_color: flank_tint,
2811                ventral_color: ventral_cream,
2812                primary_joint: j_knee,
2813                secondary_joint: j_hip,
2814                primary_weight: 0.80,
2815            },
2816            AnatomicalLoftRing {
2817                center: ankle_p,
2818                radii: [half_width * 0.16, half_width * 0.18],
2819                dorsal_color: integument_color,
2820                flank_color: flank_tint,
2821                ventral_color: charcoal_dark,
2822                primary_joint: j_ankle,
2823                secondary_joint: j_knee,
2824                primary_weight: 0.85,
2825            },
2826            AnatomicalLoftRing {
2827                center: pes_p,
2828                radii: [half_width * 0.11, half_width * 0.08],
2829                dorsal_color: charcoal_dark,
2830                flank_color: charcoal_dark,
2831                ventral_color: charcoal_dark,
2832                primary_joint: j_ankle,
2833                secondary_joint: j_knee,
2834                primary_weight: 0.95,
2835            },
2836        ];
2837        acc.push_countershaded_loft(
2838            &hind_loft,
2839            10,
2840            ZoologicalAnatomicalLayer::ExternalIntegument,
2841            true,
2842        );
2843    }
2844
2845    for (sh_p, el_p, wr_p) in [
2846        (shoulder_l, elbow_l, wrist_l),
2847        (shoulder_r, elbow_r, wrist_r),
2848    ] {
2849        let fore_loft = [
2850            AnatomicalLoftRing {
2851                center: sh_p,
2852                radii: [half_width * 0.26, half_width * 0.28],
2853                dorsal_color: integument_color,
2854                flank_color: flank_tint,
2855                ventral_color: ventral_cream,
2856                primary_joint: JOINT_LEFT_SHOULDER,
2857                secondary_joint: JOINT_CHEST,
2858                primary_weight: 0.80,
2859            },
2860            AnatomicalLoftRing {
2861                center: el_p,
2862                radii: [half_width * 0.19, half_width * 0.20],
2863                dorsal_color: integument_color,
2864                flank_color: flank_tint,
2865                ventral_color: ventral_cream,
2866                primary_joint: JOINT_LEFT_ELBOW,
2867                secondary_joint: JOINT_LEFT_SHOULDER,
2868                primary_weight: 0.80,
2869            },
2870            AnatomicalLoftRing {
2871                center: wr_p,
2872                radii: [half_width * 0.12, half_width * 0.10],
2873                dorsal_color: charcoal_dark,
2874                flank_color: charcoal_dark,
2875                ventral_color: charcoal_dark,
2876                primary_joint: JOINT_LEFT_WRIST_WING,
2877                secondary_joint: JOINT_LEFT_ELBOW,
2878                primary_weight: 0.90,
2879            },
2880        ];
2881        acc.push_countershaded_loft(
2882            &fore_loft,
2883            8,
2884            ZoologicalAnatomicalLayer::ExternalIntegument,
2885            true,
2886        );
2887    }
2888
2889    // Patagial sheet for gliders and bats
2890    if morphology.patagium > 0.0 {
2891        for side in [-1.0f32, 1.0] {
2892            acc.push_ellipsoid(
2893                [
2894                    side * half_width * 0.72,
2895                    hip_height + femur_len * 0.15,
2896                    spine_len * 0.30,
2897                ],
2898                [half_width * morphology.patagium, 0.012, spine_len * 0.42],
2899                12,
2900                8,
2901                integument_color,
2902                ZoologicalAnatomicalLayer::ExternalIntegument,
2903                JOINT_LEFT_SHOULDER,
2904                JOINT_PELVIS_ROOT,
2905                0.55,
2906            );
2907        }
2908    }
2909
2910    // Flight feathers for avian flight archetypes
2911    if matches!(
2912        archetype,
2913        FaunaBiomechanicalArchetype::RaptorSoaring
2914            | FaunaBiomechanicalArchetype::PasserinePsittacine
2915    ) {
2916        for side in [-1.0f32, 1.0] {
2917            for feather in 0..6 {
2918                let t = feather as f32 / 5.0;
2919                let wrist = if side < 0.0 { wrist_l } else { wrist_r };
2920                let elbow = if side < 0.0 { elbow_l } else { elbow_r };
2921                let base = [
2922                    wrist[0] * (1.0 - t * 0.35) + elbow[0] * t * 0.35,
2923                    wrist[1] - 0.015,
2924                    wrist[2] - body_len * t * 0.05,
2925                ];
2926                let tip = [
2927                    side * half_width * morphology.shoulder_span * (1.35 + t * 0.48),
2928                    wrist[1] - 0.025,
2929                    wrist[2] - body_len * (0.10 + t * 0.16),
2930                ];
2931                acc.push_cylinder(
2932                    base,
2933                    tip,
2934                    0.012,
2935                    0.0015,
2936                    6,
2937                    2,
2938                    integument_color,
2939                    ZoologicalAnatomicalLayer::ExternalIntegument,
2940                    JOINT_LEFT_WRIST_WING,
2941                    JOINT_LEFT_ELBOW,
2942                    0.8,
2943                );
2944            }
2945        }
2946    }
2947
2948    let int_mat = make_pbr_material("mat_integument", integument_color, 0.82, 0.0);
2949    materials.push(int_mat);
2950    submesh_ranges.push(SubmeshRange {
2951        first_index: int_start_idx,
2952        index_count: acc.indices.len() as u32 - int_start_idx,
2953        material_id: int_mat.id,
2954        semantic_id: q_hash("urn:qualia:bio:submesh:external_integument"),
2955    });
2956
2957    let int_end_v = acc.positions.len();
2958
2959    finalize_and_seal_vertebrate_anatomy_10d(
2960        archetype,
2961        acc,
2962        materials,
2963        submesh_ranges,
2964        ost_start_v..ost_end_v,
2965        myo_start_v..myo_end_v,
2966        int_start_v..int_end_v,
2967        osteology_vis_01,
2968        myology_vis_01,
2969        integument_vis_01,
2970        explode_layer_01,
2971    )
2972}
2973
2974/// Finalizes an [`AnatomyMeshAccumulator`] built from either a portable model-family scaffold
2975/// or a baseline archetype, applies zero-heap layer peeling & exploded-view displacement,
2976/// and seals the `.10d` Living Container (`MAT4`, `UV01`, `FNRM`, `SRD1`, `PROC1`,
2977/// `EONT1`, `MRP1`, `PROV`, `SKL1`) with whole-file CRC-32C verification.
2978#[allow(clippy::too_many_arguments)]
2979pub fn finalize_and_seal_vertebrate_anatomy_10d(
2980    archetype: FaunaBiomechanicalArchetype,
2981    mut acc: AnatomyMeshAccumulator,
2982    materials: Vec<MaterialRecord>,
2983    submesh_ranges: Vec<SubmeshRange>,
2984    osteology_range: std::ops::Range<usize>,
2985    myology_range: std::ops::Range<usize>,
2986    integument_range: std::ops::Range<usize>,
2987    osteology_vis_01: f32,
2988    myology_vis_01: f32,
2989    integument_vis_01: f32,
2990    explode_layer_01: f32,
2991) -> CompiledVertebrateAnatomy10d {
2992    let mut rig = FaunaSkeletalRig10d::new(archetype);
2993    if let Some(binding) = &acc.authored_skin {
2994        // Keep the legacy control-rig view consistent for its original eighteen joints.
2995        // The complete exported binding also carries the appended right forelimb.
2996        for i in 0..rig.joints.len().min(binding.joints.len()) {
2997            let old_rest_inverse = rig.rest_pose[i].conjugate();
2998            let rest = binding.joints[i].rest_local;
2999            for pose in &mut rig.clip_poses {
3000                pose[i] = rest.mul(&old_rest_inverse.mul(&pose[i])).normalize();
3001            }
3002            rig.rest_pose[i] = rest;
3003            rig.joints[i] = binding.joints[i];
3004        }
3005    }
3006    let (base_body_len, hip_height) = archetype.default_dimensions();
3007    let morphology = ArchetypeMorphology::for_archetype(archetype);
3008    let body_len = base_body_len * morphology.trunk;
3009    let spine_len = (body_len * 0.32).max(0.10);
3010    let femur_len = (hip_height * 0.48 * morphology.hindlimb).max(0.025);
3011    let (ost_start_v, ost_end_v) = (osteology_range.start, osteology_range.end);
3012    let (myo_start_v, myo_end_v) = (myology_range.start, myology_range.end);
3013    let (int_start_v, int_end_v) = (integument_range.start, integument_range.end);
3014
3015    // Ensure all positions and normals are strictly finite and unit-length for .10d FNRM validation
3016    for p in &mut acc.positions {
3017        for k in 0..3 {
3018            if !p[k].is_finite() {
3019                p[k] = 0.0;
3020            }
3021        }
3022    }
3023    for n in &mut acc.normals {
3024        let len_sq = n[0] * n[0] + n[1] * n[1] + n[2] * n[2];
3025        if len_sq.is_finite() && len_sq > 1e-8 {
3026            let inv = 1.0 / len_sq.sqrt();
3027            n[0] *= inv;
3028            n[1] *= inv;
3029            n[2] *= inv;
3030        } else {
3031            *n = [0.0, 1.0, 0.0];
3032        }
3033    }
3034
3035    // ── Apply Layer Visibility & Exploded View Displacements ─────────────────
3036    let total_v = acc.positions.len();
3037    let mut eval_positions = acc.positions.clone();
3038    let mut eval_alphas = vec![1.0f32; total_v];
3039
3040    evaluate_anatomical_layer_peel_zero_heap(
3041        &acc.positions,
3042        &acc.normals,
3043        &acc.layer_tags,
3044        osteology_vis_01,
3045        myology_vis_01,
3046        integument_vis_01,
3047        explode_layer_01,
3048        &mut eval_positions,
3049        &mut eval_alphas,
3050    );
3051
3052    // Merge computed alpha into RGBA colors
3053    for i in 0..total_v {
3054        acc.colors[i][3] *= eval_alphas[i];
3055    }
3056
3057    // Compute Mesh AABB
3058    let mut min = [f32::INFINITY; 3];
3059    let mut max = [f32::NEG_INFINITY; 3];
3060    for p in &eval_positions {
3061        for k in 0..3 {
3062            min[k] = min[k].min(p[k]);
3063            max[k] = max[k].max(p[k]);
3064        }
3065    }
3066
3067    let mut triangles = Vec::with_capacity(acc.indices.len() / 3);
3068    for tri in acc.indices.chunks_exact(3) {
3069        triangles.push([tri[0], tri[1], tri[2]]);
3070    }
3071
3072    let mesh = Mesh {
3073        positions: eval_positions.clone(),
3074        triangles,
3075        min,
3076        max,
3077    };
3078
3079    // ── Assemble & Seal .10d Container ───────────────────────────────────────
3080    let provenance = ProvenanceSidecar::new(
3081        format!("urn:qualia:fauna:scale5:{}", archetype.as_str()).into_bytes(),
3082        "application/vnd.ecopunk.fauna-anatomy;version=1",
3083        "Apache-2.0",
3084    );
3085
3086    let mut bytes = compile_mesh_to_10d_with_extras_and_frames(
3087        &mesh,
3088        &[],
3089        Some(&provenance),
3090        Compile10dExtras::default(),
3091        Some(&acc.colors),
3092        Some(&acc.normals),
3093        None,
3094    )
3095    .expect("compile_mesh_to_10d_with_extras_and_frames failed for vertebrate anatomy");
3096
3097    // MAT4 Material Section (materials must be sorted by id in ascending order)
3098    let mut sorted_materials = materials.clone();
3099    sorted_materials.sort_by_key(|m| m.id);
3100    sorted_materials.dedup_by_key(|m| m.id);
3101    super::vertebrate_layer_materials::apply_layer_opacity(
3102        &mut sorted_materials, &submesh_ranges, &acc.indices, &acc.colors,
3103    );
3104    bytes = attach_material_section(
3105        &bytes,
3106        &sorted_materials,
3107        &submesh_ranges,
3108        acc.indices.len() as u32,
3109    )
3110    .expect("attach_material_section failed");
3111
3112    // UV01 Texture Coordinate Section
3113    bytes = attach_texture_coordinate_section(&bytes, &acc.uvs)
3114        .expect("attach_texture_coordinate_section failed");
3115
3116    // PROC1 Procedural Synthesis Section
3117    let proc_header = ProceduralSynthesisHeader {
3118        magic: MAGIC_PROC,
3119        version: PROCEDURAL_SYNTHESIS_SECTION_VERSION,
3120        flags: (FLAG_CELLULAR_VORONOI
3121            | FLAG_IMPLICIT_FILLET
3122            | FLAG_ALLOMETRIC_GROWTH
3123            | FLAG_PGA_MOTOR_DYNAMICS) as u16,
3124        seed: q_hash(archetype.as_str()),
3125        voronoi_frequency: 14.5,
3126        voronoi_jitter: 0.80,
3127        fillet_blend_radius: 0.10,
3128        fillet_threshold: 0.04,
3129        allometry_exponent_k: 0.67,
3130        allometry_base_b: 1.12,
3131        spiral_growth_rate_k: 0.20,
3132        spiral_initial_radius_a: 0.05,
3133        motor_frequency_hz: 2.10,
3134        motor_damping_ratio: 0.06,
3135        critical_stress_threshold: 32.0,
3136        reserved_f32: 0.0,
3137    };
3138    bytes = attach_procedural_synthesis_section(&bytes, &proc_header)
3139        .expect("attach_procedural_synthesis_section failed");
3140
3141    // EONT1 Entity Ontology Section
3142    let onto_header = EntityOntologyMiniHeader {
3143        magic: MAGIC_EONT,
3144        version: ENTITY_ONTOLOGY_SECTION_VERSION,
3145        stage: 2, // Adult
3146        reserved_u8: 0,
3147        entity_did_hash: q_hash(&format!("did:qualia:fauna:{}", archetype.as_str())),
3148        taxon_iri_hash: q_hash(&format!("urn:qualia:taxon:{}", archetype.as_str())),
3149        energy_permill: 960,
3150        damage_permill: 20,
3151        hydration_permill: 910,
3152        wear_permill: 40,
3153        affordance_count: 3,
3154        reserved_u32: 4,
3155    };
3156
3157    let affordances = [
3158        AffordanceBinaryRecord {
3159            action_id: 0x0011,
3160            required_capability_hash: 0xCA00_1011,
3161            emitted_topic_hash: 0x7000_1011,
3162            category: 1, // Locomotion
3163            min_observer_status: 0,
3164            min_energy_permill: 100,
3165            max_damage_permill: 900,
3166            min_hydration_permill: 100,
3167            max_wear_permill: 950,
3168            energy_delta: -5,
3169            damage_delta: 0,
3170            hydration_delta: -2,
3171            wear_delta: 1,
3172            reserved_u16: 0,
3173            animation_clip_id: 1,
3174        },
3175        AffordanceBinaryRecord {
3176            action_id: 0x0012,
3177            required_capability_hash: 0xCA00_1012,
3178            emitted_topic_hash: 0x7000_1012,
3179            category: 2, // Foraging
3180            min_observer_status: 0,
3181            min_energy_permill: 50,
3182            max_damage_permill: 950,
3183            min_hydration_permill: 50,
3184            max_wear_permill: 980,
3185            energy_delta: 25,
3186            damage_delta: 0,
3187            hydration_delta: 10,
3188            wear_delta: 2,
3189            reserved_u16: 0,
3190            animation_clip_id: 2,
3191        },
3192        AffordanceBinaryRecord {
3193            action_id: 0x0013,
3194            required_capability_hash: 0xCA00_1013,
3195            emitted_topic_hash: 0x7000_1013,
3196            category: 3, // Vocalize / Social Display
3197            min_observer_status: 0,
3198            min_energy_permill: 80,
3199            max_damage_permill: 900,
3200            min_hydration_permill: 80,
3201            max_wear_permill: 900,
3202            energy_delta: -8,
3203            damage_delta: 0,
3204            hydration_delta: -4,
3205            wear_delta: 1,
3206            reserved_u16: 0,
3207            animation_clip_id: 3,
3208        },
3209    ];
3210
3211    let keyframes = [
3212        DevelopmentalKeyframeRecord {
3213            age_days: 60.0,
3214            stage: 0, // Neonate Pouch Young
3215            reserved_u8: 0,
3216            reserved_u16: 0,
3217            allometric_crown_scale: 0.20,
3218            allometric_trunk_scale: 0.15,
3219            lai_multiplier: 0.10,
3220            reserved_u32: 0,
3221            mesh_asset_hash: 0,
3222        },
3223        DevelopmentalKeyframeRecord {
3224            age_days: 240.0,
3225            stage: 1, // Sub-adult Joey
3226            reserved_u8: 0,
3227            reserved_u16: 0,
3228            allometric_crown_scale: 0.65,
3229            allometric_trunk_scale: 0.58,
3230            lai_multiplier: 0.50,
3231            reserved_u32: 0,
3232            mesh_asset_hash: 0,
3233        },
3234        DevelopmentalKeyframeRecord {
3235            age_days: 1200.0,
3236            stage: 2, // Mature Adult
3237            reserved_u8: 0,
3238            reserved_u16: 0,
3239            allometric_crown_scale: 1.0,
3240            allometric_trunk_scale: 1.0,
3241            lai_multiplier: 1.0,
3242            reserved_u32: 0,
3243            mesh_asset_hash: 0,
3244        },
3245        DevelopmentalKeyframeRecord {
3246            age_days: 4500.0,
3247            stage: 3, // Dominant Elder
3248            reserved_u8: 0,
3249            reserved_u16: 0,
3250            allometric_crown_scale: 1.15,
3251            allometric_trunk_scale: 1.25,
3252            lai_multiplier: 0.95,
3253            reserved_u32: 0,
3254            mesh_asset_hash: 0,
3255        },
3256    ];
3257
3258    bytes = attach_entity_ontology_section(&bytes, &onto_header, &affordances, &keyframes)
3259        .expect("attach_entity_ontology_section failed");
3260
3261    // MRP1 Morph Target Section (Costal Respiration, Gular Vocalization, Achilles Tendon Strain)
3262    let mut morph_deltas = Vec::with_capacity(total_v * 3 / 8);
3263    let step = (total_v / 64).max(1);
3264
3265    for vi in (0..total_v).step_by(step) {
3266        let p = eval_positions[vi];
3267        let n = acc.normals[vi];
3268        let layer = acc.layer_tags[vi];
3269
3270        // Target 0: Costal respiration (intercostal and ribcage expansion)
3271        if layer == ZoologicalAnatomicalLayer::Osteology
3272            || layer == ZoologicalAnatomicalLayer::MyologyAndTendons
3273        {
3274            let resp_amp = if p[1] > hip_height - 0.1 && p[1] < hip_height + 0.2 {
3275                0.035
3276            } else {
3277                0.008
3278            };
3279            let d0 = quantize_morph_delta(
3280                [n[0] * resp_amp, 0.015, n[2] * resp_amp],
3281                [n[0] * 0.1, 0.05, n[2] * 0.1],
3282                [0.0; 3],
3283                0.25,
3284                0,
3285                vi as u32,
3286            );
3287            morph_deltas.push(d0);
3288        }
3289
3290        // Target 1: Gular vocalization (neck / throat / jaw distension)
3291        if p[2] > spine_len * 0.5 {
3292            let gular_amp = 0.045;
3293            let d1 = quantize_morph_delta(
3294                [n[0] * gular_amp, -0.040, n[2] * gular_amp],
3295                [0.0, -0.1, 0.0],
3296                [0.0; 3],
3297                0.25,
3298                1,
3299                vi as u32,
3300            );
3301            morph_deltas.push(d1);
3302        }
3303
3304        // Target 2: Achilles tendon strain (spring elongation during locomotion)
3305        if p[1] < hip_height - femur_len * 0.5 && p[2] < 0.05 {
3306            let strain_amp = 0.055;
3307            let d2 = quantize_morph_delta(
3308                [0.0, -strain_amp, 0.012],
3309                [0.0, -0.05, 0.02],
3310                [0.0; 3],
3311                0.25,
3312                2,
3313                vi as u32,
3314            );
3315            morph_deltas.push(d2);
3316        }
3317    }
3318
3319    let morph_header = MorphSectionHeader {
3320        magic: MAGIC_MRP1,
3321        version: MORPH_SECTION_VERSION,
3322        target_count: 3,
3323        vertex_count: total_v as u32,
3324        flags: FLAG_MORPH_SPARSE | FLAG_MORPH_HAS_NORMALS | FLAG_MORPH_ONTOGENETIC_BIND,
3325        max_displacement: 0.25,
3326        ontogenetic_bind_mask: 0b0111,
3327        reserved: [0u8; 8],
3328    };
3329
3330    bytes = attach_morph_section(&bytes, &morph_header, &morph_deltas)
3331        .expect("attach_morph_section failed");
3332
3333    bytes = vertebrate_skin_seal::seal_skin(&bytes, &rig, acc.authored_skin.as_ref(), &acc.joint_indices, &acc.joint_weights)
3334        .expect("attach skeletal section failed");
3335
3336    CompiledVertebrateAnatomy10d {
3337        archetype,
3338        rig,
3339        authored_skin: acc.authored_skin,
3340        container_bytes: bytes,
3341        vertex_count: total_v,
3342        triangle_count: acc.indices.len() / 3,
3343        osteology_vertex_range: ost_start_v..ost_end_v,
3344        myology_vertex_range: myo_start_v..myo_end_v,
3345        integument_vertex_range: int_start_v..int_end_v,
3346        positions: eval_positions,
3347        normals: acc.normals,
3348        colors: acc.colors,
3349        uvs: acc.uvs,
3350        indices: acc.indices,
3351        materials: sorted_materials,
3352        submesh_ranges,
3353        skin_joint_indices: acc.joint_indices,
3354        skin_weights: acc.joint_weights,
3355        layer_tags: acc.layer_tags,
3356    }
3357}
3358
3359// ── Private Section Attachment Helpers ───────────────────────────────────────
3360
3361fn attach_raw_section(
3362    container: &[u8],
3363    section_type: SectionType,
3364    alignment_tier: AlignmentTier,
3365    stride: u32,
3366    element_count: u32,
3367    payload: &[u8],
3368) -> Result<Vec<u8>, String> {
3369    let header =
3370        Container10dHeader::parse(container).map_err(|e| format!("10d header parse: {e:?}"))?;
3371    let descriptors = parse_section_table(container, &header)
3372        .map_err(|e| format!("parse_section_table: {e:?}"))?;
3373    if descriptors.len() >= MAX_SECTION_COUNT as usize {
3374        return Err("MAX_SECTION_COUNT reached".into());
3375    }
3376
3377    let mut inputs = Vec::with_capacity(descriptors.len() + 1);
3378    for descriptor in descriptors {
3379        let start = descriptor.byte_offset as usize;
3380        let end = start
3381            .checked_add(descriptor.byte_length as usize)
3382            .filter(|&end| end <= container.len())
3383            .ok_or_else(|| {
3384                format!(
3385                    "SectionTableError::OutOfBounds offset={} length={}",
3386                    descriptor.byte_offset, descriptor.byte_length
3387                )
3388            })?;
3389        inputs.push(SectionInput {
3390            section_type: descriptor
3391                .typ()
3392                .ok_or_else(|| format!("UndefinedSectionType: {}", descriptor.section_type))?,
3393            alignment_tier: descriptor
3394                .tier()
3395                .ok_or_else(|| format!("UndefinedAlignmentTier: {}", descriptor.alignment_tier))?,
3396            stride: descriptor.stride,
3397            element_count: descriptor.element_count,
3398            payload: &container[start..end],
3399        });
3400    }
3401
3402    inputs.push(SectionInput {
3403        section_type,
3404        alignment_tier,
3405        stride,
3406        element_count,
3407        payload,
3408    });
3409
3410    let needed = match encode_container(&header, &inputs, &mut []) {
3411        Err(SectionTableError::OutputBufferTooSmall { needed, .. }) => needed,
3412        Ok(size) => size,
3413        Err(error) => return Err(format!("encode_container dry-run error: {error:?}")),
3414    };
3415    let mut output = vec![0u8; needed];
3416    let written = encode_container(&header, &inputs, &mut output)
3417        .map_err(|e| format!("encode_container error: {e:?}"))?;
3418    output.truncate(written);
3419    seal_whole_file_crc32c(&mut output);
3420    Ok(output)
3421}
3422
3423fn attach_procedural_synthesis_section(
3424    container: &[u8],
3425    header: &ProceduralSynthesisHeader,
3426) -> Result<Vec<u8>, String> {
3427    let mut buf = vec![0u8; PROCEDURAL_SYNTHESIS_HEADER_SIZE];
3428    encode_procedural_synthesis_section(header, &mut buf)
3429        .map_err(|e| format!("encode_procedural_synthesis_section: {e:?}"))?;
3430    attach_raw_section(
3431        container,
3432        SectionType::ProceduralSynthesis,
3433        AlignmentTier::CacheLine,
3434        0,
3435        0,
3436        &buf,
3437    )
3438}
3439
3440fn attach_entity_ontology_section(
3441    container: &[u8],
3442    header: &EntityOntologyMiniHeader,
3443    affordances: &[AffordanceBinaryRecord],
3444    keyframes: &[DevelopmentalKeyframeRecord],
3445) -> Result<Vec<u8>, String> {
3446    let mut hdr = *header;
3447    hdr.affordance_count = affordances.len() as u32;
3448    hdr.reserved_u32 = keyframes.len() as u32;
3449    let mut payload = Vec::with_capacity(
3450        ENTITY_ONTOLOGY_MINI_HEADER_SIZE
3451            + affordances.len() * AFFORDANCE_RECORD_SIZE
3452            + keyframes.len() * DEVELOPMENTAL_KEYFRAME_RECORD_SIZE,
3453    );
3454    payload.extend_from_slice(bytemuck::bytes_of(&hdr));
3455    for a in affordances {
3456        payload.extend_from_slice(bytemuck::bytes_of(a));
3457    }
3458    for k in keyframes {
3459        payload.extend_from_slice(bytemuck::bytes_of(k));
3460    }
3461    attach_raw_section(
3462        container,
3463        SectionType::EntityOntology,
3464        AlignmentTier::CacheLine,
3465        0,
3466        0,
3467        &payload,
3468    )
3469}
3470
3471fn attach_morph_section(
3472    container: &[u8],
3473    header: &MorphSectionHeader,
3474    deltas: &[QuantizedMorphDelta],
3475) -> Result<Vec<u8>, String> {
3476    let needed = morph_section_encoded_len(deltas.len()).ok_or_else(|| {
3477        format!(
3478            "morph_section_encoded_len overflow: deltas={}",
3479            deltas.len()
3480        )
3481    })?;
3482    let mut buf = vec![0u8; needed];
3483    encode_morph_section(header, deltas, &mut buf)
3484        .map_err(|e| format!("encode_morph_section: {e:?}"))?;
3485    attach_raw_section(
3486        container,
3487        SectionType::Reconstruction,
3488        AlignmentTier::CacheLine,
3489        0,
3490        0,
3491        &buf,
3492    )
3493}
3494
3495// ── Unit Tests ───────────────────────────────────────────────────────────────
3496
3497#[cfg(test)]
3498mod tests {
3499    use super::*;
3500    use crate::container_10d::integrity::verify_whole_file_crc32c;
3501
3502    #[test]
3503    fn wallaby_knee_loft_frames_do_not_flip() {
3504        let centers = [
3505            [0.068, 0.335, -0.115], [0.078, 0.278, -0.068],
3506            [0.078, 0.222, -0.025], [0.072, 0.152, -0.082],
3507            [0.066, 0.086, -0.136],
3508        ];
3509        let rings: Vec<_> = centers.into_iter().map(|center| AnatomicalLoftRing {
3510            center, radii: [0.03, 0.03], dorsal_color: [1.0; 4],
3511            flank_color: [1.0; 4], ventral_color: [1.0; 4],
3512            primary_joint: 0, secondary_joint: 1, primary_weight: 0.8,
3513        }).collect();
3514        let mut mesh = AnatomyMeshAccumulator::new();
3515        mesh.push_countershaded_loft(&rings, 32, ZoologicalAnatomicalLayer::ExternalIntegument, true);
3516        for i in 0..rings.len()-1 {
3517            let a = mesh.normals[i*33];
3518            let b = mesh.normals[(i+1)*33];
3519            let dot = a[0]*b[0]+a[1]*b[1]+a[2]*b[2];
3520            assert!(dot > 0.5, "adjacent knee ring frames flipped: {i}: {dot}");
3521        }
3522    }
3523
3524    const ALL_13_ARCHETYPES: [FaunaBiomechanicalArchetype; 13] = [
3525        FaunaBiomechanicalArchetype::MacropodSaltatorial,
3526        FaunaBiomechanicalArchetype::VombatidFossorial,
3527        FaunaBiomechanicalArchetype::PhascolarctidArboreal,
3528        FaunaBiomechanicalArchetype::PetauridGlider,
3529        FaunaBiomechanicalArchetype::DasyuridPredator,
3530        FaunaBiomechanicalArchetype::PteropodidChiroptera,
3531        FaunaBiomechanicalArchetype::MarinePinnipedCetacean,
3532        FaunaBiomechanicalArchetype::RatiteBipedal,
3533        FaunaBiomechanicalArchetype::RaptorSoaring,
3534        FaunaBiomechanicalArchetype::PasserinePsittacine,
3535        FaunaBiomechanicalArchetype::SquamateSprawling,
3536        FaunaBiomechanicalArchetype::SerpentineUndulatory,
3537        FaunaBiomechanicalArchetype::MonotremeTeleostAmphibian,
3538    ];
3539
3540    #[test]
3541    fn test_all_13_archetypes_build_valid_scale5_anatomy() {
3542        for arch in ALL_13_ARCHETYPES {
3543            let compiled = build_scale5_vertebrate_anatomy_10d(arch, 1.0, 1.0, 1.0, 0.0);
3544
3545            // 1. Verify high-resolution vertex count (>= 1,800)
3546            assert!(
3547                compiled.vertex_count >= 1800,
3548                "Archetype {:?} vertex count {} is below minimum 1,800",
3549                arch,
3550                compiled.vertex_count
3551            );
3552
3553            // 2. Verify submesh count & material count (17 distinct anatomical parts)
3554            assert_eq!(
3555                compiled.submesh_ranges.len(),
3556                17,
3557                "Archetype {:?} must have 17 submesh ranges (8 osteo + 8 myo + 1 integument)",
3558                arch
3559            );
3560            assert_eq!(compiled.materials.len(), 17);
3561
3562            // 3. Verify contiguous index stream without gaps
3563            let mut expected_first = 0u32;
3564            for range in &compiled.submesh_ranges {
3565                assert_eq!(range.first_index, expected_first);
3566                assert!(range.index_count > 0);
3567                expected_first += range.index_count;
3568            }
3569            assert_eq!(expected_first as usize, compiled.indices.len());
3570
3571            // 4. Verify 3-layer vertex intervals
3572            assert!(!compiled.osteology_vertex_range.is_empty());
3573            assert!(!compiled.myology_vertex_range.is_empty());
3574            assert!(!compiled.integument_vertex_range.is_empty());
3575            assert_eq!(
3576                compiled.osteology_vertex_range.end,
3577                compiled.myology_vertex_range.start
3578            );
3579            assert_eq!(
3580                compiled.myology_vertex_range.end,
3581                compiled.integument_vertex_range.start
3582            );
3583            assert_eq!(compiled.integument_vertex_range.end, compiled.vertex_count);
3584
3585            // 5. Verify non-empty .10d container bytes
3586            assert!(!compiled.container_bytes.is_empty());
3587            let skin = crate::container_10d::skeletal_container::read_skeletal_section(&compiled.container_bytes)
3588                .expect("sealed anatomy skin");
3589            assert_eq!(skin.counts().vertices, compiled.vertex_count);
3590            for i in 0..compiled.vertex_count {
3591                let influence = skin.skin(i).expect("vertex skin");
3592                assert_eq!(influence.joints, compiled.skin_joint_indices[i]);
3593                assert_eq!(influence.weights, compiled.skin_weights[i]);
3594            }
3595        }
3596    }
3597
3598    #[test]
3599    fn test_epipubic_bones_and_achilles_tendon_submeshes() {
3600        let compiled = build_scale5_vertebrate_anatomy_10d(
3601            FaunaBiomechanicalArchetype::MacropodSaltatorial,
3602            1.0,
3603            1.0,
3604            1.0,
3605            0.0,
3606        );
3607
3608        // Submesh 5: PelvicGirdleAndEpipubicBones
3609        let pelvis_range = &compiled.submesh_ranges[5];
3610        assert!(pelvis_range.index_count >= 36);
3611        assert_eq!(
3612            pelvis_range.semantic_id,
3613            q_hash("urn:qualia:bio:submesh:pelvic_epipubic_bones")
3614        );
3615
3616        // Submesh 9: ElasticAchillesTendonSpring
3617        let achilles_range = &compiled.submesh_ranges[9];
3618        assert!(achilles_range.index_count >= 36);
3619        assert_eq!(
3620            achilles_range.semantic_id,
3621            q_hash("urn:qualia:bio:submesh:achilles_tendon_spring")
3622        );
3623
3624        // Verify tendon material has collagen PBR properties
3625        let tendon_mat = compiled
3626            .materials
3627            .iter()
3628            .find(|material| material.id == achilles_range.material_id)
3629            .expect("Achilles submesh material");
3630        assert!(
3631            tendon_mat.roughness < 0.35,
3632            "Tendon should have smooth glistening collagen sheen"
3633        );
3634        assert!(
3635            tendon_mat.base_color[0] > 0.85,
3636            "Tendon should be ivory/white collagen"
3637        );
3638    }
3639
3640    #[test]
3641    fn test_zero_heap_layer_peeling() {
3642        let compiled = build_scale5_vertebrate_anatomy_10d(
3643            FaunaBiomechanicalArchetype::VombatidFossorial,
3644            1.0,
3645            1.0,
3646            1.0,
3647            0.0,
3648        );
3649
3650        let n = compiled.vertex_count;
3651        let mut out_positions = vec![[0.0f32; 3]; n];
3652        let mut out_alphas = vec![0.0f32; n];
3653
3654        // 1. Fully visible without explosion
3655        let count = evaluate_anatomical_layer_peel_zero_heap(
3656            &compiled.positions,
3657            &compiled.normals,
3658            &compiled.layer_tags,
3659            1.0,
3660            1.0,
3661            1.0,
3662            0.0,
3663            &mut out_positions,
3664            &mut out_alphas,
3665        );
3666        assert_eq!(count, n);
3667        for a in &out_alphas {
3668            assert_eq!(*a, 1.0);
3669        }
3670
3671        // 2. Hide integument (0.0), half myology (0.5), full osteology (1.0), exploded (1.0)
3672        evaluate_anatomical_layer_peel_zero_heap(
3673            &compiled.positions,
3674            &compiled.normals,
3675            &compiled.layer_tags,
3676            1.0,
3677            0.5,
3678            0.0,
3679            1.0,
3680            &mut out_positions,
3681            &mut out_alphas,
3682        );
3683
3684        // Check osteology: alpha = 1.0, displacement = 0
3685        for vi in compiled.osteology_vertex_range.clone() {
3686            assert_eq!(out_alphas[vi], 1.0);
3687            assert_eq!(out_positions[vi], compiled.positions[vi]);
3688        }
3689
3690        // Check myology: alpha = 0.5, displaced outward
3691        for vi in compiled.myology_vertex_range.clone() {
3692            assert_eq!(out_alphas[vi], 0.5);
3693            let disp = ((out_positions[vi][0] - compiled.positions[vi][0]).powi(2)
3694                + (out_positions[vi][1] - compiled.positions[vi][1]).powi(2)
3695                + (out_positions[vi][2] - compiled.positions[vi][2]).powi(2))
3696            .sqrt();
3697            assert!(disp > 0.05, "Myology layer should be exploded outward");
3698        }
3699
3700        // Check integument: alpha = 0.0, displaced even further outward
3701        for vi in compiled.integument_vertex_range.clone() {
3702            assert_eq!(out_alphas[vi], 0.0);
3703            let disp = ((out_positions[vi][0] - compiled.positions[vi][0]).powi(2)
3704                + (out_positions[vi][1] - compiled.positions[vi][1]).powi(2)
3705                + (out_positions[vi][2] - compiled.positions[vi][2]).powi(2))
3706            .sqrt();
3707            assert!(
3708                disp > 0.12,
3709                "Integument layer should be exploded furthest outward"
3710            );
3711        }
3712    }
3713
3714    #[test]
3715    fn test_10d_container_verification() {
3716        let compiled = build_scale5_vertebrate_anatomy_10d(
3717            FaunaBiomechanicalArchetype::MacropodSaltatorial,
3718            1.0,
3719            1.0,
3720            1.0,
3721            0.0,
3722        );
3723
3724        let mut bytes = compiled.container_bytes.clone();
3725
3726        // Verify valid 10d header
3727        let header = Container10dHeader::parse(&bytes).expect("Header parse must succeed");
3728        assert_eq!(header.magic, crate::container_10d::header::MAGIC_10D);
3729
3730        // Verify whole-file CRC32C seal
3731        verify_whole_file_crc32c(&mut bytes).expect("Whole-file CRC-32C verification must pass");
3732
3733        // Verify section table contents
3734        let descriptors =
3735            parse_section_table(&bytes, &header).expect("Section table parse must succeed");
3736        assert!(
3737            descriptors.len() >= 8,
3738            "Expected at least 8 sections, got {}",
3739            descriptors.len()
3740        );
3741
3742        let section_types: Vec<Option<SectionType>> = descriptors.iter().map(|d| d.typ()).collect();
3743        assert!(section_types.contains(&Some(SectionType::QuantizedMesh)));
3744        assert!(section_types.contains(&Some(SectionType::ProvenanceSidecar)));
3745        assert!(section_types.contains(&Some(SectionType::FieldSidecar)));
3746        assert!(section_types.contains(&Some(SectionType::SurfaceReading)));
3747        assert!(section_types.contains(&Some(SectionType::Materials)));
3748        assert!(section_types.contains(&Some(SectionType::TextureCoordinates)));
3749        assert!(section_types.contains(&Some(SectionType::Reconstruction))); // Morph targets
3750        assert!(section_types.contains(&Some(SectionType::EntityOntology)));
3751        assert!(section_types.contains(&Some(SectionType::ProceduralSynthesis)));
3752    }
3753}