Skip to main content

qualia_core_db/render/
botanical_anatomy.rs

1//! Botanical 4-Scale Digital Twin Anatomy, Histological Dissection & Living Container Generator.
2//!
3//! Implements **Epic 1** of `biological-education-assets-and-explorable-world-plan.md`
4//! for *Corymbia aparrerinja* (Ghost Gum) and Australian sclerophyll flora across
5//! four educational scales:
6//!
7//! 1. **Scale 1 — Whole-Organism Architecture & Subterranean Root System (`10 m – 40 m`):**
8//!    Continuous 5-order branching (bole $\to$ scaffold limbs $\to$ secondary/tertiary branches $\to$
9//!    terminal branchlets) via Runions space colonization, Leonardo da Vinci / Shinozaki Pipe Model
10//!    ($\eta = 2.49$) radius tapering, root flare allometry, lignotuber with epicormic meristem buds,
11//!    primary taproot, lateral buttress flares, and pendulous foliage clusters.
12//!
13//! 2. **Scale 2 — Branch Phyllotaxis & Stem/Bark Histology Wedge (`50 mm – 2 m`):**
14//!    Golden-angle ($\phi = 137.5077^\circ$) phyllotaxis plus a 270°-wedged transverse/radial/tangential
15//!    stem dissection with 6 concentric peelable tissue cylinders (`OuterRhytidome`, `PhellogenCorkCambium`,
16//!    `SecondaryPhloemAndKinoDucts`, `VascularCambium`, `SapwoodSecondaryXylem`, `HeartwoodAndPith`).
17//!
18//! 3. **Scale 3 — Floral & Fruit Reproductive Dissection (`5 mm – 150 mm`):**
19//!    Axillary 7-flowered umbellaster, fused `HypanthiumCalyxTube`, shedding `OperculumCalyptra` (driven
20//!    by anthesis progress and baked into `.10d` `MRP1` morph deltas), 48-filament inflexed/unfurling
21//!    `StaminalRingFilaments`, bilobed `VersatileAnthersAndPollen`, `GynoeciumStyleStigma`, 4-locule inferior
22//!    ovary with axile placentation and `OvaryLoculesAndOvules`, mature urceolate `WoodyPericarpAndDehiscingValves`,
23//!    and `FertileWingedSeedsAndChaff`.
24//!
25//! 4. **Scale 4 — Foliar Lamina Venation & Cellular Histology (`50 µm – 50 mm`):**
26//!    Falcate-lanceolate blade with Murray's Law ($r_p^3 = r_1^3 + r_2^3$) midrib, diagnostic Myrtaceae
27//!    intramarginal vein, pinnate secondaries, and tertiary reticulate areoles, paired with a magnified 3D
28//!    histological block featuring `WaxyCuticle`, `UpperAndLowerEpidermis`, sunken `AmphistomaticStomatalGuardCells`,
29//!    `IsobilateralPalisadeMesophyll`, `SpongyMesophyllAndAirSpaces`, `CollateralVascularBundleXylemPhloem`,
30//!    `SclerenchymaBundleSheathGirders`, and spherical `SchizogenousEssentialOilGland`.
31//!
32//! Strictly zero-V8, fully sealed `.10d` living containers with `MAT4`, `UV01`, `FNRM`, `SRD1`,
33//! `PROC1`, `EONT1`, `MRP1`, and `PROV` sections.
34
35use crate::container_10d::entity_ontology_section::{
36    AffordanceBinaryRecord, DevelopmentalKeyframeRecord, EntityOntologyMiniHeader,
37    AFFORDANCE_RECORD_SIZE, DEVELOPMENTAL_KEYFRAME_RECORD_SIZE, ENTITY_ONTOLOGY_MINI_HEADER_SIZE,
38    ENTITY_ONTOLOGY_SECTION_VERSION, MAGIC_EONT,
39};
40use crate::container_10d::header::{Container10dHeader, MAX_SECTION_COUNT};
41use crate::container_10d::integrity::{seal_whole_file_crc32c, verify_whole_file_crc32c};
42use crate::container_10d::morph_section::{
43    encode_morph_section, morph_section_encoded_len, quantize_morph_delta, MorphSectionHeader,
44    QuantizedMorphDelta, FLAG_MORPH_HAS_NORMALS, FLAG_MORPH_ONTOGENETIC_BIND, FLAG_MORPH_SPARSE,
45    MAGIC_MRP1, MORPH_SECTION_VERSION,
46};
47use crate::container_10d::procedural_synthesis::{
48    encode_procedural_synthesis_section, ProceduralSynthesisHeader, FLAG_ALLOMETRIC_GROWTH,
49    FLAG_CELLULAR_VORONOI, FLAG_IMPLICIT_FILLET, FLAG_PGA_MOTOR_DYNAMICS, MAGIC_PROC,
50    PROCEDURAL_SYNTHESIS_HEADER_SIZE, PROCEDURAL_SYNTHESIS_SECTION_VERSION,
51};
52use crate::container_10d::provenance_section::ProvenanceSidecar;
53use crate::container_10d::section::{
54    encode_container, parse_section_table, AlignmentTier, SectionInput, SectionTableError,
55    SectionType,
56};
57use crate::container_10d::{
58    attach_material_section, attach_texture_coordinate_section, MaterialRecord, OpacityMode,
59    ShadingModel, SubmeshRange,
60};
61use crate::q_hash;
62use crate::render::assets::Mesh;
63use crate::render::compile_10d::{compile_mesh_to_10d_with_extras_and_frames, Compile10dExtras};
64use crate::specialized_libs::computational_geometry::space_colonization::{
65    lateral_whorl_directions, space_colonization_3d, SpaceColonizationConfig, ROOT_PARENT,
66};
67use crate::specialized_libs::computational_geometry::tree_skeleton_3d::pipe_model_radii;
68use crate::specialized_libs::computational_geometry::Point3;
69use bytemuck;
70use etalon_sim::leaf_biophysics::{LeafEconomicsProfile, LeafVascularSkeleton};
71use etalon_sim::metamer_fspm::{Metamer, MetamerOrgan, MetamerPlantGraph, ThermalPhenology};
72use serde::{Deserialize, Serialize};
73use sha2::{Digest, Sha256};
74use std::f32::consts::PI;
75#[cfg(not(target_arch = "wasm32"))]
76use std::fs;
77#[cfg(not(target_arch = "wasm32"))]
78use std::io::Write;
79#[cfg(not(target_arch = "wasm32"))]
80use std::path::Path;
81
82// Coverage splitting is kept separate from the multi-scale geometry builders.
83#[path = "botanical_materials.rs"]
84mod tissue_materials;
85
86/// Canonical golden ratio angle ($\phi = 137.507764^\circ$) in radians.
87pub const GOLDEN_ANGLE_RAD: f32 = 2.39996323;
88pub const GOLDEN_ANGLE: f32 = GOLDEN_ANGLE_RAD;
89
90/// Leonardo da Vinci / Shinozaki pipe exponent for eucalyptus crown hydraulic architecture.
91pub const PIPE_EXPONENT_EUCALYPTUS: f64 = 2.49;
92
93/// Re-export upstream FSPM plant architecture type.
94pub type PlantArchitecture = MetamerPlantGraph;
95
96// ============================================================================
97// 1. Core Educational Scales & Anatomical Taxonomies
98// ============================================================================
99
100/// Four progressive spatial scales of botanical digital twin education.
101#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
102pub enum BotanicalEducationScale {
103    /// Whole tree habit, bole, 5-order branching canopy, and subterranean root architecture.
104    Scale1WholeOrganismAndRoots,
105    /// Metamer internodes, golden-angle phyllotaxis, and 6-layer concentric stem histology wedge.
106    Scale2BranchPhyllotaxisAndStemWedge,
107    /// 7-flowered umbellaster, calyptrate flower anthesis, and woody dehiscing gumnut capsule.
108    Scale3FloralAndGumnutDissection,
109    /// Isobilateral sclerophyll lamina, Murray's Law venation, intramarginal vein, and cellular layers.
110    Scale4FoliarVenationAndCellularHistology,
111}
112
113impl BotanicalEducationScale {
114    pub const fn name(&self) -> &'static str {
115        match self {
116            Self::Scale1WholeOrganismAndRoots => "Scale 1: Whole Organism & Root Architecture",
117            Self::Scale2BranchPhyllotaxisAndStemWedge => {
118                "Scale 2: Branch Phyllotaxis & Stem Wedge Anatomy"
119            }
120            Self::Scale3FloralAndGumnutDissection => {
121                "Scale 3: Floral & Fruit Reproductive Dissection"
122            }
123            Self::Scale4FoliarVenationAndCellularHistology => {
124                "Scale 4: Foliar Lamina Venation & Cellular Histology"
125            }
126        }
127    }
128
129    pub const fn physical_range(&self) -> &'static str {
130        match self {
131            Self::Scale1WholeOrganismAndRoots => "10 m – 40 m",
132            Self::Scale2BranchPhyllotaxisAndStemWedge => "50 mm – 2 m",
133            Self::Scale3FloralAndGumnutDissection => "5 mm – 150 mm",
134            Self::Scale4FoliarVenationAndCellularHistology => "50 µm – 50 mm",
135        }
136    }
137
138    pub const fn description(&self) -> &'static str {
139        match self {
140            Self::Scale1WholeOrganismAndRoots => {
141                "Macroscopic organismal habit, Leonardo da Vinci pipe model crown, lignotuber and subterranean roots"
142            }
143            Self::Scale2BranchPhyllotaxisAndStemWedge => {
144                "Stem metamer, 137.5° spiral phyllotaxis, and peelable 6-layer concentric tissue histology wedge"
145            }
146            Self::Scale3FloralAndGumnutDissection => {
147                "Axillary umbellaster, circumscissile operculum shedding, inflexed stamens, and dehiscing woody capsule"
148            }
149            Self::Scale4FoliarVenationAndCellularHistology => {
150                "Falcate lamina, intramarginal vein, amphistomatic guard cells, isobilateral mesophyll, and oil glands"
151            }
152        }
153    }
154}
155
156/// Ontogenetic developmental stage of the botanical digital twin organism.
157#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
158pub enum DevelopmentalStage {
159    /// Germinant / seedling with cotyledons and opposite juvenile glaucous leaves.
160    Seedling,
161    /// Upright competing sapling with transitional alternate petiolate foliage.
162    Sapling,
163    /// Fully mature canopy with chalk-white bole, mass flowering, and fruiting capsules.
164    Mature,
165    /// Veteran tree with dead staghorn crown limbs, fungal heartwood decay hollows, and epicormic bursts.
166    AncientHollowBearing,
167}
168
169impl DevelopmentalStage {
170    pub const fn stage_id(&self) -> u8 {
171        match self {
172            Self::Seedling => 0,
173            Self::Sapling => 1,
174            Self::Mature => 2,
175            Self::AncientHollowBearing => 3,
176        }
177    }
178
179    pub const fn description(&self) -> &'static str {
180        match self {
181            Self::Seedling => "Seedling (cotyledons, opposite ovate leaves, juvenile lignotuber)",
182            Self::Sapling => "Sapling (competing leaders, upright scaffold limbs, transitional foliage)",
183            Self::Mature => "Mature (spreading irregular canopy, smooth chalk bole, full reproductive capacity)",
184            Self::AncientHollowBearing => "Ancient Veteran (senescent staghorn limbs, trunk hollow cavities, epicormic regrowth)",
185        }
186    }
187}
188
189/// Dissectible and peelable botanical tissue layer with Plant Ontology (PO) bindings.
190#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
191pub enum HistologicalTissueLayer {
192    // --- Scale 2: Stem & Bark Histological Layers ---
193    /// Outer dead bark / shed flakes (Plant Ontology: PO:0004518).
194    OuterRhytidome,
195    /// Secondary cork cambium and phelloderm meristem (PO:0005597).
196    PhellogenCorkCambium,
197    /// Inner conducting bark with sieve tubes, fibers, and kino resin ducts (PO:0004523).
198    SecondaryPhloemAndKinoDucts,
199    /// Uniseriate lateral meristem ring producing xylem inwardly and phloem outwardly (PO:0005598).
200    VascularCambium,
201    /// Active water-conducting secondary xylem with annual rings, vessel pores, and medullary rays (PO:0004524).
202    SapwoodSecondaryXylem,
203    /// Polyphenol-impregnated structural core (duramen) and central primary pith (PO:0004525).
204    HeartwoodAndPith,
205
206    // --- Scale 3: Floral & Fruit Reproductive Layers ---
207    /// Inflorescence stalk and individual flower stalks of the 7-flowered umbellaster (PO:0009053).
208    PeduncleAndPedicel,
209    /// Floral cup fused with the inferior ovary wall (PO:0009064).
210    HypanthiumCalyxTube,
211    /// Calyptriform bud cap shedding circumscissilely at anthesis (PO:0009049).
212    OperculumCalyptra,
213    /// Inflexed multi-whorl cream filaments emerging from the floral ring (PO:0009066).
214    StaminalRingFilaments,
215    /// Dorsifixed versatile bilobed anther sacs containing microspores/pollen (PO:0009067).
216    VersatileAnthersAndPollen,
217    /// Central terete style, papillate stigma, and nectariferous disc (PO:0009072).
218    GynoeciumStyleStigma,
219    /// Inferior ovary cutaway showing 4 locule chambers, axile placenta, and ovules (PO:0009062).
220    OvaryLoculesAndOvules,
221    /// Thick woody capsule wall with 4 sunken triangular dehiscing valves (PO:0009084).
222    WoodyPericarpAndDehiscingValves,
223    /// Terminal-winged fertile seeds and sterile crystalline red-brown chaff (PO:0009010).
224    FertileWingedSeedsAndChaff,
225
226    // --- Scale 4: Foliar Lamina & Cellular Histological Layers ---
227    /// Epicuticular wax film with crystalline micro-platelets (PO:0000030).
228    WaxyCuticle,
229    /// Adaxial and abaxial uniseriate cobblestone epidermal pavement cells (PO:0000040).
230    UpperAndLowerEpidermis,
231    /// Sunken paired kidney-shaped guard cells and substomatal respiratory cavities (PO:0002000).
232    AmphistomaticStomatalGuardCells,
233    /// Symmetrical 2-layer columnar chlorenchyma on both adaxial and abaxial surfaces (PO:0006079).
234    IsobilateralPalisadeMesophyll,
235    /// Central loosely packed aerating parenchyma with intercellular gas channels (PO:0006080).
236    SpongyMesophyllAndAirSpaces,
237    /// Collateral vascular bundles: adaxial xylem tracheary vessels + abaxial phloem sieve tubes (PO:0005020).
238    CollateralVascularBundleXylemPhloem,
239    /// Lignified I-beam bundle sheath extensions anchoring veins to both epidermises (PO:0004533).
240    SclerenchymaBundleSheathGirders,
241    /// Spherical internal secretory cavity lined with epithelial cells producing essential oils (PO:0004540).
242    SchizogenousEssentialOilGland,
243}
244
245impl HistologicalTissueLayer {
246    /// Return the canonical Plant Ontology (PO) identifier.
247    pub const fn plant_ontology_id(&self) -> &'static str {
248        match self {
249            Self::OuterRhytidome => "PO:0004518",
250            Self::PhellogenCorkCambium => "PO:0005597",
251            Self::SecondaryPhloemAndKinoDucts => "PO:0004523",
252            Self::VascularCambium => "PO:0005598",
253            Self::SapwoodSecondaryXylem => "PO:0004524",
254            Self::HeartwoodAndPith => "PO:0004525",
255            Self::PeduncleAndPedicel => "PO:0009053",
256            Self::HypanthiumCalyxTube => "PO:0009064",
257            Self::OperculumCalyptra => "PO:0009049",
258            Self::StaminalRingFilaments => "PO:0009066",
259            Self::VersatileAnthersAndPollen => "PO:0009067",
260            Self::GynoeciumStyleStigma => "PO:0009072",
261            Self::OvaryLoculesAndOvules => "PO:0009062",
262            Self::WoodyPericarpAndDehiscingValves => "PO:0009084",
263            Self::FertileWingedSeedsAndChaff => "PO:0009010",
264            Self::WaxyCuticle => "PO:0000030",
265            Self::UpperAndLowerEpidermis => "PO:0000040",
266            Self::AmphistomaticStomatalGuardCells => "PO:0002000",
267            Self::IsobilateralPalisadeMesophyll => "PO:0006079",
268            Self::SpongyMesophyllAndAirSpaces => "PO:0006080",
269            Self::CollateralVascularBundleXylemPhloem => "PO:0005020",
270            Self::SclerenchymaBundleSheathGirders => "PO:0004533",
271            Self::SchizogenousEssentialOilGland => "PO:0004540",
272        }
273    }
274
275    /// English scientific common name.
276    pub const fn common_name(&self) -> &'static str {
277        match self {
278            Self::OuterRhytidome => "Outer Rhytidome (Chalk Bark Flakes)",
279            Self::PhellogenCorkCambium => "Phellogen (Cork Cambium & Phelloderm)",
280            Self::SecondaryPhloemAndKinoDucts => "Secondary Phloem & Kino Resin Ducts",
281            Self::VascularCambium => "Vascular Cambium (Lateral Meristem Ring)",
282            Self::SapwoodSecondaryXylem => "Sapwood (Secondary Xylem & Rays)",
283            Self::HeartwoodAndPith => "Heartwood (Duramen) & Central Pith",
284            Self::PeduncleAndPedicel => "Peduncle & Pedicels (Umbellaster Stalks)",
285            Self::HypanthiumCalyxTube => "Hypanthium (Floral Calyx Tube)",
286            Self::OperculumCalyptra => "Operculum (Calyptra Bud Cap)",
287            Self::StaminalRingFilaments => "Staminal Ring Filaments (Androecium)",
288            Self::VersatileAnthersAndPollen => "Versatile Anthers & Pollen Grains",
289            Self::GynoeciumStyleStigma => "Gynoecium (Style, Stigma & Nectar Disc)",
290            Self::OvaryLoculesAndOvules => "Inferior Ovary (4 Locules, Placenta & Ovules)",
291            Self::WoodyPericarpAndDehiscingValves => "Woody Pericarp & Dehiscing Valves",
292            Self::FertileWingedSeedsAndChaff => "Fertile Winged Seeds & Chaff",
293            Self::WaxyCuticle => "Epicuticular Waxy Cuticle Platelets",
294            Self::UpperAndLowerEpidermis => "Upper & Lower Epidermis Pavement Cells",
295            Self::AmphistomaticStomatalGuardCells => "Amphistomatic Stomatal Guard Cells",
296            Self::IsobilateralPalisadeMesophyll => "Isobilateral Palisade Mesophyll Columns",
297            Self::SpongyMesophyllAndAirSpaces => "Spongy Mesophyll Parenchyma & Air Spaces",
298            Self::CollateralVascularBundleXylemPhloem => {
299                "Collateral Vascular Bundle (Xylem & Phloem)"
300            }
301            Self::SclerenchymaBundleSheathGirders => "Sclerenchyma Bundle Sheath Girders",
302            Self::SchizogenousEssentialOilGland => "Schizogenous Essential Oil Secretory Cavity",
303        }
304    }
305
306    /// Associated educational scale.
307    pub const fn scale(&self) -> BotanicalEducationScale {
308        match self {
309            Self::OuterRhytidome
310            | Self::PhellogenCorkCambium
311            | Self::SecondaryPhloemAndKinoDucts
312            | Self::VascularCambium
313            | Self::SapwoodSecondaryXylem
314            | Self::HeartwoodAndPith => {
315                BotanicalEducationScale::Scale2BranchPhyllotaxisAndStemWedge
316            }
317
318            Self::PeduncleAndPedicel
319            | Self::HypanthiumCalyxTube
320            | Self::OperculumCalyptra
321            | Self::StaminalRingFilaments
322            | Self::VersatileAnthersAndPollen
323            | Self::GynoeciumStyleStigma
324            | Self::OvaryLoculesAndOvules
325            | Self::WoodyPericarpAndDehiscingValves
326            | Self::FertileWingedSeedsAndChaff => {
327                BotanicalEducationScale::Scale3FloralAndGumnutDissection
328            }
329
330            Self::WaxyCuticle
331            | Self::UpperAndLowerEpidermis
332            | Self::AmphistomaticStomatalGuardCells
333            | Self::IsobilateralPalisadeMesophyll
334            | Self::SpongyMesophyllAndAirSpaces
335            | Self::CollateralVascularBundleXylemPhloem
336            | Self::SclerenchymaBundleSheathGirders
337            | Self::SchizogenousEssentialOilGland => {
338                BotanicalEducationScale::Scale4FoliarVenationAndCellularHistology
339            }
340        }
341    }
342
343    /// Diagnostic default RGBA color.
344    pub const fn default_color_rgba(&self) -> [f32; 4] {
345        match self {
346            Self::OuterRhytidome => [0.93, 0.92, 0.88, 1.0], // Chalky white
347            Self::PhellogenCorkCambium => [0.58, 0.64, 0.44, 1.0], // Olive green meristem
348            Self::SecondaryPhloemAndKinoDucts => [0.72, 0.44, 0.28, 1.0], // Warm amber phloem
349            Self::VascularCambium => [0.78, 0.88, 0.52, 1.0], // Pale lime dividing ring
350            Self::SapwoodSecondaryXylem => [0.86, 0.79, 0.67, 1.0], // Cream active wood
351            Self::HeartwoodAndPith => [0.42, 0.22, 0.16, 1.0], // Deep tannin duramen
352
353            Self::PeduncleAndPedicel => [0.48, 0.56, 0.38, 1.0], // Glaucous green stem
354            Self::HypanthiumCalyxTube => [0.74, 0.72, 0.56, 1.0], // Creamy-green cup
355            Self::OperculumCalyptra => [0.88, 0.84, 0.68, 1.0],  // Pale conical cap
356            Self::StaminalRingFilaments => [0.98, 0.96, 0.85, 1.0], // Fluffy cream filaments
357            Self::VersatileAnthersAndPollen => [0.96, 0.82, 0.24, 1.0], // Golden yellow pollen
358            Self::GynoeciumStyleStigma => [0.65, 0.78, 0.48, 1.0], // Translucent green style
359            Self::OvaryLoculesAndOvules => [0.82, 0.86, 0.70, 1.0], // Pale ovule interior
360            Self::WoodyPericarpAndDehiscingValves => [0.46, 0.38, 0.30, 1.0], // Weathered brown gumnut
361            Self::FertileWingedSeedsAndChaff => [0.28, 0.18, 0.12, 1.0], // Dark chocolate seeds
362
363            Self::WaxyCuticle => [0.82, 0.88, 0.84, 0.85], // Glaucous translucent wax
364            Self::UpperAndLowerEpidermis => [0.46, 0.62, 0.42, 1.0], // Bright epidermal green
365            Self::AmphistomaticStomatalGuardCells => [0.36, 0.54, 0.32, 1.0], // Kidney guard cell green
366            Self::IsobilateralPalisadeMesophyll => [0.24, 0.48, 0.22, 1.0], // Deep chloroplast green
367            Self::SpongyMesophyllAndAirSpaces => [0.38, 0.58, 0.36, 0.9],   // Aerated parenchyma
368            Self::CollateralVascularBundleXylemPhloem => [0.75, 0.68, 0.48, 1.0], // Lignified xylem/phloem
369            Self::SclerenchymaBundleSheathGirders => [0.82, 0.76, 0.54, 1.0], // Lignified fibrous girders
370            Self::SchizogenousEssentialOilGland => [0.95, 0.84, 0.35, 0.95],  // Golden cineole oil
371        }
372    }
373
374    /// Default physical roughness and metallic parameters `(roughness, metallic)`.
375    pub const fn default_pbr_material(&self) -> (f32, f32) {
376        match self {
377            Self::OuterRhytidome => (0.92, 0.0),
378            Self::PhellogenCorkCambium => (0.75, 0.0),
379            Self::SecondaryPhloemAndKinoDucts => (0.55, 0.02),
380            Self::VascularCambium => (0.60, 0.0),
381            Self::SapwoodSecondaryXylem => (0.80, 0.0),
382            Self::HeartwoodAndPith => (0.85, 0.0),
383
384            Self::PeduncleAndPedicel => (0.70, 0.0),
385            Self::HypanthiumCalyxTube => (0.65, 0.0),
386            Self::OperculumCalyptra => (0.68, 0.0),
387            Self::StaminalRingFilaments => (0.45, 0.0),
388            Self::VersatileAnthersAndPollen => (0.50, 0.0),
389            Self::GynoeciumStyleStigma => (0.40, 0.0),
390            Self::OvaryLoculesAndOvules => (0.60, 0.0),
391            Self::WoodyPericarpAndDehiscingValves => (0.88, 0.0),
392            Self::FertileWingedSeedsAndChaff => (0.78, 0.0),
393
394            Self::WaxyCuticle => (0.28, 0.0),
395            Self::UpperAndLowerEpidermis => (0.55, 0.0),
396            Self::AmphistomaticStomatalGuardCells => (0.50, 0.0),
397            Self::IsobilateralPalisadeMesophyll => (0.65, 0.0),
398            Self::SpongyMesophyllAndAirSpaces => (0.70, 0.0),
399            Self::CollateralVascularBundleXylemPhloem => (0.75, 0.0),
400            Self::SclerenchymaBundleSheathGirders => (0.80, 0.0),
401            Self::SchizogenousEssentialOilGland => (0.18, 0.0),
402        }
403    }
404}
405
406/// A contiguous submesh range representing an individual histological tissue layer.
407#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
408pub struct TissueSubmeshSlice {
409    pub layer: HistologicalTissueLayer,
410    pub vertex_start: u32,
411    pub vertex_count: u32,
412    pub index_start: u32,
413    pub index_count: u32,
414    pub plant_ontology_id: &'static str,
415    pub common_name: &'static str,
416}
417
418/// Compiled high-density botanical organ with full living `.10d` container bytes.
419#[derive(Debug, Clone)]
420pub struct CompiledBotanicalOrgan10d {
421    pub scale: BotanicalEducationScale,
422    pub vertices: Vec<[f32; 3]>,
423    pub normals: Vec<[f32; 3]>,
424    pub uvs: Vec<[f32; 2]>,
425    pub colors: Vec<[u8; 4]>,
426    pub material_indices: Vec<u8>,
427    pub indices: Vec<u32>,
428    pub tissue_slices: Vec<TissueSubmeshSlice>,
429    pub container_bytes: Vec<u8>,
430}
431
432impl CompiledBotanicalOrgan10d {
433    /// Total vertices in organ mesh.
434    pub fn vertex_count(&self) -> usize {
435        self.vertices.len()
436    }
437
438    /// Total triangles in organ mesh.
439    pub fn triangle_count(&self) -> usize {
440        self.indices.len() / 3
441    }
442
443    /// Find the submesh slice for a specific tissue layer.
444    pub fn tissue_layer_slice(
445        &self,
446        layer: HistologicalTissueLayer,
447    ) -> Option<&TissueSubmeshSlice> {
448        self.tissue_slices.iter().find(|s| s.layer == layer)
449    }
450
451    /// Verify structural, section table, CRC-32C, and geometric integrity.
452    pub fn verify_all(&self) -> Result<(), String> {
453        if self.container_bytes.len() < 64 {
454            return Err("Container bytes too short for 10D header".into());
455        }
456        let header = Container10dHeader::parse(&self.container_bytes)
457            .map_err(|e| format!("Header parse error: {e:?}"))?;
458
459        let descriptors = parse_section_table(&self.container_bytes, &header)
460            .map_err(|e| format!("Section table parse error: {e:?}"))?;
461        if descriptors.is_empty() {
462            return Err("Section table is empty".into());
463        }
464
465        let mut bytes_copy = self.container_bytes.clone();
466        verify_whole_file_crc32c(&mut bytes_copy)
467            .map_err(|e| format!("Whole file CRC-32C verification failed: {e:?}"))?;
468
469        if self.vertices.is_empty() {
470            return Err("Organ vertices must not be empty".into());
471        }
472        if self.indices.len() % 3 != 0 {
473            return Err("Indices count must be a multiple of 3".into());
474        }
475        for &idx in &self.indices {
476            if (idx as usize) >= self.vertices.len() {
477                return Err(format!(
478                    "Index out of range: {idx} >= {}",
479                    self.vertices.len()
480                ));
481            }
482        }
483        if self.normals.len() != self.vertices.len() {
484            return Err("Normals length does not match vertices".into());
485        }
486        if self.uvs.len() != self.vertices.len() {
487            return Err("UVs length does not match vertices".into());
488        }
489        if self.colors.len() != self.vertices.len() {
490            return Err("Colors length does not match vertices".into());
491        }
492
493        for slice in &self.tissue_slices {
494            if (slice.vertex_start as usize) + (slice.vertex_count as usize) > self.vertices.len() {
495                return Err(format!(
496                    "Slice vertex range out of bounds for layer {:?}",
497                    slice.layer
498                ));
499            }
500            if (slice.index_start as usize) + (slice.index_count as usize) > self.indices.len() {
501                return Err(format!(
502                    "Slice index range out of bounds for layer {:?}",
503                    slice.layer
504                ));
505            }
506        }
507
508        Ok(())
509    }
510}
511
512// ============================================================================
513// 2. Allometry & Upstream Computational Geometry Utilities
514// ============================================================================
515
516/// Allometric root flare radius at depth $d$ below the ground line ($d \ge 0$):
517/// $r_{\text{flare}}(d) = r_{\text{collar}} \cdot (1.0 + \alpha_{\text{flare}} \cdot e^{-\beta_{\text{flare}} \cdot d})$
518pub fn root_flare_radius(base_radius: f64, depth_m: f64, flare_factor: f64) -> f64 {
519    base_radius * (1.0 + flare_factor * (-depth_m.abs() * 2.5).exp())
520}
521
522/// Run deterministic 3D space colonization from `seed_nodes` towards `attractors`.
523pub fn grow_crown(
524    attractors: &[Point3],
525    seeds: &[Point3],
526    seed_parents: &[u32],
527    cfg: &SpaceColonizationConfig,
528    out_nodes: &mut [Point3],
529    out_parents: &mut [u32],
530) -> Result<usize, String> {
531    space_colonization_3d(attractors, seeds, seed_parents, cfg, out_nodes, out_parents)
532        .map(|r| r.node_count)
533        .map_err(|e| format!("space_colonization error: {e:?}"))
534}
535
536/// Emit lateral buds with golden-angle or whorled phyllotaxis.
537pub fn emit_lateral_buds(
538    axis_dir: Point3,
539    insertion_angle_rad: f64,
540    count: usize,
541    out_dirs: &mut [Point3],
542) -> Result<usize, String> {
543    lateral_whorl_directions(axis_dir, insertion_angle_rad, count, out_dirs)
544        .map_err(|e| format!("emit_lateral_buds error: {e:?}"))
545}
546
547// ============================================================================
548// 3. Organ Mesh Builder & Container Sealer
549// ============================================================================
550
551struct OrganMeshBuilder {
552    positions: Vec<[f32; 3]>,
553    normals: Vec<[f32; 3]>,
554    uvs: Vec<[f32; 2]>,
555    colors: Vec<[u8; 4]>,
556    material_indices: Vec<u8>,
557    indices: Vec<u32>,
558    slices: Vec<TissueSubmeshSlice>,
559    active_layer: Option<(HistologicalTissueLayer, u32, u32)>,
560    current_mat_idx: u8,
561}
562
563impl OrganMeshBuilder {
564    fn new() -> Self {
565        Self {
566            positions: Vec::with_capacity(4096),
567            normals: Vec::with_capacity(4096),
568            uvs: Vec::with_capacity(4096),
569            colors: Vec::with_capacity(4096),
570            material_indices: Vec::with_capacity(4096),
571            indices: Vec::with_capacity(16384),
572            slices: Vec::new(),
573            active_layer: None,
574            current_mat_idx: 0,
575        }
576    }
577
578    fn begin_tissue_layer(&mut self, layer: HistologicalTissueLayer, mat_idx: u8) {
579        if self.active_layer.is_some() {
580            self.end_tissue_layer();
581        }
582        let v_start = self.positions.len() as u32;
583        let i_start = self.indices.len() as u32;
584        self.active_layer = Some((layer, v_start, i_start));
585        self.current_mat_idx = mat_idx;
586    }
587
588    fn end_tissue_layer(&mut self) {
589        if let Some((layer, v_start, i_start)) = self.active_layer.take() {
590            let v_count = (self.positions.len() as u32).saturating_sub(v_start);
591            let i_count = (self.indices.len() as u32).saturating_sub(i_start);
592            self.slices.push(TissueSubmeshSlice {
593                layer,
594                vertex_start: v_start,
595                vertex_count: v_count,
596                index_start: i_start,
597                index_count: i_count,
598                plant_ontology_id: layer.plant_ontology_id(),
599                common_name: layer.common_name(),
600            });
601        }
602    }
603
604    fn add_vertex(&mut self, pos: [f32; 3], norm: [f32; 3], uv: [f32; 2], col: [u8; 4]) -> u32 {
605        let idx = self.positions.len() as u32;
606        self.positions.push(pos);
607        self.normals.push(norm);
608        self.uvs.push(uv);
609        self.colors.push(col);
610        self.material_indices.push(self.current_mat_idx);
611        idx
612    }
613
614    fn add_triangle(&mut self, i0: u32, i1: u32, i2: u32) {
615        self.indices.push(i0);
616        self.indices.push(i1);
617        self.indices.push(i2);
618    }
619
620    fn add_quad(&mut self, i0: u32, i1: u32, i2: u32, i3: u32) {
621        self.add_triangle(i0, i1, i2);
622        self.add_triangle(i0, i2, i3);
623    }
624
625    /// Rebuild smooth vertex normals for newly appended geometry from its indexed triangles.
626    fn recompute_normals_since(&mut self, vertex_start: usize, index_start: usize) {
627        if vertex_start >= self.positions.len() || index_start >= self.indices.len() {
628            return;
629        }
630        self.normals[vertex_start..].fill([0.0; 3]);
631        for tri in self.indices[index_start..].chunks_exact(3) {
632            let a_idx = tri[0] as usize;
633            let b_idx = tri[1] as usize;
634            let c_idx = tri[2] as usize;
635            if a_idx < vertex_start || b_idx < vertex_start || c_idx < vertex_start {
636                continue;
637            }
638            let a = self.positions[a_idx];
639            let b = self.positions[b_idx];
640            let c = self.positions[c_idx];
641            let ab = [b[0] - a[0], b[1] - a[1], b[2] - a[2]];
642            let ac = [c[0] - a[0], c[1] - a[1], c[2] - a[2]];
643            let face = [
644                ab[1] * ac[2] - ab[2] * ac[1],
645                ab[2] * ac[0] - ab[0] * ac[2],
646                ab[0] * ac[1] - ab[1] * ac[0],
647            ];
648            for idx in [a_idx, b_idx, c_idx] {
649                let normal = &mut self.normals[idx];
650                normal[0] += face[0];
651                normal[1] += face[1];
652                normal[2] += face[2];
653            }
654        }
655        for normal in &mut self.normals[vertex_start..] {
656            let len =
657                (normal[0] * normal[0] + normal[1] * normal[1] + normal[2] * normal[2]).sqrt();
658            if len > 1e-8 {
659                normal[0] /= len;
660                normal[1] /= len;
661                normal[2] /= len;
662            }
663        }
664    }
665
666    /// Add a cylindrical shell or segment along `p0 -> p1` with radius `r0` to `r1`.
667    fn add_cylinder_segment(
668        &mut self,
669        p0: [f32; 3],
670        p1: [f32; 3],
671        r0: f32,
672        r1: f32,
673        radial_slices: usize,
674        col0: [u8; 4],
675        col1: [u8; 4],
676    ) {
677        let dx = p1[0] - p0[0];
678        let dy = p1[1] - p0[1];
679        let dz = p1[2] - p0[2];
680        let len = (dx * dx + dy * dy + dz * dz).sqrt().max(1e-5);
681        let axis = [dx / len, dy / len, dz / len];
682
683        let ref_v = if axis[0].abs() < 0.8 {
684            [1.0, 0.0, 0.0]
685        } else {
686            [0.0, 1.0, 0.0]
687        };
688        let dot_a = ref_v[0] * axis[0] + ref_v[1] * axis[1] + ref_v[2] * axis[2];
689        let mut u = [
690            ref_v[0] - dot_a * axis[0],
691            ref_v[1] - dot_a * axis[1],
692            ref_v[2] - dot_a * axis[2],
693        ];
694        let u_len = (u[0] * u[0] + u[1] * u[1] + u[2] * u[2]).sqrt().max(1e-5);
695        u = [u[0] / u_len, u[1] / u_len, u[2] / u_len];
696        let v = [
697            axis[1] * u[2] - axis[2] * u[1],
698            axis[2] * u[0] - axis[0] * u[2],
699            axis[0] * u[1] - axis[1] * u[0],
700        ];
701
702        let base_idx = self.positions.len() as u32;
703        let n = radial_slices.max(4);
704
705        for i in 0..=n {
706            let frac = (i as f32) / (n as f32);
707            let angle = frac * 2.0 * PI;
708            let cos_a = angle.cos();
709            let sin_a = angle.sin();
710            let norm = [
711                u[0] * cos_a + v[0] * sin_a,
712                u[1] * cos_a + v[1] * sin_a,
713                u[2] * cos_a + v[2] * sin_a,
714            ];
715
716            let v0 = [
717                p0[0] + norm[0] * r0,
718                p0[1] + norm[1] * r0,
719                p0[2] + norm[2] * r0,
720            ];
721            self.add_vertex(v0, norm, [frac, 0.0], col0);
722
723            let v1 = [
724                p1[0] + norm[0] * r1,
725                p1[1] + norm[1] * r1,
726                p1[2] + norm[2] * r1,
727            ];
728            self.add_vertex(v1, norm, [frac, 1.0], col1);
729        }
730
731        for i in 0..n {
732            let i0 = base_idx + (i * 2) as u32;
733            let i1 = i0 + 1;
734            let i2 = i0 + 3;
735            let i3 = i0 + 2;
736            self.add_quad(i0, i1, i2, i3);
737        }
738    }
739
740    /// Add a 3D box cell (e.g. brick epidermal or columnar palisade cell).
741    fn add_box_cell(&mut self, center: [f32; 3], half_extents: [f32; 3], col: [u8; 4]) {
742        let cx = center[0];
743        let cy = center[1];
744        let cz = center[2];
745        let hx = half_extents[0];
746        let hy = half_extents[1];
747        let hz = half_extents[2];
748
749        let faces = [
750            // +Y top
751            (
752                [0.0, 1.0, 0.0],
753                [
754                    [cx - hx, cy + hy, cz - hz],
755                    [cx - hx, cy + hy, cz + hz],
756                    [cx + hx, cy + hy, cz + hz],
757                    [cx + hx, cy + hy, cz - hz],
758                ],
759            ),
760            // -Y bottom
761            (
762                [0.0, -1.0, 0.0],
763                [
764                    [cx - hx, cy - hy, cz - hz],
765                    [cx + hx, cy - hy, cz - hz],
766                    [cx + hx, cy - hy, cz + hz],
767                    [cx - hx, cy - hy, cz + hz],
768                ],
769            ),
770            // +X right
771            (
772                [1.0, 0.0, 0.0],
773                [
774                    [cx + hx, cy - hy, cz - hz],
775                    [cx + hx, cy + hy, cz - hz],
776                    [cx + hx, cy + hy, cz + hz],
777                    [cx + hx, cy - hy, cz + hz],
778                ],
779            ),
780            // -X left
781            (
782                [-1.0, 0.0, 0.0],
783                [
784                    [cx - hx, cy - hy, cz - hz],
785                    [cx - hx, cy - hy, cz + hz],
786                    [cx - hx, cy + hy, cz + hz],
787                    [cx - hx, cy + hy, cz - hz],
788                ],
789            ),
790            // +Z front
791            (
792                [0.0, 0.0, 1.0],
793                [
794                    [cx - hx, cy - hy, cz + hz],
795                    [cx + hx, cy - hy, cz + hz],
796                    [cx + hx, cy + hy, cz + hz],
797                    [cx - hx, cy + hy, cz + hz],
798                ],
799            ),
800            // -Z back
801            (
802                [0.0, 0.0, -1.0],
803                [
804                    [cx - hx, cy - hy, cz - hz],
805                    [cx - hx, cy + hy, cz - hz],
806                    [cx + hx, cy + hy, cz - hz],
807                    [cx + hx, cy - hy, cz - hz],
808                ],
809            ),
810        ];
811
812        for (norm, corners) in faces {
813            let i0 = self.add_vertex(corners[0], norm, [0.0, 0.0], col);
814            let i1 = self.add_vertex(corners[1], norm, [0.0, 1.0], col);
815            let i2 = self.add_vertex(corners[2], norm, [1.0, 1.0], col);
816            let i3 = self.add_vertex(corners[3], norm, [1.0, 0.0], col);
817            self.add_quad(i0, i1, i2, i3);
818        }
819    }
820
821    /// Add an ellipsoid or sphere (e.g. oil gland, ovary ovule, bud).
822    fn add_ellipsoid(
823        &mut self,
824        center: [f32; 3],
825        radii: [f32; 3],
826        rings: usize,
827        sectors: usize,
828        col: [u8; 4],
829    ) {
830        let base_idx = self.positions.len() as u32;
831        let nr = rings.max(4);
832        let ns = sectors.max(6);
833
834        for r in 0..=nr {
835            let theta = (r as f32) * PI / (nr as f32);
836            let sin_t = theta.sin();
837            let cos_t = theta.cos();
838
839            for s in 0..=ns {
840                let phi = (s as f32) * 2.0 * PI / (ns as f32);
841                let sin_p = phi.sin();
842                let cos_p = phi.cos();
843
844                let norm = [sin_t * cos_p, cos_t, sin_t * sin_p];
845                let pos = [
846                    center[0] + norm[0] * radii[0],
847                    center[1] + norm[1] * radii[1],
848                    center[2] + norm[2] * radii[2],
849                ];
850                let u = (s as f32) / (ns as f32);
851                let v = (r as f32) / (nr as f32);
852                self.add_vertex(pos, norm, [u, v], col);
853            }
854        }
855
856        for r in 0..nr {
857            for s in 0..ns {
858                let i0 = base_idx + (r * (ns + 1) + s) as u32;
859                let i1 = i0 + (ns + 1) as u32;
860                let i2 = i1 + 1;
861                let i3 = i0 + 1;
862                self.add_quad(i0, i1, i2, i3);
863            }
864        }
865    }
866}
867
868fn attach_raw_section(
869    container: &[u8],
870    section_type: SectionType,
871    alignment_tier: AlignmentTier,
872    stride: u32,
873    element_count: u32,
874    payload: &[u8],
875) -> Result<Vec<u8>, String> {
876    let header = Container10dHeader::parse(container)
877        .map_err(|e| format!("10d header parse error: {e:?}"))?;
878    let descriptors = parse_section_table(container, &header)
879        .map_err(|e| format!("parse_section_table error: {e:?}"))?;
880    if descriptors.len() >= MAX_SECTION_COUNT as usize {
881        return Err("MAX_SECTION_COUNT reached".into());
882    }
883
884    let mut inputs = Vec::with_capacity(descriptors.len() + 1);
885    for descriptor in descriptors {
886        let start = descriptor.byte_offset as usize;
887        let end = start
888            .checked_add(descriptor.byte_length as usize)
889            .filter(|&end| end <= container.len())
890            .ok_or_else(|| {
891                format!(
892                    "SectionTableError::OutOfBounds offset={} length={}",
893                    descriptor.byte_offset, descriptor.byte_length
894                )
895            })?;
896        inputs.push(SectionInput {
897            section_type: descriptor
898                .typ()
899                .ok_or_else(|| format!("UndefinedSectionType: {}", descriptor.section_type))?,
900            alignment_tier: descriptor
901                .tier()
902                .ok_or_else(|| format!("UndefinedAlignmentTier: {}", descriptor.alignment_tier))?,
903            stride: descriptor.stride,
904            element_count: descriptor.element_count,
905            payload: &container[start..end],
906        });
907    }
908
909    inputs.push(SectionInput {
910        section_type,
911        alignment_tier,
912        stride,
913        element_count,
914        payload,
915    });
916
917    let needed = match encode_container(&header, &inputs, &mut []) {
918        Err(SectionTableError::OutputBufferTooSmall { needed, .. }) => needed,
919        Ok(size) => size,
920        Err(error) => return Err(format!("encode_container dry-run error: {error:?}")),
921    };
922    let mut output = vec![0u8; needed];
923    let written = encode_container(&header, &inputs, &mut output)
924        .map_err(|e| format!("encode_container error: {e:?}"))?;
925    output.truncate(written);
926    seal_whole_file_crc32c(&mut output);
927    Ok(output)
928}
929
930fn attach_procedural_synthesis_section(
931    container: &[u8],
932    header: &ProceduralSynthesisHeader,
933) -> Result<Vec<u8>, String> {
934    let mut buf = vec![0u8; PROCEDURAL_SYNTHESIS_HEADER_SIZE];
935    encode_procedural_synthesis_section(header, &mut buf)
936        .map_err(|e| format!("encode_procedural_synthesis_section: {e:?}"))?;
937    attach_raw_section(
938        container,
939        SectionType::ProceduralSynthesis,
940        AlignmentTier::CacheLine,
941        0,
942        0,
943        &buf,
944    )
945}
946
947fn attach_entity_ontology_section(
948    container: &[u8],
949    header: &EntityOntologyMiniHeader,
950    affordances: &[AffordanceBinaryRecord],
951    keyframes: &[DevelopmentalKeyframeRecord],
952) -> Result<Vec<u8>, String> {
953    let mut hdr = *header;
954    hdr.affordance_count = affordances.len() as u32;
955    hdr.reserved_u32 = keyframes.len() as u32;
956    let mut payload = Vec::with_capacity(
957        ENTITY_ONTOLOGY_MINI_HEADER_SIZE
958            + affordances.len() * AFFORDANCE_RECORD_SIZE
959            + keyframes.len() * DEVELOPMENTAL_KEYFRAME_RECORD_SIZE,
960    );
961    payload.extend_from_slice(bytemuck::bytes_of(&hdr));
962    for a in affordances {
963        payload.extend_from_slice(bytemuck::bytes_of(a));
964    }
965    for k in keyframes {
966        payload.extend_from_slice(bytemuck::bytes_of(k));
967    }
968    attach_raw_section(
969        container,
970        SectionType::EntityOntology,
971        AlignmentTier::CacheLine,
972        0,
973        0,
974        &payload,
975    )
976}
977
978fn attach_morph_section(
979    container: &[u8],
980    header: &MorphSectionHeader,
981    deltas: &[QuantizedMorphDelta],
982) -> Result<Vec<u8>, String> {
983    let needed = morph_section_encoded_len(deltas.len()).ok_or_else(|| {
984        format!(
985            "morph_section_encoded_len overflow: deltas={}",
986            deltas.len()
987        )
988    })?;
989    let mut buf = vec![0u8; needed];
990    encode_morph_section(header, deltas, &mut buf)
991        .map_err(|e| format!("encode_morph_section: {e:?}"))?;
992    attach_raw_section(
993        container,
994        SectionType::Reconstruction,
995        AlignmentTier::CacheLine,
996        0,
997        0,
998        &buf,
999    )
1000}
1001
1002/// Seal a botanical organ mesh into a fully verified, multi-section `.10d` living container.
1003fn seal_botanical_organ_10d(
1004    scale: BotanicalEducationScale,
1005    positions: &[[f32; 3]],
1006    normals: &[[f32; 3]],
1007    colors: &[[u8; 4]],
1008    uvs: &[[f32; 2]],
1009    indices: &[u32],
1010    slices: &[TissueSubmeshSlice],
1011    recipe_urn: &str,
1012    morph_deltas: Option<(&MorphSectionHeader, &[QuantizedMorphDelta])>,
1013) -> Result<Vec<u8>, String> {
1014    let mut min = [f32::INFINITY; 3];
1015    let mut max = [f32::NEG_INFINITY; 3];
1016    for p in positions {
1017        for k in 0..3 {
1018            min[k] = min[k].min(p[k]);
1019            max[k] = max[k].max(p[k]);
1020        }
1021    }
1022    let mut triangles = Vec::with_capacity(indices.len() / 3);
1023    for tri in indices.chunks_exact(3) {
1024        triangles.push([tri[0], tri[1], tri[2]]);
1025    }
1026    let mesh = Mesh {
1027        positions: positions.to_vec(),
1028        triangles,
1029        min,
1030        max,
1031    };
1032
1033    let colors_f32: Vec<[f32; 4]> = colors
1034        .iter()
1035        .map(|c| {
1036            [
1037                (c[0] as f32) / 255.0,
1038                (c[1] as f32) / 255.0,
1039                (c[2] as f32) / 255.0,
1040                (c[3] as f32) / 255.0,
1041            ]
1042        })
1043        .collect();
1044
1045    let mut hasher = Sha256::new();
1046    hasher.update(recipe_urn.as_bytes());
1047    let _recipe_digest: [u8; 32] = hasher.finalize().into();
1048
1049    let provenance = ProvenanceSidecar::new(
1050        recipe_urn.as_bytes().to_vec(),
1051        "application/vnd.ecopunk.botanical-organ;version=1",
1052        "Apache-2.0",
1053    );
1054
1055    let mut bytes = compile_mesh_to_10d_with_extras_and_frames(
1056        &mesh,
1057        &[],
1058        Some(&provenance),
1059        Compile10dExtras::default(),
1060        Some(&colors_f32),
1061        Some(normals),
1062        None,
1063    )
1064    .map_err(|e| format!("compile_mesh_to_10d_with_extras_and_frames error: {e}"))?;
1065
1066    // 1. Build Materials and Submesh Ranges from TissueSubmeshSlices
1067    let mut materials = Vec::new();
1068    let mut ranges = Vec::new();
1069
1070    for (idx, slice) in slices.iter().enumerate() {
1071        if slice.index_count == 0 {
1072            continue;
1073        }
1074        let (roughness, metallic) = slice.layer.default_pbr_material();
1075        let base_col = slice.layer.default_color_rgba();
1076        let mat_id = q_hash(&format!(
1077            "urn:qualia:material:ecopunk:botanical:{:?}:{}",
1078            scale, idx
1079        ));
1080
1081        let mut mat = MaterialRecord::legacy_default();
1082        mat.id = mat_id;
1083        mat.shading_model = ShadingModel::MetallicRoughness;
1084        mat.opacity_mode = OpacityMode::Opaque;
1085        mat.double_sided = matches!(
1086            slice.layer,
1087            HistologicalTissueLayer::WaxyCuticle
1088                | HistologicalTissueLayer::StaminalRingFilaments
1089                | HistologicalTissueLayer::WoodyPericarpAndDehiscingValves
1090        );
1091        mat.casts_shadow = true;
1092        mat.receives_shadow = true;
1093        mat.pickable = true;
1094        mat.multiply_vertex_color = true;
1095        mat.wind_animated = matches!(
1096            slice.layer,
1097            HistologicalTissueLayer::WaxyCuticle | HistologicalTissueLayer::StaminalRingFilaments
1098        );
1099        mat.base_color = base_col;
1100        mat.roughness = roughness;
1101        mat.metallic = metallic;
1102        mat.specular = 0.5;
1103
1104        tissue_materials::append_tissue_ranges(
1105            mat, slice, indices, colors, &mut materials, &mut ranges,
1106        )?;
1107    }
1108
1109    if !materials.is_empty() {
1110        materials.sort_by_key(|m| m.id);
1111        bytes = attach_material_section(&bytes, &materials, &ranges, indices.len() as u32)
1112            .map_err(|e| format!("attach_material_section error: {e:?}"))?;
1113    }
1114
1115    // 2. Texture coordinates
1116    bytes = attach_texture_coordinate_section(&bytes, uvs)
1117        .map_err(|e| format!("attach_texture_coordinate_section error: {e:?}"))?;
1118
1119    // 3. Procedural Synthesis Section (`MAGIC_PROC`, SectionType 18)
1120    let proc_header = ProceduralSynthesisHeader {
1121        magic: MAGIC_PROC,
1122        version: PROCEDURAL_SYNTHESIS_SECTION_VERSION,
1123        flags: (FLAG_CELLULAR_VORONOI
1124            | FLAG_IMPLICIT_FILLET
1125            | FLAG_ALLOMETRIC_GROWTH
1126            | FLAG_PGA_MOTOR_DYNAMICS) as u16,
1127        seed: 0x9E37_79B9_7F4A_7C15,
1128        voronoi_frequency: 24.0,
1129        voronoi_jitter: 0.88,
1130        fillet_blend_radius: 0.15,
1131        fillet_threshold: 0.04,
1132        allometry_exponent_k: 0.67,
1133        allometry_base_b: 1.15,
1134        spiral_growth_rate_k: 0.22,
1135        spiral_initial_radius_a: 0.05,
1136        motor_frequency_hz: 1.75,
1137        motor_damping_ratio: 0.09,
1138        critical_stress_threshold: 28.0,
1139        reserved_f32: 0.0,
1140    };
1141    bytes = attach_procedural_synthesis_section(&bytes, &proc_header)?;
1142
1143    // 4. Entity Ontology Section (`MAGIC_EONT`, SectionType 17)
1144    let onto_header = EntityOntologyMiniHeader {
1145        magic: MAGIC_EONT,
1146        version: ENTITY_ONTOLOGY_SECTION_VERSION,
1147        stage: 2, // Adult
1148        reserved_u8: 0,
1149        entity_did_hash: 0xD1D0_A057_FA11_9921,
1150        taxon_iri_hash: 0x7A00_ECA1_CA7A_1001,
1151        energy_permill: 950,
1152        damage_permill: 20,
1153        hydration_permill: 880,
1154        wear_permill: 95,
1155        affordance_count: 3,
1156        reserved_u32: 4,
1157    };
1158    let affordances = [
1159        AffordanceBinaryRecord {
1160            action_id: 0x0001,
1161            required_capability_hash: 0xCA00_1001,
1162            emitted_topic_hash: 0x7000_1001,
1163            category: 1, // Pollination
1164            min_observer_status: 0,
1165            min_energy_permill: 100,
1166            max_damage_permill: 800,
1167            min_hydration_permill: 150,
1168            max_wear_permill: 900,
1169            energy_delta: 40,
1170            damage_delta: 0,
1171            hydration_delta: 25,
1172            wear_delta: 5,
1173            reserved_u16: 0,
1174            animation_clip_id: 1,
1175        },
1176        AffordanceBinaryRecord {
1177            action_id: 0x0002,
1178            required_capability_hash: 0xCA00_2002,
1179            emitted_topic_hash: 0x7000_2002,
1180            category: 2, // Kino Harvesting
1181            min_observer_status: 1,
1182            min_energy_permill: 200,
1183            max_damage_permill: 700,
1184            min_hydration_permill: 200,
1185            max_wear_permill: 850,
1186            energy_delta: -15,
1187            damage_delta: 20,
1188            hydration_delta: -20,
1189            wear_delta: 30,
1190            reserved_u16: 0,
1191            animation_clip_id: 2,
1192        },
1193        AffordanceBinaryRecord {
1194            action_id: 0x0003,
1195            required_capability_hash: 0xCA00_3003,
1196            emitted_topic_hash: 0x7000_3003,
1197            category: 3, // Hollow Nesting
1198            min_observer_status: 0,
1199            min_energy_permill: 50,
1200            max_damage_permill: 950,
1201            min_hydration_permill: 50,
1202            max_wear_permill: 980,
1203            energy_delta: 60,
1204            damage_delta: -5,
1205            hydration_delta: 35,
1206            wear_delta: -5,
1207            reserved_u16: 0,
1208            animation_clip_id: 3,
1209        },
1210    ];
1211    let keyframes = [
1212        DevelopmentalKeyframeRecord {
1213            age_days: 30.0,
1214            stage: 0,
1215            reserved_u8: 0,
1216            reserved_u16: 0,
1217            allometric_crown_scale: 0.12,
1218            allometric_trunk_scale: 0.08,
1219            lai_multiplier: 0.15,
1220            reserved_u32: 0,
1221            mesh_asset_hash: 0,
1222        },
1223        DevelopmentalKeyframeRecord {
1224            age_days: 365.0,
1225            stage: 1,
1226            reserved_u8: 0,
1227            reserved_u16: 0,
1228            allometric_crown_scale: 0.45,
1229            allometric_trunk_scale: 0.38,
1230            lai_multiplier: 0.52,
1231            reserved_u32: 0,
1232            mesh_asset_hash: 0,
1233        },
1234        DevelopmentalKeyframeRecord {
1235            age_days: 3650.0,
1236            stage: 2,
1237            reserved_u8: 0,
1238            reserved_u16: 0,
1239            allometric_crown_scale: 1.0,
1240            allometric_trunk_scale: 1.0,
1241            lai_multiplier: 1.0,
1242            reserved_u32: 0,
1243            mesh_asset_hash: 0,
1244        },
1245        DevelopmentalKeyframeRecord {
1246            age_days: 36500.0,
1247            stage: 3,
1248            reserved_u8: 0,
1249            reserved_u16: 0,
1250            allometric_crown_scale: 1.28,
1251            allometric_trunk_scale: 1.45,
1252            lai_multiplier: 0.88,
1253            reserved_u32: 0,
1254            mesh_asset_hash: 0,
1255        },
1256    ];
1257    bytes = attach_entity_ontology_section(&bytes, &onto_header, &affordances, &keyframes)?;
1258
1259    // 5. Morph Target Section (`MAGIC_MRP1`, SectionType::SkeletalAnimation)
1260    if let Some((morph_hdr, deltas)) = morph_deltas {
1261        if !deltas.is_empty() {
1262            bytes = attach_morph_section(&bytes, morph_hdr, deltas)?;
1263        }
1264    } else if !positions.is_empty() {
1265        // Fallback subtle wind/ontogenetic morph target
1266        let n_verts = positions.len();
1267        let mut deltas = Vec::new();
1268        let step = (n_verts / 32).max(1);
1269        for vi in (0..n_verts).step_by(step) {
1270            let p = positions[vi];
1271            let n = normals.get(vi).copied().unwrap_or([0.0, 1.0, 0.0]);
1272            let d = quantize_morph_delta(
1273                [p[0] * 0.02, p[1] * 0.01, p[2] * 0.02],
1274                [n[0] * 0.05, n[1] * 0.05, n[2] * 0.05],
1275                [0.0, 0.0, 0.0],
1276                0.2,
1277                0,
1278                vi as u32,
1279            );
1280            deltas.push(d);
1281        }
1282        let morph_hdr = MorphSectionHeader {
1283            magic: MAGIC_MRP1,
1284            version: MORPH_SECTION_VERSION,
1285            target_count: 1,
1286            vertex_count: n_verts as u32,
1287            flags: FLAG_MORPH_SPARSE | FLAG_MORPH_HAS_NORMALS | FLAG_MORPH_ONTOGENETIC_BIND,
1288            max_displacement: 0.2,
1289            ontogenetic_bind_mask: 0b0001,
1290            reserved: [0u8; 8],
1291        };
1292        bytes = attach_morph_section(&bytes, &morph_hdr, &deltas)?;
1293    }
1294
1295    Ok(bytes)
1296}
1297
1298// ============================================================================
1299// 4. Scale 1: Whole-Organism Architecture & Subterranean Root System
1300// ============================================================================
1301
1302/// Synthesize Scale 1 Whole Organism (`10 m – 40 m`) with 5-order Leonardo da Vinci crown,
1303/// lignotuber swelling with dormant epicormic buds, primary taproot, lateral buttress flares,
1304/// and pendulous foliage clusters. ($\ge 2,500$ vertices).
1305pub fn build_scale1_whole_organism_10d(
1306    species_id: &str,
1307    stage: DevelopmentalStage,
1308) -> Result<CompiledBotanicalOrgan10d, String> {
1309    let mut b = OrganMeshBuilder::new();
1310
1311    let (height_m, bole_r, crown_r, branch_orders) = match stage {
1312        DevelopmentalStage::Seedling => (0.45_f32, 0.008_f32, 0.25_f32, 2usize),
1313        DevelopmentalStage::Sapling => (3.8_f32, 0.045_f32, 1.6_f32, 3usize),
1314        DevelopmentalStage::Mature => (16.5_f32, 0.32_f32, 6.5_f32, 5usize),
1315        DevelopmentalStage::AncientHollowBearing => (18.0_f32, 0.48_f32, 7.8_f32, 5usize),
1316    };
1317
1318    // Leonardo da Vinci / Shinozaki Pipe Model calculation for the 5-order branching tree
1319    let tree_parents = [ROOT_PARENT, 0, 1, 2, 2, 3, 3, 4, 4];
1320    let mut scratch = vec![0u32; tree_parents.len()];
1321    let mut calculated_radii = vec![0.0f64; tree_parents.len()];
1322    let _ = pipe_model_radii(
1323        &tree_parents,
1324        bole_r as f64 * 0.12,
1325        PIPE_EXPONENT_EUCALYPTUS,
1326        &mut scratch,
1327        &mut calculated_radii,
1328    );
1329    let pipe_scaffold_base = calculated_radii
1330        .get(2)
1331        .copied()
1332        .filter(|r| r.is_finite() && *r > 0.0)
1333        .unwrap_or((bole_r * 0.48) as f64) as f32;
1334
1335    // Biophysical metamer plant graph coupling for hydraulic and thermal phenology
1336    let mut metamer_graph = PlantArchitecture::new(ThermalPhenology::default());
1337    metamer_graph.update_thermal_time(28.0, 14.0, 120.0);
1338    let _root_organ = MetamerOrgan::RootTip;
1339    let _metamer_sample = Metamer::default();
1340
1341    // ------------------------------------------------------------------------
1342    // Layer 1: Subterranean Root Architecture (`PhellogenCorkCambium`)
1343    // ------------------------------------------------------------------------
1344    b.begin_tissue_layer(HistologicalTissueLayer::PhellogenCorkCambium, 0);
1345
1346    // 1A. Lignotuber: Basal root collar swelling ($y \in [-0.8, 0.2] \times \text{scale}$)
1347    let ligno_r = bole_r * 1.85;
1348    let ligno_center = [0.0, -0.35 * bole_r, 0.0];
1349    b.add_ellipsoid(
1350        ligno_center,
1351        [ligno_r, bole_r * 1.2, ligno_r],
1352        8,
1353        16,
1354        [148, 163, 112, 255],
1355    );
1356
1357    // 1B. Dormant Epicormic Meristem Buds: 16 small hemispherical nodules on the lignotuber
1358    let bud_r = bole_r * 0.18;
1359    for i in 0..16 {
1360        let phi = (i as f32) * (2.0 * PI / 16.0);
1361        let bx = ligno_r * 0.95 * phi.cos();
1362        let bz = ligno_r * 0.95 * phi.sin();
1363        let by = ligno_center[1] + (i as f32 % 3.0 - 1.0) * bud_r * 0.8;
1364        b.add_ellipsoid(
1365            [bx, by, bz],
1366            [bud_r, bud_r, bud_r],
1367            4,
1368            6,
1369            [175, 195, 125, 255],
1370        );
1371    }
1372
1373    // 1C. Primary Taproot: Vertical anchor cylinder descending into the subsoil
1374    let tap_depth = height_m * 0.25;
1375    let tap_steps = 6;
1376    for s in 0..tap_steps {
1377        let y0 = -((s as f32) / (tap_steps as f32)) * tap_depth;
1378        let y1 = -(((s + 1) as f32) / (tap_steps as f32)) * tap_depth;
1379        let r0 = root_flare_radius(bole_r as f64 * 0.7, y0 as f64, 0.8) as f32;
1380        let r1 = root_flare_radius(bole_r as f64 * 0.7, y1 as f64, 0.8) as f32;
1381        b.add_cylinder_segment(
1382            [0.0, y0, 0.0],
1383            [0.0, y1, 0.0],
1384            r0,
1385            r1.max(bole_r * 0.15),
1386            8,
1387            [120, 105, 82, 255],
1388            [105, 92, 70, 255],
1389        );
1390    }
1391
1392    // 1D. Root-Collar Buttress Flares, Lateral Anchor Roots & Fine Feeder Rootlets
1393    let num_laterals = 6;
1394    for i in 0..num_laterals {
1395        let angle = (i as f32) * (2.0 * PI / (num_laterals as f32));
1396        let cos_a = angle.cos();
1397        let sin_a = angle.sin();
1398        let lat_len = crown_r * 0.48;
1399
1400        // Above-ground fluted buttress collar spur flaring from lower bole into root crown
1401        let b_top = [cos_a * bole_r * 0.65, bole_r * 2.2, sin_a * bole_r * 0.65];
1402        let p0 = [cos_a * bole_r * 1.15, -bole_r * 0.08, sin_a * bole_r * 1.15];
1403        let p1 = [
1404            cos_a * lat_len * 0.52,
1405            -bole_r * 0.85,
1406            sin_a * lat_len * 0.52,
1407        ];
1408        let p2 = [cos_a * lat_len, -bole_r * 1.75, sin_a * lat_len];
1409
1410        let r_base = bole_r * 0.58;
1411        b.add_cylinder_segment(
1412            b_top,
1413            p0,
1414            r_base * 0.52,
1415            r_base * 1.08,
1416            6,
1417            [142, 126, 98, 255],
1418            [130, 115, 88, 255],
1419        );
1420        b.add_cylinder_segment(
1421            p0,
1422            p1,
1423            r_base,
1424            r_base * 0.62,
1425            6,
1426            [130, 115, 88, 255],
1427            [115, 100, 75, 255],
1428        );
1429        b.add_cylinder_segment(
1430            p1,
1431            p2,
1432            r_base * 0.62,
1433            r_base * 0.24,
1434            6,
1435            [115, 100, 75, 255],
1436            [95, 80, 60, 255],
1437        );
1438
1439        // Bifurcating secondary & tertiary feeder rootlets
1440        for side in [-1.0_f32, 1.0_f32] {
1441            let p_sub = [
1442                p1[0] + (cos_a * 0.4 + side * sin_a * 0.6) * lat_len * 0.28,
1443                p1[1] - bole_r * 0.58,
1444                p1[2] + (sin_a * 0.4 - side * cos_a * 0.6) * lat_len * 0.28,
1445            ];
1446            b.add_cylinder_segment(
1447                p1,
1448                p_sub,
1449                r_base * 0.32,
1450                r_base * 0.09,
1451                4,
1452                [110, 95, 70, 255],
1453                [90, 75, 55, 255],
1454            );
1455        }
1456    }
1457    b.end_tissue_layer();
1458
1459    // ------------------------------------------------------------------------
1460    // Layer 2: Heartwood & Central Pith (`HeartwoodAndPith`)
1461    // ------------------------------------------------------------------------
1462    b.begin_tissue_layer(HistologicalTissueLayer::HeartwoodAndPith, 1);
1463    let trunk_h = height_m * 0.46;
1464    let pith_r = bole_r * 0.24;
1465    b.add_cylinder_segment(
1466        [0.0, 0.0, 0.0],
1467        [0.0, trunk_h, 0.0],
1468        pith_r,
1469        pith_r * 0.75,
1470        8,
1471        [107, 56, 41, 255],
1472        [125, 68, 50, 255],
1473    );
1474
1475    // For ancient stage: Add a hollow trunk split cavity exposing decayed duramen
1476    if stage == DevelopmentalStage::AncientHollowBearing {
1477        let cav_h = trunk_h * 0.4;
1478        let cav_r = bole_r * 0.65;
1479        b.add_cylinder_segment(
1480            [cav_r * 0.3, trunk_h * 0.15, 0.0],
1481            [cav_r * 0.2, trunk_h * 0.15 + cav_h, 0.0],
1482            cav_r * 0.7,
1483            cav_r * 0.5,
1484            8,
1485            [75, 38, 28, 255],
1486            [60, 30, 22, 255],
1487        );
1488    }
1489    b.end_tissue_layer();
1490
1491    // ------------------------------------------------------------------------
1492    // Layer 3: Active Sapwood Scaffold Limbs (`SapwoodSecondaryXylem`)
1493    // ------------------------------------------------------------------------
1494    b.begin_tissue_layer(HistologicalTissueLayer::SapwoodSecondaryXylem, 2);
1495    // Primary scaffold limbs branching off the bole with curved mid-segments
1496    let num_scaffolds = if branch_orders >= 4 { 6 } else { 4 };
1497    let mut scaffold_tips = Vec::new();
1498
1499    for i in 0..num_scaffolds {
1500        let frac = (i as f32) / (num_scaffolds as f32);
1501        let azimuth = frac * 2.0 * PI + 0.32;
1502        let h_base = trunk_h * (0.58 + frac * 0.38);
1503        let limb_len = crown_r * (0.62 + 0.24 * ((i as f32 * 1.7).sin().abs()));
1504        let elevation = 0.42 + 0.14 * (i as f32 % 3.0);
1505
1506        let p_start = [
1507            0.04 * bole_r * (h_base * 0.8).sin(),
1508            h_base,
1509            0.04 * bole_r * (h_base * 0.8).cos(),
1510        ];
1511        let p_mid = [
1512            p_start[0] + azimuth.cos() * limb_len * 0.52 * elevation.cos(),
1513            h_base + limb_len * 0.56 * elevation.sin(),
1514            p_start[2] + azimuth.sin() * limb_len * 0.52 * elevation.cos(),
1515        ];
1516        let p_end = [
1517            p_start[0] + azimuth.cos() * limb_len * elevation.cos(),
1518            h_base + limb_len * elevation.sin(),
1519            p_start[2] + azimuth.sin() * limb_len * elevation.cos(),
1520        ];
1521
1522        let pipe_tip = calculated_radii
1523            .get(3 + (i % 2))
1524            .copied()
1525            .filter(|r| r.is_finite() && *r > 0.0)
1526            .unwrap_or((bole_r * 0.22) as f64) as f32;
1527        let r_start = pipe_scaffold_base.max(bole_r * 0.26);
1528        let r_mid = (r_start * 0.74).max(bole_r * 0.17);
1529        let r_end = pipe_tip.max(bole_r * 0.12).min(r_mid * 0.82);
1530
1531        // Collar flare at bole junction
1532        b.add_cylinder_segment(
1533            p_start,
1534            p_mid,
1535            r_start * 1.18,
1536            r_mid,
1537            8,
1538            [219, 201, 171, 255],
1539            [212, 194, 164, 255],
1540        );
1541        b.add_cylinder_segment(
1542            p_mid,
1543            p_end,
1544            r_mid,
1545            r_end,
1546            8,
1547            [212, 194, 164, 255],
1548            [202, 184, 152, 255],
1549        );
1550        scaffold_tips.push((p_end, r_end, azimuth));
1551    }
1552    b.end_tissue_layer();
1553
1554    // ------------------------------------------------------------------------
1555    // Layer 4: Outer Rhytidome (Chalk-White Bark Bole, Peeling Ribbons & Branches)
1556    // ------------------------------------------------------------------------
1557    b.begin_tissue_layer(HistologicalTissueLayer::OuterRhytidome, 3);
1558    // Main bole cylinder with dark tessellated basal stocking transitioning to chalk-white upper bark
1559    let bole_steps = 10;
1560    for s in 0..bole_steps {
1561        let f0 = s as f32 / bole_steps as f32;
1562        let f1 = (s + 1) as f32 / bole_steps as f32;
1563        let y0 = f0 * trunk_h;
1564        let y1 = f1 * trunk_h;
1565        let flare0 = if f0 < 0.22 {
1566            1.0 + 0.35 * (1.0 - f0 / 0.22).powi(2)
1567        } else {
1568            1.0
1569        };
1570        let flare1 = if f1 < 0.22 {
1571            1.0 + 0.35 * (1.0 - f1 / 0.22).powi(2)
1572        } else {
1573            1.0
1574        };
1575        let r0 = bole_r * (1.0 - 0.24 * f0) * flare0;
1576        let r1 = bole_r * (1.0 - 0.24 * f1) * flare1;
1577        let col0 = if f0 < 0.18 {
1578            [118, 98, 82, 255]
1579        } else {
1580            [237, 235, 224, 255]
1581        };
1582        let col1 = if f1 < 0.18 {
1583            [148, 128, 108, 255]
1584        } else {
1585            [244, 242, 234, 255]
1586        };
1587        b.add_cylinder_segment(
1588            [0.04 * bole_r * (f0 * PI).sin(), y0, 0.0],
1589            [0.04 * bole_r * (f1 * PI).sin(), y1, 0.0],
1590            r0,
1591            r1,
1592            12,
1593            col0,
1594            col1,
1595        );
1596    }
1597
1598    // Peeling bark ribbons curling off the lower/mid bole stocking transition
1599    for rib in 0..6 {
1600        let ra = (rib as f32) * (2.0 * PI / 6.0) + 0.4;
1601        let ry = trunk_h * (0.18 + 0.09 * (rib as f32));
1602        let rr = bole_r * (1.0 - 0.18 * (ry / trunk_h));
1603        let p_attach = [ra.cos() * rr, ry, ra.sin() * rr];
1604        let p_curl = [
1605            ra.cos() * (rr + bole_r * 0.22),
1606            ry - bole_r * 0.55,
1607            ra.sin() * (rr + bole_r * 0.22),
1608        ];
1609        let p_tip = [
1610            ra.cos() * (rr + bole_r * 0.36),
1611            ry - bole_r * 1.05,
1612            ra.sin() * (rr + bole_r * 0.36),
1613        ];
1614        b.add_cylinder_segment(
1615            p_attach,
1616            p_curl,
1617            bole_r * 0.045,
1618            bole_r * 0.032,
1619            4,
1620            [218, 204, 184, 255],
1621            [178, 146, 118, 255],
1622        );
1623        b.add_cylinder_segment(
1624            p_curl,
1625            p_tip,
1626            bole_r * 0.032,
1627            bole_r * 0.012,
1628            4,
1629            [178, 146, 118, 255],
1630            [145, 112, 86, 255],
1631        );
1632    }
1633
1634    // Secondary, tertiary branchlets and pendulous quaternary twigs extending from scaffold limbs
1635    let mut terminal_twigs = Vec::new();
1636    for &(scaf_pos, scaf_r, scaf_azim) in &scaffold_tips {
1637        let num_secondary = 3;
1638        for t in 0..num_secondary {
1639            let t_frac = t as f32 - 1.0;
1640            let spread_a = scaf_azim + t_frac * 0.58;
1641            let t_len = crown_r * 0.42;
1642
1643            let p_sec = [
1644                scaf_pos[0] + spread_a.cos() * t_len * 0.82,
1645                scaf_pos[1] + t_len * 0.34 - t_frac.abs() * 0.16,
1646                scaf_pos[2] + spread_a.sin() * t_len * 0.82,
1647            ];
1648            b.add_cylinder_segment(
1649                scaf_pos,
1650                p_sec,
1651                scaf_r * 1.08,
1652                scaf_r * 0.44,
1653                6,
1654                [232, 230, 220, 255],
1655                [220, 218, 206, 255],
1656            );
1657
1658            // Tertiary and pendulous quaternary twigs
1659            for q in 0..3 {
1660                let q_azim = spread_a + (q as f32 - 1.0) * 0.58;
1661                let q_len = crown_r * 0.24;
1662                let p_tert = [
1663                    p_sec[0] + q_azim.cos() * q_len * 0.65,
1664                    p_sec[1] + q_len * 0.12,
1665                    p_sec[2] + q_azim.sin() * q_len * 0.65,
1666                ];
1667                let p_twig = [
1668                    p_tert[0] + q_azim.cos() * q_len * 0.55,
1669                    p_tert[1] - 0.22 * q_len, // Pendulous sclerophyllous twig droop
1670                    p_tert[2] + q_azim.sin() * q_len * 0.55,
1671                ];
1672                b.add_cylinder_segment(
1673                    p_sec,
1674                    p_tert,
1675                    scaf_r * 0.40,
1676                    scaf_r * 0.20,
1677                    5,
1678                    [210, 205, 192, 255],
1679                    [184, 176, 158, 255],
1680                );
1681                b.add_cylinder_segment(
1682                    p_tert,
1683                    p_twig,
1684                    scaf_r * 0.20,
1685                    scaf_r * 0.08,
1686                    4,
1687                    [184, 176, 158, 255],
1688                    [156, 134, 108, 255],
1689                );
1690                terminal_twigs.push((p_tert, p_twig, q_azim));
1691            }
1692        }
1693    }
1694    b.end_tissue_layer();
1695
1696    // ------------------------------------------------------------------------
1697    // Layer 5: Woody Gumnut Capsule Clusters on Outer Canopy Shoots
1698    // ------------------------------------------------------------------------
1699    b.begin_tissue_layer(HistologicalTissueLayer::WoodyPericarpAndDehiscingValves, 5);
1700    let nut_r = (height_m * 0.0028).clamp(0.004, 0.024);
1701    for (idx, &(p_node, _p_twig, azim)) in terminal_twigs.iter().enumerate() {
1702        if idx % 2 == 0 {
1703            for k in 0..3 {
1704                let ka = azim + (k as f32 - 1.0) * 0.85;
1705                let p_nut = [
1706                    p_node[0] + ka.cos() * nut_r * 2.2,
1707                    p_node[1] - nut_r * 1.8,
1708                    p_node[2] + ka.sin() * nut_r * 2.2,
1709                ];
1710                b.add_cylinder_segment(
1711                    p_node,
1712                    p_nut,
1713                    nut_r * 0.45,
1714                    nut_r,
1715                    5,
1716                    [117, 97, 76, 255],
1717                    [96, 78, 60, 255],
1718                );
1719            }
1720        }
1721    }
1722    b.end_tissue_layer();
1723
1724    // ------------------------------------------------------------------------
1725    // Layer 6: Dense Pendulous Falcate Leaf Sprays (`WaxyCuticle`)
1726    // ------------------------------------------------------------------------
1727    b.begin_tissue_layer(HistologicalTissueLayer::WaxyCuticle, 4);
1728    // At each terminal twig, hang dense phyllotactic sprays of curved falcate leaves
1729    let leaf_len = (height_m * 0.028).clamp(0.08, 0.26);
1730    let leaf_w = leaf_len * 0.24;
1731
1732    for (t_idx, &(p_tert, twig_pos, twig_azim)) in terminal_twigs.iter().enumerate() {
1733        let num_leaves = 7;
1734        for l in 0..num_leaves {
1735            let l_frac = l as f32 / num_leaves as f32;
1736            let l_angle = twig_azim + (l as f32) * GOLDEN_ANGLE;
1737            let stem_mix = 0.25 + 0.75 * l_frac;
1738            let attach = [
1739                p_tert[0] * (1.0 - stem_mix) + twig_pos[0] * stem_mix,
1740                p_tert[1] * (1.0 - stem_mix) + twig_pos[1] * stem_mix,
1741                p_tert[2] * (1.0 - stem_mix) + twig_pos[2] * stem_mix,
1742            ];
1743            let lx = attach[0] + l_angle.cos() * leaf_w * 0.95;
1744            let lz = attach[2] + l_angle.sin() * leaf_w * 0.95;
1745            let ly_top = attach[1];
1746
1747            // Vertically pendulous, falcate sickle lamina with raised midrib and copper-flush young tips
1748            let segs = 4;
1749            let vertex_start = b.positions.len();
1750            let index_start = b.indices.len();
1751            let mut previous = [0u32; 3];
1752            let is_young_tip = l + 1 == num_leaves && (t_idx % 3 == 0);
1753
1754            for seg in 0..=segs {
1755                let s_frac = seg as f32 / segs as f32;
1756                let sin_s = (s_frac * PI).sin();
1757                let cur_y = ly_top - s_frac * leaf_len;
1758                // Falcate sickle curvature along x/z
1759                let curve_offset = sin_s * leaf_w * 0.72 * (0.4 + 0.6 * s_frac);
1760                let cur_x = lx + l_angle.cos() * curve_offset;
1761                let cur_z = lz + l_angle.sin() * curve_offset;
1762                let w = sin_s.max(0.06).powf(0.82) * (1.0 - 0.16 * s_frac) * leaf_w * 0.55;
1763                let ridge = leaf_w * 0.14 * sin_s;
1764
1765                let perp_x = -l_angle.sin() * w;
1766                let perp_z = l_angle.cos() * w;
1767
1768                let (col_margin, col_mid) = if is_young_tip {
1769                    ([138, 86, 58, 255], [162, 108, 72, 255])
1770                } else {
1771                    ([78, 114, 84, 255], [112, 146, 104, 255])
1772                };
1773
1774                let v_left = b.add_vertex(
1775                    [cur_x - perp_x, cur_y, cur_z - perp_z],
1776                    [l_angle.cos(), 0.0, l_angle.sin()],
1777                    [0.0, s_frac],
1778                    col_margin,
1779                );
1780                let v_mid = b.add_vertex(
1781                    [
1782                        cur_x + l_angle.cos() * ridge,
1783                        cur_y,
1784                        cur_z + l_angle.sin() * ridge,
1785                    ],
1786                    [l_angle.cos(), 0.0, l_angle.sin()],
1787                    [0.5, s_frac],
1788                    col_mid,
1789                );
1790                let v_right = b.add_vertex(
1791                    [cur_x + perp_x, cur_y, cur_z + perp_z],
1792                    [l_angle.cos(), 0.0, l_angle.sin()],
1793                    [1.0, s_frac],
1794                    col_margin,
1795                );
1796
1797                if seg > 0 {
1798                    b.add_quad(previous[0], v_left, v_mid, previous[1]);
1799                    b.add_quad(previous[1], v_mid, v_right, previous[2]);
1800                }
1801                previous = [v_left, v_mid, v_right];
1802            }
1803            b.recompute_normals_since(vertex_start, index_start);
1804        }
1805    }
1806    b.end_tissue_layer();
1807
1808    let recipe_urn = format!("urn:qualia:botanical:scale1:{species_id}:{:?}", stage);
1809    let container_bytes = seal_botanical_organ_10d(
1810        BotanicalEducationScale::Scale1WholeOrganismAndRoots,
1811        &b.positions,
1812        &b.normals,
1813        &b.colors,
1814        &b.uvs,
1815        &b.indices,
1816        &b.slices,
1817        &recipe_urn,
1818        None,
1819    )?;
1820
1821    let organ = CompiledBotanicalOrgan10d {
1822        scale: BotanicalEducationScale::Scale1WholeOrganismAndRoots,
1823        vertices: b.positions,
1824        normals: b.normals,
1825        uvs: b.uvs,
1826        colors: b.colors,
1827        material_indices: b.material_indices,
1828        indices: b.indices,
1829        tissue_slices: b.slices,
1830        container_bytes,
1831    };
1832
1833    organ.verify_all()?;
1834    Ok(organ)
1835}
1836
1837// ============================================================================
1838// 5. Scale 2: Branch Phyllotaxis & Stem/Bark Histology Wedge
1839// ============================================================================
1840
1841/// Synthesize Scale 2 Stem Anatomy Wedge (`50 mm – 2 m`) with golden-angle phyllotaxis
1842/// nodes and 6 concentric peelable tissue cylinders displaced radially/axially by `explode_factor_01`.
1843/// ($\ge 1,800$ vertices).
1844pub fn build_scale2_stem_bark_wedge_10d(
1845    species_id: &str,
1846    explode_factor_01: f32,
1847) -> Result<CompiledBotanicalOrgan10d, String> {
1848    let mut b = OrganMeshBuilder::new();
1849
1850    let wedge_span_rad = 1.5 * PI; // 270 degrees
1851    let stem_height = 0.38_f32;
1852    let n_radial = 28usize;
1853    let n_vertical = 8usize;
1854
1855    // Define the 6 concentric histological layers with exact radii bounds (meters)
1856    let layers = [
1857        (
1858            HistologicalTissueLayer::HeartwoodAndPith,
1859            0.0_f32,
1860            0.034_f32,
1861            [107, 56, 41, 255], // Deep reddish duramen
1862            0u8,
1863        ),
1864        (
1865            HistologicalTissueLayer::SapwoodSecondaryXylem,
1866            0.034_f32,
1867            0.074_f32,
1868            [219, 201, 171, 255], // Cream secondary xylem
1869            1u8,
1870        ),
1871        (
1872            HistologicalTissueLayer::VascularCambium,
1873            0.074_f32,
1874            0.078_f32,
1875            [199, 224, 133, 255], // Lime dividing ring
1876            2u8,
1877        ),
1878        (
1879            HistologicalTissueLayer::SecondaryPhloemAndKinoDucts,
1880            0.078_f32,
1881            0.092_f32,
1882            [184, 112, 71, 255], // Warm amber phloem + kino
1883            3u8,
1884        ),
1885        (
1886            HistologicalTissueLayer::PhellogenCorkCambium,
1887            0.092_f32,
1888            0.096_f32,
1889            [148, 163, 112, 255], // Greenish cork cambium
1890            4u8,
1891        ),
1892        (
1893            HistologicalTissueLayer::OuterRhytidome,
1894            0.096_f32,
1895            0.106_f32,
1896            [237, 235, 224, 255], // Chalky white outer bark
1897            5u8,
1898        ),
1899    ];
1900
1901    // Angle of explosion along the bisector of the 270° wedge (135° = 0.75 * PI)
1902    let bisect_angle = 0.75 * PI;
1903    let explode_dir = [
1904        bisect_angle.cos() * 0.045,
1905        0.022_f32,
1906        bisect_angle.sin() * 0.045,
1907    ];
1908
1909    for (layer_enum, r_inner, r_outer, base_col, layer_idx) in layers {
1910        b.begin_tissue_layer(layer_enum, layer_idx);
1911
1912        // Displacement vector for interactive layer peeling
1913        let disp_scale = explode_factor_01 * (layer_idx as f32);
1914        let disp = [
1915            explode_dir[0] * disp_scale,
1916            explode_dir[1] * disp_scale,
1917            explode_dir[2] * disp_scale,
1918        ];
1919
1920        // 1. Outer curved cylindrical wall of the 270° wedge (with bark fissures on OuterRhytidome)
1921        let base_v_outer = b.positions.len() as u32;
1922        for v in 0..=n_vertical {
1923            let y_frac = v as f32 / n_vertical as f32;
1924            let y = y_frac * stem_height + disp[1];
1925
1926            for a in 0..=n_radial {
1927                let a_frac = a as f32 / n_radial as f32;
1928                let theta = a_frac * wedge_span_rad;
1929                let norm = [theta.cos(), 0.0, theta.sin()];
1930                let fissure = if layer_enum == HistologicalTissueLayer::OuterRhytidome {
1931                    0.0018 * ((theta * 14.0).sin() * (y_frac * PI * 3.0).cos())
1932                } else {
1933                    0.0
1934                };
1935                let r_eff = r_outer + fissure;
1936                let pos = [disp[0] + norm[0] * r_eff, y, disp[2] + norm[2] * r_eff];
1937                b.add_vertex(pos, norm, [a_frac, y_frac], base_col);
1938            }
1939        }
1940        for v in 0..n_vertical {
1941            for a in 0..n_radial {
1942                let i0 = base_v_outer + (v * (n_radial + 1) + a) as u32;
1943                let i1 = i0 + (n_radial + 1) as u32;
1944                let i2 = i1 + 1;
1945                let i3 = i0 + 1;
1946                b.add_quad(i0, i1, i2, i3);
1947            }
1948        }
1949
1950        // 2. Inner curved cylindrical wall (if r_inner > 0.0)
1951        if r_inner > 0.001 {
1952            let base_v_inner = b.positions.len() as u32;
1953            for v in 0..=n_vertical {
1954                let y_frac = v as f32 / n_vertical as f32;
1955                let y = y_frac * stem_height + disp[1];
1956
1957                for a in 0..=n_radial {
1958                    let a_frac = a as f32 / n_radial as f32;
1959                    let theta = a_frac * wedge_span_rad;
1960                    let norm = [-theta.cos(), 0.0, -theta.sin()];
1961                    let pos = [disp[0] - norm[0] * r_inner, y, disp[2] - norm[2] * r_inner];
1962                    b.add_vertex(pos, norm, [a_frac, y_frac], base_col);
1963                }
1964            }
1965            for v in 0..n_vertical {
1966                for a in 0..n_radial {
1967                    let i0 = base_v_inner + (v * (n_radial + 1) + a) as u32;
1968                    let i1 = i0 + 1;
1969                    let i2 = i1 + (n_radial + 1) as u32;
1970                    let i3 = i0 + (n_radial + 1) as u32;
1971                    b.add_quad(i0, i1, i2, i3);
1972                }
1973            }
1974        }
1975
1976        // 3. Top Transverse Annular Face (Y = stem_height)
1977        let base_top = b.positions.len() as u32;
1978        let y_top = stem_height + disp[1];
1979        for a in 0..=n_radial {
1980            let a_frac = a as f32 / n_radial as f32;
1981            let theta = a_frac * wedge_span_rad;
1982            let cos_t = theta.cos();
1983            let sin_t = theta.sin();
1984
1985            let p_in = [disp[0] + cos_t * r_inner, y_top, disp[2] + sin_t * r_inner];
1986            let p_out = [disp[0] + cos_t * r_outer, y_top, disp[2] + sin_t * r_outer];
1987            b.add_vertex(p_in, [0.0, 1.0, 0.0], [0.0, a_frac], base_col);
1988            b.add_vertex(p_out, [0.0, 1.0, 0.0], [1.0, a_frac], base_col);
1989        }
1990        for a in 0..n_radial {
1991            let i0 = base_top + (a * 2) as u32;
1992            let i1 = i0 + 1;
1993            let i2 = i0 + 3;
1994            let i3 = i0 + 2;
1995            b.add_quad(i0, i1, i2, i3);
1996        }
1997
1998        // 4. Bottom Transverse Annular Face (Y = 0)
1999        let base_bot = b.positions.len() as u32;
2000        let y_bot = disp[1];
2001        for a in 0..=n_radial {
2002            let a_frac = a as f32 / n_radial as f32;
2003            let theta = a_frac * wedge_span_rad;
2004            let cos_t = theta.cos();
2005            let sin_t = theta.sin();
2006
2007            let p_in = [disp[0] + cos_t * r_inner, y_bot, disp[2] + sin_t * r_inner];
2008            let p_out = [disp[0] + cos_t * r_outer, y_bot, disp[2] + sin_t * r_outer];
2009            b.add_vertex(p_in, [0.0, -1.0, 0.0], [0.0, a_frac], base_col);
2010            b.add_vertex(p_out, [0.0, -1.0, 0.0], [1.0, a_frac], base_col);
2011        }
2012        for a in 0..n_radial {
2013            let i0 = base_bot + (a * 2) as u32;
2014            let i1 = i0 + 2;
2015            let i2 = i0 + 3;
2016            let i3 = i0 + 1;
2017            b.add_quad(i0, i1, i2, i3);
2018        }
2019
2020        // 5. Radial Cut Face at theta = 0 (Normal = [0, 0, -1])
2021        let i0 = b.add_vertex(
2022            [disp[0] + r_inner, y_bot, disp[2]],
2023            [0.0, 0.0, -1.0],
2024            [0.0, 0.0],
2025            base_col,
2026        );
2027        let i1 = b.add_vertex(
2028            [disp[0] + r_inner, y_top, disp[2]],
2029            [0.0, 0.0, -1.0],
2030            [0.0, 1.0],
2031            base_col,
2032        );
2033        let i2 = b.add_vertex(
2034            [disp[0] + r_outer, y_top, disp[2]],
2035            [0.0, 0.0, -1.0],
2036            [1.0, 1.0],
2037            base_col,
2038        );
2039        let i3 = b.add_vertex(
2040            [disp[0] + r_outer, y_bot, disp[2]],
2041            [0.0, 0.0, -1.0],
2042            [1.0, 0.0],
2043            base_col,
2044        );
2045        b.add_quad(i0, i1, i2, i3);
2046
2047        // 6. Tangential Cut Face at theta = 270° (Normal = [1, 0, 0])
2048        let cos_270 = wedge_span_rad.cos();
2049        let sin_270 = wedge_span_rad.sin();
2050        let norm_tangent = [-sin_270, 0.0, cos_270];
2051        let j0 = b.add_vertex(
2052            [
2053                disp[0] + cos_270 * r_inner,
2054                y_bot,
2055                disp[2] + sin_270 * r_inner,
2056            ],
2057            norm_tangent,
2058            [0.0, 0.0],
2059            base_col,
2060        );
2061        let j1 = b.add_vertex(
2062            [
2063                disp[0] + cos_270 * r_outer,
2064                y_bot,
2065                disp[2] + sin_270 * r_outer,
2066            ],
2067            norm_tangent,
2068            [1.0, 0.0],
2069            base_col,
2070        );
2071        let j2 = b.add_vertex(
2072            [
2073                disp[0] + cos_270 * r_outer,
2074                y_top,
2075                disp[2] + sin_270 * r_outer,
2076            ],
2077            norm_tangent,
2078            [1.0, 1.0],
2079            base_col,
2080        );
2081        let j3 = b.add_vertex(
2082            [
2083                disp[0] + cos_270 * r_inner,
2084                y_top,
2085                disp[2] + sin_270 * r_inner,
2086            ],
2087            norm_tangent,
2088            [0.0, 1.0],
2089            base_col,
2090        );
2091        b.add_quad(j0, j1, j2, j3);
2092
2093        // Layer-specific histological structures:
2094        match layer_enum {
2095            HistologicalTissueLayer::HeartwoodAndPith => {
2096                // Central primary pith column and dark heartwood growth-ring bands
2097                b.add_cylinder_segment(
2098                    [disp[0], y_bot - 0.001, disp[2]],
2099                    [disp[0], y_top + 0.001, disp[2]],
2100                    0.006,
2101                    0.006,
2102                    8,
2103                    [78, 38, 26, 255],
2104                    [78, 38, 26, 255],
2105                );
2106            }
2107            HistologicalTissueLayer::SapwoodSecondaryXylem => {
2108                // 1) 3 concentric latewood growth-ring ridges on the top transverse face
2109                for ring_k in 1..=3 {
2110                    let r_ring = r_inner + (ring_k as f32 / 4.0) * (r_outer - r_inner);
2111                    for a in 0..8 {
2112                        let t0 = (a as f32 / 8.0) * wedge_span_rad;
2113                        let t1 = ((a + 1) as f32 / 8.0) * wedge_span_rad;
2114                        b.add_cylinder_segment(
2115                            [
2116                                disp[0] + t0.cos() * r_ring,
2117                                y_top + 0.0008,
2118                                disp[2] + t0.sin() * r_ring,
2119                            ],
2120                            [
2121                                disp[0] + t1.cos() * r_ring,
2122                                y_top + 0.0008,
2123                                disp[2] + t1.sin() * r_ring,
2124                            ],
2125                            0.0009,
2126                            0.0009,
2127                            4,
2128                            [172, 146, 112, 255],
2129                            [172, 146, 112, 255],
2130                        );
2131                    }
2132                }
2133                // 2) 10 radial medullary rays cutting across growth rings and descending the radial face
2134                for ray_i in 0..10 {
2135                    let ray_frac = (ray_i as f32 + 0.5) / 10.0;
2136                    let ray_theta = ray_frac * wedge_span_rad;
2137                    let rx0 = disp[0] + ray_theta.cos() * (r_inner + 0.002);
2138                    let rz0 = disp[2] + ray_theta.sin() * (r_inner + 0.002);
2139                    let rx1 = disp[0] + ray_theta.cos() * (r_outer - 0.002);
2140                    let rz1 = disp[2] + ray_theta.sin() * (r_outer - 0.002);
2141                    b.add_cylinder_segment(
2142                        [rx0, y_top + 0.001, rz0],
2143                        [rx1, y_top + 0.001, rz1],
2144                        0.0011,
2145                        0.0011,
2146                        4,
2147                        [188, 168, 136, 255],
2148                        [188, 168, 136, 255],
2149                    );
2150                }
2151                // 3) Xylem vessel pores (tracheary vessel elements) exposed on transverse cut
2152                for pore_i in 0..14 {
2153                    let pf = (pore_i as f32 + 0.5) / 14.0;
2154                    let p_theta = pf * wedge_span_rad;
2155                    let p_rad = r_inner
2156                        + (0.22 + 0.58 * ((pore_i * 7 % 5) as f32 / 4.0)) * (r_outer - r_inner);
2157                    let px = disp[0] + p_theta.cos() * p_rad;
2158                    let pz = disp[2] + p_theta.sin() * p_rad;
2159                    b.add_cylinder_segment(
2160                        [px, y_top - 0.018, pz],
2161                        [px, y_top + 0.0016, pz],
2162                        0.0016,
2163                        0.0016,
2164                        6,
2165                        [132, 108, 82, 255],
2166                        [112, 88, 64, 255],
2167                    );
2168                }
2169            }
2170            HistologicalTissueLayer::SecondaryPhloemAndKinoDucts => {
2171                // Axial phloem sieve-tube bundles & blood-red kino resin ducts
2172                for k in 0..8 {
2173                    let k_frac = (k as f32 + 0.5) / 8.0;
2174                    let k_theta = k_frac * wedge_span_rad;
2175                    let k_r = (r_inner + r_outer) * 0.5;
2176                    let kx = disp[0] + k_theta.cos() * k_r;
2177                    let kz = disp[2] + k_theta.sin() * k_r;
2178                    let col_duct = if k % 2 == 0 {
2179                        [165, 38, 24, 255] // Blood-red kino resin duct
2180                    } else {
2181                        [204, 142, 92, 255] // Phloem sieve tube strand
2182                    };
2183                    b.add_cylinder_segment(
2184                        [kx, y_bot + 0.01, kz],
2185                        [kx, y_top - 0.001, kz],
2186                        0.0022,
2187                        0.0022,
2188                        5,
2189                        col_duct,
2190                        col_duct,
2191                    );
2192                }
2193            }
2194            HistologicalTissueLayer::OuterRhytidome => {
2195                // Golden-angle phyllotaxis lateral nodes, leaf scars, and peeling bark strips
2196                for b_idx in 0..4 {
2197                    let b_y = disp[1] + stem_height * (0.18 + 0.22 * b_idx as f32);
2198                    let b_phi = (b_idx as f32) * GOLDEN_ANGLE_RAD;
2199                    let phi_clamped = b_phi.rem_euclid(2.0 * PI);
2200                    if phi_clamped < wedge_span_rad - 0.15 {
2201                        let b_dir = [phi_clamped.cos(), 0.22, phi_clamped.sin()];
2202                        let p_base = [
2203                            disp[0] + b_dir[0] * r_outer,
2204                            b_y,
2205                            disp[2] + b_dir[2] * r_outer,
2206                        ];
2207                        let p_tip = [
2208                            p_base[0] + b_dir[0] * 0.028,
2209                            p_base[1] + b_dir[1] * 0.028,
2210                            p_base[2] + b_dir[2] * 0.028,
2211                        ];
2212                        b.add_cylinder_segment(
2213                            p_base,
2214                            p_tip,
2215                            0.0085,
2216                            0.0042,
2217                            6,
2218                            [218, 214, 202, 255],
2219                            [172, 188, 134, 255],
2220                        );
2221                    }
2222                }
2223            }
2224            _ => {}
2225        }
2226
2227        b.end_tissue_layer();
2228    }
2229
2230    let recipe_urn = format!(
2231        "urn:qualia:botanical:scale2:{species_id}:wedge:explode={:.2}",
2232        explode_factor_01
2233    );
2234    let container_bytes = seal_botanical_organ_10d(
2235        BotanicalEducationScale::Scale2BranchPhyllotaxisAndStemWedge,
2236        &b.positions,
2237        &b.normals,
2238        &b.colors,
2239        &b.uvs,
2240        &b.indices,
2241        &b.slices,
2242        &recipe_urn,
2243        None,
2244    )?;
2245
2246    let organ = CompiledBotanicalOrgan10d {
2247        scale: BotanicalEducationScale::Scale2BranchPhyllotaxisAndStemWedge,
2248        vertices: b.positions,
2249        normals: b.normals,
2250        uvs: b.uvs,
2251        colors: b.colors,
2252        material_indices: b.material_indices,
2253        indices: b.indices,
2254        tissue_slices: b.slices,
2255        container_bytes,
2256    };
2257
2258    organ.verify_all()?;
2259    Ok(organ)
2260}
2261
2262// ============================================================================
2263// 6. Scale 3: Floral & Fruit Reproductive Dissection
2264// ============================================================================
2265
2266/// Synthesize Scale 3 Floral & Fruit Reproductive Dissection (`5 mm – 150 mm`) with
2267/// 7-flowered umbellaster, circumscissile operculum shedding (baked into `MRP1` morph deltas),
2268/// 48+ inflexed/unfurling stamens, versatile anthers, style/stigma, 4-locule inferior ovary with ovules,
2269/// and dehiscing woody gumnut capsule with fertile winged seeds and chaff. ($\ge 2,200$ vertices).
2270pub fn build_scale3_floral_and_gumnut_dissection_10d(
2271    species_id: &str,
2272    anthesis_progress_01: f32,
2273    cutaway_01: f32,
2274) -> Result<CompiledBotanicalOrgan10d, String> {
2275    let mut b = OrganMeshBuilder::new();
2276
2277    // ------------------------------------------------------------------------
2278    // Layer 1: Inflorescence Peduncle & Pedicels (`PeduncleAndPedicel`)
2279    // ------------------------------------------------------------------------
2280    b.begin_tissue_layer(HistologicalTissueLayer::PeduncleAndPedicel, 0);
2281    // Common central peduncle with basal bract scar swelling
2282    let ped_base = [0.0_f32, -0.048_f32, 0.0_f32];
2283    let ped_mid = [0.0_f32, -0.030_f32, 0.0_f32];
2284    let ped_top = [0.0_f32, -0.014_f32, 0.0_f32];
2285    b.add_cylinder_segment(
2286        ped_base,
2287        ped_mid,
2288        0.0032,
2289        0.0026,
2290        8,
2291        [114, 136, 88, 255],
2292        [126, 148, 98, 255],
2293    );
2294    b.add_cylinder_segment(
2295        ped_mid,
2296        ped_top,
2297        0.0026,
2298        0.0034,
2299        8,
2300        [126, 148, 98, 255],
2301        [138, 162, 108, 255],
2302    );
2303
2304    // 7 radiating pedicels forming the corymbose umbellaster + woody fruiting pedicel
2305    let num_flowers = 7;
2306    let mut flower_origins = Vec::new();
2307
2308    for f in 0..num_flowers {
2309        let f_pos = if f == 0 {
2310            // Central terminal dissected flower
2311            [0.0_f32, 0.0_f32, 0.0_f32]
2312        } else {
2313            // 6 peripheral umbel rays
2314            let angle = ((f - 1) as f32) * (2.0 * PI / 6.0);
2315            let ray_r = 0.025_f32;
2316            [
2317                angle.cos() * ray_r,
2318                0.003_f32 + 0.002 * ((f % 2) as f32),
2319                angle.sin() * ray_r,
2320            ]
2321        };
2322        b.add_cylinder_segment(
2323            ped_top,
2324            f_pos,
2325            0.0019,
2326            0.0015,
2327            6,
2328            [135, 158, 108, 255],
2329            [150, 172, 118, 255],
2330        );
2331        flower_origins.push(f_pos);
2332    }
2333
2334    // Woody stalk supporting the mature gumnut capsule at right
2335    // Separate the dissection specimen in both front and side projections.
2336    let gumnut_offset = [0.038_f32, 0.0_f32, -0.035_f32];
2337    b.add_cylinder_segment(
2338        [gumnut_offset[0], -0.016, gumnut_offset[2]],
2339        gumnut_offset,
2340        0.0022,
2341        0.0028,
2342        6,
2343        [112, 94, 72, 255],
2344        [124, 104, 80, 255],
2345    );
2346    b.end_tissue_layer();
2347
2348    // Focus high-detail dissection on the central flower (`f == 0` at [0, 0, 0])
2349    let cup_base = [0.0_f32, 0.0_f32, 0.0_f32];
2350    let cup_rim_y = 0.013_f32;
2351    let cup_rim_r = 0.0078_f32;
2352    // Cutaway angle removes up to 110 degrees on the front (+Z) side of the central hypanthium
2353    let cut_half_angle = cutaway_01.clamp(0.15, 1.0) * (PI * 0.32);
2354
2355    // ------------------------------------------------------------------------
2356    // Layer 2: Hypanthium Calyx Tube (`HypanthiumCalyxTube`)
2357    // ------------------------------------------------------------------------
2358    b.begin_tissue_layer(HistologicalTissueLayer::HypanthiumCalyxTube, 1);
2359    // Sculpted urceolate-campanulate floral cup on the central flower with cutaway window
2360    let n_cup = 20usize;
2361    let n_cup_y = 7usize;
2362    let base_cup_v = b.positions.len() as u32;
2363    let start_angle = PI * 0.5 + cut_half_angle;
2364    let sweep_angle = 2.0 * PI - 2.0 * cut_half_angle;
2365
2366    for y_idx in 0..=n_cup_y {
2367        let y_frac = y_idx as f32 / n_cup_y as f32;
2368        let y = cup_base[1] + y_frac * (cup_rim_y - cup_base[1]);
2369        // Urceolate floral tube profile: rounded ovary belly + slight neck + flared staminal rim
2370        let belly = (y_frac * PI).sin() * 0.0014;
2371        let r = 0.0020 + y_frac * (cup_rim_r - 0.0020) + belly;
2372
2373        for a in 0..=n_cup {
2374            let a_frac = a as f32 / n_cup as f32;
2375            let theta = start_angle + a_frac * sweep_angle;
2376            let norm = [theta.cos() * 0.92, -0.25, theta.sin() * 0.92];
2377            let pos = [theta.cos() * r, y, theta.sin() * r];
2378            b.add_vertex(pos, norm, [a_frac, y_frac], [176, 184, 134, 255]);
2379        }
2380    }
2381    for y_idx in 0..n_cup_y {
2382        for a in 0..n_cup {
2383            let i0 = base_cup_v + (y_idx * (n_cup + 1) + a) as u32;
2384            let i1 = i0 + (n_cup + 1) as u32;
2385            let i2 = i1 + 1;
2386            let i3 = i0 + 1;
2387            b.add_quad(i0, i1, i2, i3);
2388        }
2389    }
2390
2391    // Peripheral umbellaster floral cups (6 surrounding flowers in the 7-flowered umbellaster)
2392    for &p_orig in flower_origins.iter().skip(1) {
2393        let p_top = [p_orig[0], p_orig[1] + 0.0085, p_orig[2]];
2394        b.add_cylinder_segment(
2395            p_orig,
2396            p_top,
2397            0.0018,
2398            0.0046,
2399            8,
2400            [164, 176, 124, 255],
2401            [184, 192, 142, 255],
2402        );
2403    }
2404    b.end_tissue_layer();
2405
2406    // ------------------------------------------------------------------------
2407    // Layer 3: Operculum (Calyptriform Bud Cap) (`OperculumCalyptra`)
2408    // ------------------------------------------------------------------------
2409    b.begin_tissue_layer(HistologicalTissueLayer::OperculumCalyptra, 2);
2410    // Central operculum lifts off and tilts away along an arc as anthesis progresses
2411    let operculum_lift = anthesis_progress_01 * 0.022;
2412    let operculum_tilt = anthesis_progress_01 * 0.82;
2413    let op_center = [
2414        operculum_lift * 0.55,
2415        cup_rim_y + operculum_lift,
2416        operculum_lift * 0.25,
2417    ];
2418
2419    let n_op = 18usize;
2420    let n_op_y = 7usize;
2421    let base_op_v = b.positions.len() as u32;
2422
2423    for y_idx in 0..=n_op_y {
2424        let y_frac = y_idx as f32 / n_op_y as f32;
2425        let local_y = y_frac * 0.0072;
2426        // Conical-beaked calyptra profile (umbonate apex typical of Corymbia/Eucalyptus)
2427        let local_r = cup_rim_r * (1.0 - y_frac).powf(0.72);
2428
2429        for a in 0..=n_op {
2430            let a_frac = a as f32 / n_op as f32;
2431            let theta = a_frac * 2.0 * PI;
2432            let cos_t = theta.cos();
2433            let sin_t = theta.sin();
2434
2435            let rx = cos_t * local_r * operculum_tilt.cos() - local_y * operculum_tilt.sin();
2436            let ry = cos_t * local_r * operculum_tilt.sin() + local_y * operculum_tilt.cos();
2437            let rz = sin_t * local_r;
2438
2439            let pos = [op_center[0] + rx, op_center[1] + ry, op_center[2] + rz];
2440            let norm = [cos_t * 0.7, 0.7, sin_t * 0.7];
2441            b.add_vertex(pos, norm, [a_frac, y_frac], [224, 214, 173, 255]);
2442        }
2443    }
2444    for y_idx in 0..n_op_y {
2445        for a in 0..n_op {
2446            let i0 = base_op_v + (y_idx * (n_op + 1) + a) as u32;
2447            let i1 = i0 + (n_op + 1) as u32;
2448            let i2 = i1 + 1;
2449            let i3 = i0 + 1;
2450            b.add_quad(i0, i1, i2, i3);
2451        }
2452    }
2453
2454    // Intact conical operculum caps on 3 of the peripheral buds in the umbellaster
2455    for (idx, &p_orig) in flower_origins.iter().skip(1).enumerate() {
2456        if idx % 2 == 0 {
2457            let rim = [p_orig[0], p_orig[1] + 0.0085, p_orig[2]];
2458            let apex = [p_orig[0], p_orig[1] + 0.0135, p_orig[2]];
2459            b.add_cylinder_segment(
2460                rim,
2461                apex,
2462                0.0046,
2463                0.0006,
2464                8,
2465                [218, 208, 166, 255],
2466                [232, 222, 182, 255],
2467            );
2468        }
2469    }
2470    b.end_tissue_layer();
2471
2472    // ------------------------------------------------------------------------
2473    // Layer 4 & 5: Staminal Ring Filaments & Versatile Anthers
2474    // ------------------------------------------------------------------------
2475    b.begin_tissue_layer(HistologicalTissueLayer::StaminalRingFilaments, 3);
2476    let num_filaments = 56usize;
2477    let fil_len = 0.0145_f32;
2478    let mut anther_positions = Vec::new();
2479
2480    for i in 0..num_filaments {
2481        let whorl = (i % 3) as f32;
2482        let frac = (i as f32) / (num_filaments as f32);
2483        let theta = frac * 2.0 * PI;
2484        let r_insertion = cup_rim_r * (0.84 + whorl * 0.055);
2485
2486        let p_base = [
2487            theta.cos() * r_insertion,
2488            cup_rim_y,
2489            theta.sin() * r_insertion,
2490        ];
2491
2492        // Anthesis controls uncurling from inflexed bud posture to radiant cream burst
2493        let uncurl = anthesis_progress_01.clamp(0.0, 1.0);
2494        let out_reach = r_insertion + uncurl * (0.0065 + whorl * 0.0022);
2495        let p_knee = [
2496            theta.cos() * (r_insertion + uncurl * 0.0028),
2497            cup_rim_y + 0.0042 * (0.7 + uncurl * 0.9),
2498            theta.sin() * (r_insertion + uncurl * 0.0028),
2499        ];
2500        let p_mid = [
2501            theta.cos() * (r_insertion + uncurl * 0.0055),
2502            cup_rim_y + 0.0082 * (0.5 + uncurl * 0.85),
2503            theta.sin() * (r_insertion + uncurl * 0.0055),
2504        ];
2505        let p_tip = [
2506            theta.cos() * out_reach,
2507            cup_rim_y
2508                + if uncurl < 0.25 {
2509                    -0.0018
2510                } else {
2511                    fil_len * (0.48 + uncurl * 0.52) - whorl * 0.0012
2512                },
2513            theta.sin() * out_reach,
2514        ];
2515
2516        b.add_cylinder_segment(
2517            p_base,
2518            p_knee,
2519            0.00028,
2520            0.00024,
2521            4,
2522            [248, 242, 212, 255],
2523            [252, 248, 224, 255],
2524        );
2525        b.add_cylinder_segment(
2526            p_knee,
2527            p_mid,
2528            0.00024,
2529            0.00020,
2530            4,
2531            [252, 248, 224, 255],
2532            [254, 250, 232, 255],
2533        );
2534        b.add_cylinder_segment(
2535            p_mid,
2536            p_tip,
2537            0.00020,
2538            0.00015,
2539            4,
2540            [254, 250, 232, 255],
2541            [255, 252, 238, 255],
2542        );
2543
2544        anther_positions.push(p_tip);
2545    }
2546
2547    // Radiant stamen filaments on the 3 open peripheral flowers in the umbellaster
2548    for (idx, &p_orig) in flower_origins.iter().skip(1).enumerate() {
2549        if idx % 2 == 1 {
2550            let rim_y = p_orig[1] + 0.0085;
2551            for k in 0..12 {
2552                let ka = (k as f32 / 12.0) * 2.0 * PI;
2553                let pb = [
2554                    p_orig[0] + ka.cos() * 0.0042,
2555                    rim_y,
2556                    p_orig[2] + ka.sin() * 0.0042,
2557                ];
2558                let pt = [
2559                    p_orig[0] + ka.cos() * 0.0095,
2560                    rim_y + 0.0065,
2561                    p_orig[2] + ka.sin() * 0.0095,
2562                ];
2563                b.add_cylinder_segment(
2564                    pb,
2565                    pt,
2566                    0.00022,
2567                    0.00014,
2568                    4,
2569                    [252, 248, 224, 255],
2570                    [255, 252, 238, 255],
2571                );
2572                anther_positions.push(pt);
2573            }
2574        }
2575    }
2576    b.end_tissue_layer();
2577
2578    b.begin_tissue_layer(HistologicalTissueLayer::VersatileAnthersAndPollen, 4);
2579    // Dorsifixed versatile bilobed anthers at each stamen tip
2580    for &p_anther in &anther_positions {
2581        b.add_ellipsoid(
2582            p_anther,
2583            [0.00062, 0.00042, 0.00045],
2584            4,
2585            6,
2586            [245, 209, 61, 255], // Golden pollen yellow
2587        );
2588    }
2589    b.end_tissue_layer();
2590
2591    // ------------------------------------------------------------------------
2592    // Layer 6: Gynoecium (Style, Stigma & Nectar Disc) (`GynoeciumStyleStigma`)
2593    // ------------------------------------------------------------------------
2594    b.begin_tissue_layer(HistologicalTissueLayer::GynoeciumStyleStigma, 5);
2595    // Central terete style rising from the superior ovary roof
2596    let style_h = 0.0098_f32;
2597    b.add_cylinder_segment(
2598        [0.0, cup_rim_y - 0.001, 0.0],
2599        [0.0, cup_rim_y + style_h, 0.0],
2600        0.00082,
2601        0.00056,
2602        8,
2603        [158, 192, 114, 255],
2604        [176, 212, 132, 255],
2605    );
2606    // Terminal capitate papillate stigma
2607    b.add_ellipsoid(
2608        [0.0, cup_rim_y + style_h + 0.0004, 0.0],
2609        [0.00088, 0.00065, 0.00088],
2610        5,
2611        8,
2612        [194, 228, 142, 255],
2613    );
2614    // Raised annular nectariferous disc lining the hypanthium summit
2615    b.add_cylinder_segment(
2616        [0.0, cup_rim_y - 0.0008, 0.0],
2617        [0.0, cup_rim_y + 0.0006, 0.0],
2618        cup_rim_r * 0.62,
2619        cup_rim_r * 0.54,
2620        12,
2621        [146, 178, 106, 255],
2622        [164, 196, 122, 255],
2623    );
2624    b.end_tissue_layer();
2625
2626    // ------------------------------------------------------------------------
2627    // Layer 7: Ovary Locules & Ovules Dissection (`OvaryLoculesAndOvules`)
2628    // ------------------------------------------------------------------------
2629    b.begin_tissue_layer(HistologicalTissueLayer::OvaryLoculesAndOvules, 6);
2630    // 4 locule chambers with central axile placentation, radial septa, and anatropous ovules
2631    let locule_y = cup_rim_y * 0.44;
2632    let loc_r = cup_rim_r * 0.36;
2633
2634    // Central axile placenta column
2635    b.add_cylinder_segment(
2636        [0.0, 0.0018, 0.0],
2637        [0.0, cup_rim_y * 0.86, 0.0],
2638        0.00085,
2639        0.00075,
2640        8,
2641        [204, 214, 172, 255],
2642        [214, 224, 182, 255],
2643    );
2644
2645    // 4 locules with 2 vertical rows of anatropous ovules per locule
2646    for loc in 0..4 {
2647        let loc_a = (loc as f32) * (PI / 2.0) + 0.39;
2648        let lx = loc_a.cos() * loc_r;
2649        let lz = loc_a.sin() * loc_r;
2650
2651        for row in 0..5 {
2652            let oy = locule_y + (row as f32 - 2.0) * 0.0011;
2653            b.add_ellipsoid(
2654                [lx, oy, lz],
2655                [0.00052, 0.00044, 0.00052],
2656                4,
2657                6,
2658                [234, 240, 208, 255],
2659            );
2660        }
2661    }
2662    b.end_tissue_layer();
2663
2664    // ------------------------------------------------------------------------
2665    // Layer 8 & 9: Mature Woody Gumnut Capsule & Seeds (Offset beside the flower)
2666    // ------------------------------------------------------------------------
2667    b.begin_tissue_layer(HistologicalTissueLayer::WoodyPericarpAndDehiscingValves, 7);
2668    // Sculpted urceolate (pitcher/urn-shaped) woody *Corymbia* gumnut capsule
2669    let cap_h = 0.0155_f32;
2670    let cap_r_max = 0.0078_f32;
2671    let cap_rim_r = 0.0056_f32;
2672    let n_cap = 20usize;
2673    let n_cap_y = 8usize;
2674    let base_cap_v = b.positions.len() as u32;
2675
2676    for y_idx in 0..=n_cap_y {
2677        let y_frac = y_idx as f32 / n_cap_y as f32;
2678        let y = gumnut_offset[1] + y_frac * cap_h;
2679        // Authentic urceolate profile: rounded cup base, swollen belly, contracted neck, flared rim
2680        let r = if y_frac < 0.55 {
2681            cap_r_max * (0.48 + 0.52 * (y_frac / 0.55 * PI * 0.5).sin())
2682        } else if y_frac < 0.85 {
2683            let neck_t = (y_frac - 0.55) / 0.30;
2684            cap_r_max * (1.0 - 0.30 * (neck_t * PI * 0.5).sin())
2685        } else {
2686            let flare_t = (y_frac - 0.85) / 0.15;
2687            cap_r_max * (0.70 + 0.08 * flare_t)
2688        };
2689
2690        for a in 0..=n_cap {
2691            let a_frac = a as f32 / n_cap as f32;
2692            let theta = a_frac * 2.0 * PI;
2693            let norm = [theta.cos(), 0.12, theta.sin()];
2694            let pos = [
2695                gumnut_offset[0] + theta.cos() * r,
2696                y,
2697                gumnut_offset[2] + theta.sin() * r,
2698            ];
2699            let shade = if y_frac > 0.85 {
2700                [138, 114, 90, 255]
2701            } else {
2702                [112, 92, 72, 255]
2703            };
2704            b.add_vertex(pos, norm, [a_frac, y_frac], shade);
2705        }
2706    }
2707    for y_idx in 0..n_cap_y {
2708        for a in 0..n_cap {
2709            let i0 = base_cap_v + (y_idx * (n_cap + 1) + a) as u32;
2710            let i1 = i0 + (n_cap + 1) as u32;
2711            let i2 = i1 + 1;
2712            let i3 = i0 + 1;
2713            b.add_quad(i0, i1, i2, i3);
2714        }
2715    }
2716
2717    // 4 woody triangular dehiscing valves opening at the capsule summit
2718    let valve_y = gumnut_offset[1] + cap_h - 0.0016;
2719    for v in 0..4 {
2720        let a0 = (v as f32) * (PI * 0.5);
2721        let a1 = a0 + PI * 0.25;
2722        let a2 = a0 + PI * 0.5;
2723
2724        let p_center = [gumnut_offset[0], valve_y - 0.0018, gumnut_offset[2]];
2725        let p0 = [
2726            gumnut_offset[0] + a0.cos() * cap_rim_r * 0.88,
2727            valve_y,
2728            gumnut_offset[2] + a0.sin() * cap_rim_r * 0.88,
2729        ];
2730        let p1 = [
2731            gumnut_offset[0] + a1.cos() * cap_rim_r * 0.55,
2732            valve_y + 0.0018, // Reflexed open valve tip
2733            gumnut_offset[2] + a1.sin() * cap_rim_r * 0.55,
2734        ];
2735        let p2 = [
2736            gumnut_offset[0] + a2.cos() * cap_rim_r * 0.88,
2737            valve_y,
2738            gumnut_offset[2] + a2.sin() * cap_rim_r * 0.88,
2739        ];
2740
2741        let i_c = b.add_vertex(p_center, [0.0, 1.0, 0.0], [0.5, 0.5], [88, 70, 54, 255]);
2742        let i_0 = b.add_vertex(p0, [0.0, 1.0, 0.0], [0.0, 0.0], [132, 110, 88, 255]);
2743        let i_1 = b.add_vertex(p1, [0.0, 1.0, 0.0], [0.5, 1.0], [152, 128, 102, 255]);
2744        let i_2 = b.add_vertex(p2, [0.0, 1.0, 0.0], [1.0, 0.0], [132, 110, 88, 255]);
2745        b.add_triangle(i_c, i_0, i_1);
2746        b.add_triangle(i_c, i_1, i_2);
2747    }
2748    b.end_tissue_layer();
2749
2750    b.begin_tissue_layer(HistologicalTissueLayer::FertileWingedSeedsAndChaff, 8);
2751    // Fertile terminal-winged seeds and reddish-brown sterile chaff spilling from the dehiscing capsule
2752    for s in 0..12 {
2753        let s_a = (s as f32) * (2.0 * PI / 12.0) + 0.25;
2754        let s_dist = cap_rim_r * (0.28 + (s as f32 % 4.0) * 0.22);
2755        let s_pos = [
2756            gumnut_offset[0] + s_a.cos() * s_dist,
2757            valve_y - 0.0006 + (s as f32 * 0.00045),
2758            gumnut_offset[2] + s_a.sin() * s_dist,
2759        ];
2760        let is_fertile = s % 2 == 0;
2761        let radii = if is_fertile {
2762            [0.0016, 0.00038, 0.00085] // Flattened winged seed
2763        } else {
2764            [0.00075, 0.00035, 0.00045] // Subulate sterile chaff grain
2765        };
2766        let col = if is_fertile {
2767            [68, 42, 28, 255]
2768        } else {
2769            [128, 68, 42, 255]
2770        };
2771        b.add_ellipsoid(s_pos, radii, 3, 5, col);
2772    }
2773    b.end_tissue_layer();
2774
2775    // Baked morph targets for anthesis operculum shedding and stamen unfurling
2776    let mut morph_deltas = Vec::new();
2777    let n_verts = b.positions.len();
2778    let step = (n_verts / 32).max(1);
2779    for vi in (0..n_verts).step_by(step) {
2780        let p = b.positions[vi];
2781        let n = b.normals.get(vi).copied().unwrap_or([0.0, 1.0, 0.0]);
2782        // Target 0: Anthesis expansion (filaments bloom outward, operculum translates away)
2783        let lift = if p[1] > cup_rim_y { 0.015 } else { 0.0 };
2784        let d0 = quantize_morph_delta(
2785            [p[0] * 0.25, lift, p[2] * 0.25],
2786            [n[0] * 0.1, n[1] * 0.05, n[2] * 0.1],
2787            [0.0, 0.0, 0.0],
2788            0.05,
2789            0,
2790            vi as u32,
2791        );
2792        morph_deltas.push(d0);
2793    }
2794    let morph_hdr = MorphSectionHeader {
2795        magic: MAGIC_MRP1,
2796        version: MORPH_SECTION_VERSION,
2797        target_count: 1,
2798        vertex_count: n_verts as u32,
2799        flags: FLAG_MORPH_SPARSE | FLAG_MORPH_HAS_NORMALS | FLAG_MORPH_ONTOGENETIC_BIND,
2800        max_displacement: 0.05,
2801        ontogenetic_bind_mask: 0b0001,
2802        reserved: [0u8; 8],
2803    };
2804
2805    let recipe_urn = format!(
2806        "urn:qualia:botanical:scale3:{species_id}:anthesis={:.2}:cutaway={:.2}",
2807        anthesis_progress_01, cutaway_01
2808    );
2809    let container_bytes = seal_botanical_organ_10d(
2810        BotanicalEducationScale::Scale3FloralAndGumnutDissection,
2811        &b.positions,
2812        &b.normals,
2813        &b.colors,
2814        &b.uvs,
2815        &b.indices,
2816        &b.slices,
2817        &recipe_urn,
2818        Some((&morph_hdr, &morph_deltas)),
2819    )?;
2820
2821    let organ = CompiledBotanicalOrgan10d {
2822        scale: BotanicalEducationScale::Scale3FloralAndGumnutDissection,
2823        vertices: b.positions,
2824        normals: b.normals,
2825        uvs: b.uvs,
2826        colors: b.colors,
2827        material_indices: b.material_indices,
2828        indices: b.indices,
2829        tissue_slices: b.slices,
2830        container_bytes,
2831    };
2832
2833    organ.verify_all()?;
2834    Ok(organ)
2835}
2836
2837// ============================================================================
2838// 7. Scale 4: Foliar Lamina Venation & Cellular Histology
2839// ============================================================================
2840
2841/// Synthesize Scale 4 Foliar Venation & Cellular Histology (`50 µm – 50 mm`) with Murray's Law
2842/// ($r_p^3 = r_1^3 + r_2^3$) midrib, diagnostic Myrtaceae intramarginal vein, pinnate secondaries,
2843/// tertiary areoles, and magnified 3D histological block featuring all 8 foliar cellular layers.
2844/// ($\ge 2,000$ vertices).
2845pub fn build_scale4_leaf_venation_and_histology_10d(
2846    species_id: &str,
2847    cutaway_01: f32,
2848) -> Result<CompiledBotanicalOrgan10d, String> {
2849    let mut b = OrganMeshBuilder::new();
2850
2851    // Verify upstream LeafVascularSkeleton biophysics
2852    let profile = LeafEconomicsProfile::eucalyptus_sclerophyll();
2853    let mut vascular_skel = LeafVascularSkeleton::new(profile, 1.25);
2854    vascular_skel.generate_venation();
2855    vascular_skel.propagate_murray_law();
2856    vascular_skel.evaluate_hydraulics(1.002e-3);
2857
2858    let leaf_len = profile.leaf_length_m; // 0.16 m = 160 mm
2859    let leaf_w = profile.leaf_width_m; // 0.035 m = 35 mm
2860
2861    // ------------------------------------------------------------------------
2862    // Part A: Macroscopic Falcate Leaf Lamina with Petiole & Cuticle Window
2863    // ------------------------------------------------------------------------
2864    let cut_clamped = cutaway_01.clamp(0.0, 1.0);
2865    // Magnified histological cutaway window positioned at the right mid-basal lamina,
2866    // oriented PARALLEL to the leaf blade (+Z = adaxial upper surface, -Z = abaxial lower surface)
2867    // so it reads as an authentic stepped anatomical magnification of the leaf cross-section
2868    // rather than an unrelated perpendicular sandwich floating beside the blade.
2869    let block_origin = [0.034_f32, -0.006_f32, 0.0015_f32];
2870    let bx_half = 0.016_f32;
2871    let by_half = 0.013_f32;
2872    let bz_half = 0.0052_f32;
2873
2874    b.begin_tissue_layer(HistologicalTissueLayer::WaxyCuticle, 0);
2875
2876    // 1. Curved twisted petiole at the leaf base
2877    let petiole_base = [-0.0045_f32, -leaf_len * 0.5 - 0.026, -0.0022_f32];
2878    let petiole_mid = [-0.0018_f32, -leaf_len * 0.5 - 0.012, -0.0008_f32];
2879    let petiole_top = [0.0_f32, -leaf_len * 0.5, 0.0004_f32];
2880    b.add_cylinder_segment(
2881        petiole_base,
2882        petiole_mid,
2883        0.0018,
2884        0.0016,
2885        8,
2886        [136, 98, 66, 255],
2887        [146, 114, 76, 255],
2888    );
2889    b.add_cylinder_segment(
2890        petiole_mid,
2891        petiole_top,
2892        0.0016,
2893        0.0015,
2894        8,
2895        [146, 114, 76, 255],
2896        [156, 134, 88, 255],
2897    );
2898
2899    // 2. Multi-column (6 columns x 32 rows) curved falcate leaf blade
2900    let n_leaf_segs = 32usize;
2901    let n_blade_cols = 6usize;
2902    let leaf_vertex_start = b.positions.len();
2903    let leaf_index_start = b.indices.len();
2904    let mut spine_pts = Vec::with_capacity(n_leaf_segs + 1);
2905    let mut half_widths = Vec::with_capacity(n_leaf_segs + 1);
2906    let mut intra_left_pts = Vec::with_capacity(n_leaf_segs + 1);
2907    let mut intra_right_pts = Vec::with_capacity(n_leaf_segs + 1);
2908
2909    // Helper for leaf surface Z elevation at (frac, signed_u in [-1, 1])
2910    let leaf_surface_z = |frac: f32, signed_u: f32| -> f32 {
2911        let ridge_z = 0.0022 * (frac * PI).sin();
2912        let u_abs = signed_u.abs();
2913        // Raised central midrib with shallow V-cupped sclerophyll lamina and subtle margin undulation
2914        let camber = -0.0016 * u_abs.powf(1.35) * (frac * PI).sin();
2915        let wave = 0.00035 * (frac * PI * 5.0).sin() * u_abs;
2916        ridge_z + camber + wave
2917    };
2918
2919    for s in 0..=n_leaf_segs {
2920        let frac = s as f32 / n_leaf_segs as f32;
2921        let y = (frac - 0.5) * leaf_len;
2922        // Authentic falcate (sickle-shaped) curvature in X
2923        let curve_x = (frac * PI).sin() * leaf_w * 0.58 - (frac * frac) * leaf_w * 0.14;
2924        let mid_z = leaf_surface_z(frac, 0.0);
2925        spine_pts.push([curve_x, y, mid_z]);
2926
2927        // Broadest in basal-to-middle third, long acuminate drip tip
2928        let w = (frac.powf(0.55) * (1.0 - frac).powf(0.78) * 2.35).max(0.025) * leaf_w;
2929        half_widths.push(w);
2930
2931        let intra_u = 0.86_f32;
2932        let iz_l = leaf_surface_z(frac, -intra_u) + 0.00025;
2933        let iz_r = leaf_surface_z(frac, intra_u) + 0.00025;
2934        intra_left_pts.push([curve_x - w * intra_u, y, iz_l]);
2935        intra_right_pts.push([curve_x + w * intra_u, y, iz_r]);
2936    }
2937
2938    // Triangulate the multi-column curved leaf blade
2939    let base_blade_v = b.positions.len() as u32;
2940    for s in 0..=n_leaf_segs {
2941        let frac = s as f32 / n_leaf_segs as f32;
2942        let mid = spine_pts[s];
2943        let w = half_widths[s];
2944
2945        for c in 0..=n_blade_cols {
2946            let u_frac = c as f32 / n_blade_cols as f32;
2947            let signed_u = u_frac * 2.0 - 1.0; // -1.0 (left margin) .. 0.0 (midrib) .. +1.0 (right margin)
2948            let x = mid[0] + signed_u * w;
2949            let y = mid[1];
2950            let z = leaf_surface_z(frac, signed_u);
2951
2952            // Naturalistic sclerophyll olive-sage gradient with warm copper-red tip flush and pale margin rim
2953            let tip_flush = ((frac - 0.72) / 0.28).clamp(0.0, 1.0);
2954            let margin_highlight = signed_u.abs().powi(2);
2955            let r_col = (94.0 + 18.0 * margin_highlight + 52.0 * tip_flush) as u8;
2956            let g_col = (126.0 + 14.0 * margin_highlight - 16.0 * tip_flush) as u8;
2957            let b_col = (96.0 + 10.0 * margin_highlight - 22.0 * tip_flush) as u8;
2958
2959            b.add_vertex(
2960                [x, y, z],
2961                [0.0, 0.0, 1.0],
2962                [u_frac, frac],
2963                [r_col, g_col, b_col, 255],
2964            );
2965        }
2966    }
2967    let stride = (n_blade_cols + 1) as u32;
2968    for s in 0..n_leaf_segs {
2969        for c in 0..n_blade_cols {
2970            let i0 = base_blade_v + (s as u32) * stride + (c as u32);
2971            let i1 = i0 + 1;
2972            let j0 = i0 + stride;
2973            let j1 = j0 + 1;
2974            b.add_quad(i0, j0, j1, i1);
2975        }
2976    }
2977    b.recompute_normals_since(leaf_vertex_start, leaf_index_start);
2978
2979    // 3. Translucent Waxy Cuticle Plates on the Magnified Histological Cutaway Block
2980    // Stepped back by `cut_clamped` so the underlying epidermis and mesophyll are exposed in cutaway view
2981    let cut_x_span = bx_half * (1.0 - cut_clamped * 0.45);
2982    let cut_x_center = block_origin[0] - bx_half * cut_clamped * 0.45;
2983    // Partial coverage keeps both faces of the thin study sheet readable;
2984    // two 225/255 faces would still obscure almost all underlying cells.
2985    // Adaxial (upper, +Z) waxy cuticle sheet
2986    b.add_box_cell(
2987        [cut_x_center, block_origin[1], block_origin[2] + bz_half],
2988        [cut_x_span, by_half, 0.00022],
2989        [212, 228, 216, 100],
2990    );
2991    // Abaxial (lower, -Z) waxy cuticle sheet
2992    b.add_box_cell(
2993        [cut_x_center, block_origin[1], block_origin[2] - bz_half],
2994        [cut_x_span, by_half, 0.00022],
2995        [206, 222, 210, 100],
2996    );
2997    b.end_tissue_layer();
2998
2999    // ------------------------------------------------------------------------
3000    // Part B: Diagnostic Vascular System (Midrib, Intramarginal, Pinnate & Bundle)
3001    // ------------------------------------------------------------------------
3002    b.begin_tissue_layer(
3003        HistologicalTissueLayer::CollateralVascularBundleXylemPhloem,
3004        1,
3005    );
3006    // 1. 3D Primary Midrib following Murray's Law ($r_p^3 = r_1^3 + r_2^3$) tapering from base to apex
3007    for s in 0..n_leaf_segs {
3008        let f0 = s as f32 / n_leaf_segs as f32;
3009        let f1 = (s + 1) as f32 / n_leaf_segs as f32;
3010        let r0 = 0.00145 * (1.0 - f0 * 0.78).cbrt();
3011        let r1 = 0.00145 * (1.0 - f1 * 0.78).cbrt();
3012
3013        b.add_cylinder_segment(
3014            spine_pts[s],
3015            spine_pts[s + 1],
3016            r0,
3017            r1,
3018            6,
3019            [184, 192, 146, 255],
3020            [176, 186, 140, 255],
3021        );
3022    }
3023
3024    // 2. Continuous Myrtaceae Intramarginal Veins + Curved Pinnate Secondaries + Reticulate Tertiaries
3025    for s in 0..n_leaf_segs {
3026        let r_intra = 0.00038_f32;
3027        b.add_cylinder_segment(
3028            intra_left_pts[s],
3029            intra_left_pts[s + 1],
3030            r_intra,
3031            r_intra,
3032            4,
3033            [164, 178, 134, 255],
3034            [164, 178, 134, 255],
3035        );
3036        b.add_cylinder_segment(
3037            intra_right_pts[s],
3038            intra_right_pts[s + 1],
3039            r_intra,
3040            r_intra,
3041            4,
3042            [164, 178, 134, 255],
3043            [164, 178, 134, 255],
3044        );
3045
3046        // Pinnate secondary lateral veins diverging forward (~55 deg) from midrib to intramarginal vein
3047        if s >= 2 && s + 2 <= n_leaf_segs && s % 2 == 0 {
3048            let s_target = (s + 2).min(n_leaf_segs);
3049            let f_start = s as f32 / n_leaf_segs as f32;
3050            let f_end = s_target as f32 / n_leaf_segs as f32;
3051            let f_mid = 0.5 * (f_start + f_end);
3052            let w_mid = 0.5 * (half_widths[s] + half_widths[s_target]);
3053            let mid_pt = spine_pts[s];
3054
3055            // Left curved secondary vein (2 segments)
3056            let p_il_end = intra_left_pts[s_target];
3057            let p_il_ctrl = [
3058                0.5 * (mid_pt[0] + p_il_end[0]) - w_mid * 0.06,
3059                0.5 * (mid_pt[1] + p_il_end[1]) + 0.0012,
3060                leaf_surface_z(f_mid, -0.45) + 0.00025,
3061            ];
3062            let r_sec = 0.00046_f32 * (1.0 - f_start * 0.45);
3063            b.add_cylinder_segment(
3064                mid_pt,
3065                p_il_ctrl,
3066                r_sec,
3067                r_sec * 0.82,
3068                4,
3069                [174, 184, 140, 255],
3070                [166, 176, 132, 255],
3071            );
3072            b.add_cylinder_segment(
3073                p_il_ctrl,
3074                p_il_end,
3075                r_sec * 0.82,
3076                r_sec * 0.65,
3077                4,
3078                [166, 176, 132, 255],
3079                [158, 170, 126, 255],
3080            );
3081
3082            // Right curved secondary vein (2 segments)
3083            let p_ir_end = intra_right_pts[s_target];
3084            let p_ir_ctrl = [
3085                0.5 * (mid_pt[0] + p_ir_end[0]) + w_mid * 0.06,
3086                0.5 * (mid_pt[1] + p_ir_end[1]) + 0.0012,
3087                leaf_surface_z(f_mid, 0.45) + 0.00025,
3088            ];
3089            b.add_cylinder_segment(
3090                mid_pt,
3091                p_ir_ctrl,
3092                r_sec,
3093                r_sec * 0.82,
3094                4,
3095                [174, 184, 140, 255],
3096                [166, 176, 132, 255],
3097            );
3098            b.add_cylinder_segment(
3099                p_ir_ctrl,
3100                p_ir_end,
3101                r_sec * 0.82,
3102                r_sec * 0.65,
3103                4,
3104                [166, 176, 132, 255],
3105                [158, 170, 126, 255],
3106            );
3107
3108            // Tertiary reticulate cross-veinlets forming closed areoles between adjacent secondaries
3109            if s + 4 <= n_leaf_segs {
3110                let f_next = (s + 3) as f32 / n_leaf_segs as f32;
3111                let p_tert_l = [
3112                    spine_pts[s + 2][0] - half_widths[s + 2] * 0.52,
3113                    spine_pts[s + 2][1],
3114                    leaf_surface_z(f_next, -0.52) + 0.0002,
3115                ];
3116                let p_tert_r = [
3117                    spine_pts[s + 2][0] + half_widths[s + 2] * 0.52,
3118                    spine_pts[s + 2][1],
3119                    leaf_surface_z(f_next, 0.52) + 0.0002,
3120                ];
3121                b.add_cylinder_segment(
3122                    p_il_ctrl,
3123                    p_tert_l,
3124                    0.00024,
3125                    0.00022,
3126                    4,
3127                    [154, 166, 122, 255],
3128                    [154, 166, 122, 255],
3129                );
3130                b.add_cylinder_segment(
3131                    p_ir_ctrl,
3132                    p_tert_r,
3133                    0.00024,
3134                    0.00022,
3135                    4,
3136                    [154, 166, 122, 255],
3137                    [154, 166, 122, 255],
3138                );
3139            }
3140        }
3141    }
3142
3143    // 3. Magnified Collateral Vascular Bundle inside the Histological Cutaway Window
3144    // Oriented parallel to the leaf blade: adaxial xylem vessels on +Z, abaxial phloem sieve tubes on -Z
3145    let vein_center = [block_origin[0] - 0.0032, block_origin[1], block_origin[2]];
3146    for vx in [-0.0011_f32, 0.0_f32, 0.0011_f32] {
3147        // Adaxial (+Z) lignified xylem tracheary vessels
3148        b.add_cylinder_segment(
3149            [
3150                vein_center[0] + vx,
3151                vein_center[1] - by_half * 0.88,
3152                vein_center[2] + 0.0008,
3153            ],
3154            [
3155                vein_center[0] + vx,
3156                vein_center[1] + by_half * 0.88,
3157                vein_center[2] + 0.0008,
3158            ],
3159            0.00062,
3160            0.00062,
3161            8,
3162            [198, 178, 124, 255],
3163            [188, 168, 114, 255],
3164        );
3165        // Abaxial (-Z) phloem sieve tubes and companion cells
3166        b.add_cylinder_segment(
3167            [
3168                vein_center[0] + vx * 0.85,
3169                vein_center[1] - by_half * 0.88,
3170                vein_center[2] - 0.0008,
3171            ],
3172            [
3173                vein_center[0] + vx * 0.85,
3174                vein_center[1] + by_half * 0.88,
3175                vein_center[2] - 0.0008,
3176            ],
3177            0.00052,
3178            0.00052,
3179            8,
3180            [172, 138, 92, 255],
3181            [164, 130, 86, 255],
3182        );
3183    }
3184    b.end_tissue_layer();
3185
3186    // ------------------------------------------------------------------------
3187    // Part C: Magnified 3D Histological Cellular Cutaway Block (Parallel to Leaf)
3188    // ------------------------------------------------------------------------
3189    // Layer 2: Upper (+Z) & Lower (-Z) Epidermis Pavement Cells
3190    b.begin_tissue_layer(HistologicalTissueLayer::UpperAndLowerEpidermis, 2);
3191    let nx_cells = 7usize;
3192    let ny_cells = 6usize;
3193    let cell_w = (bx_half * 2.0) / (nx_cells as f32);
3194    let cell_h = (by_half * 2.0) / (ny_cells as f32);
3195
3196    for ix in 0..nx_cells {
3197        // Step back upper epidermis on the right side when cutaway_01 > 0 to reveal palisade beneath
3198        let x_frac = (ix as f32 + 0.5) / (nx_cells as f32);
3199        let skip_for_cutaway = x_frac > (1.0 - cut_clamped * 0.55);
3200
3201        for iy in 0..ny_cells {
3202            let cx = block_origin[0] - bx_half + (ix as f32 + 0.5) * cell_w;
3203            let cy = block_origin[1] - by_half + (iy as f32 + 0.5) * cell_h;
3204            // Reserve stomatal pore openings
3205            if (ix == 2 && iy == 1) || (ix == 4 && iy == 3) || (ix == 2 && iy == 4) {
3206                continue;
3207            }
3208            if !skip_for_cutaway {
3209                // Adaxial (upper, +Z) epidermal pavement cell
3210                b.add_box_cell(
3211                    [cx, cy, block_origin[2] + bz_half - 0.00065],
3212                    [cell_w * 0.46, cell_h * 0.46, 0.00038],
3213                    [118, 158, 106, 255],
3214                );
3215            }
3216            // Abaxial (lower, -Z) epidermal pavement cell
3217            b.add_box_cell(
3218                [cx, cy, block_origin[2] - bz_half + 0.00065],
3219                [cell_w * 0.46, cell_h * 0.46, 0.00038],
3220                [112, 152, 100, 255],
3221            );
3222        }
3223    }
3224    b.end_tissue_layer();
3225
3226    // Layer 3: Amphistomatic Stomatal Guard Cells (sunken on BOTH +Z adaxial and -Z abaxial faces)
3227    b.begin_tissue_layer(HistologicalTissueLayer::AmphistomaticStomatalGuardCells, 3);
3228    let stomata_grid = [(2usize, 1usize), (4usize, 3usize), (2usize, 4usize)];
3229    for &(ix, iy) in &stomata_grid {
3230        let cx = block_origin[0] - bx_half + (ix as f32 + 0.5) * cell_w;
3231        let cy = block_origin[1] - by_half + (iy as f32 + 0.5) * cell_h;
3232        for &is_adaxial in &[true, false] {
3233            let z_sign = if is_adaxial { 1.0_f32 } else { -1.0_f32 };
3234            let z_guard = block_origin[2] + z_sign * (bz_half - 0.00075);
3235            let col_guard = [90, 140, 80, 255];
3236            // Paired kidney-shaped (reniform) guard cells flanking the stomatal pore
3237            b.add_ellipsoid(
3238                [cx - 0.00055, cy, z_guard],
3239                [0.00048, 0.00095, 0.00042],
3240                4,
3241                6,
3242                col_guard,
3243            );
3244            b.add_ellipsoid(
3245                [cx + 0.00055, cy, z_guard],
3246                [0.00048, 0.00095, 0.00042],
3247                4,
3248                6,
3249                col_guard,
3250            );
3251            // Substomatal vapour chamber cavity beneath the guard cells
3252            b.add_ellipsoid(
3253                [cx, cy, block_origin[2] + z_sign * (bz_half - 0.00145)],
3254                [0.00095, 0.0011, 0.00045],
3255                3,
3256                5,
3257                [68, 96, 64, 185],
3258            );
3259        }
3260    }
3261    b.end_tissue_layer();
3262
3263    // Layer 4: Isobilateral Palisade Mesophyll (Chlorenchyma columns under BOTH +Z and -Z faces!)
3264    b.begin_tissue_layer(HistologicalTissueLayer::IsobilateralPalisadeMesophyll, 4);
3265    let pal_nx = 9usize;
3266    let pal_ny = 7usize;
3267    let pal_w = (bx_half * 2.0) / (pal_nx as f32);
3268    let pal_h = (by_half * 2.0) / (pal_ny as f32);
3269
3270    for px in 0..pal_nx {
3271        for py in 0..pal_ny {
3272            let cx = block_origin[0] - bx_half + (px as f32 + 0.5) * pal_w;
3273            let cy = block_origin[1] - by_half + (py as f32 + 0.5) * pal_h;
3274            // Leave clear structural channels for the vascular bundle (left-center) and oil gland (right-center)
3275            let dist_vein = (cx - vein_center[0]).abs();
3276            let gland_center_x = block_origin[0] + 0.0048;
3277            let dist_gland =
3278                ((cx - gland_center_x).powi(2) + (cy - block_origin[1]).powi(2)).sqrt();
3279            if dist_vein < 0.0024 || dist_gland < 0.0038 {
3280                continue;
3281            }
3282            // Adaxial (+Z) palisade chlorenchyma columns oriented perpendicular to the leaf blade (along Z)
3283            b.add_cylinder_segment(
3284                [cx, cy, block_origin[2] + bz_half - 0.0011],
3285                [cx, cy, block_origin[2] + 0.0012],
3286                pal_w * 0.36,
3287                pal_w * 0.36,
3288                6,
3289                [60, 124, 54, 255],
3290                [50, 108, 46, 255],
3291            );
3292            // Abaxial (-Z) palisade chlorenchyma columns (diagnostic isobilateral eucalypt leaf symmetry)
3293            b.add_cylinder_segment(
3294                [cx, cy, block_origin[2] - 0.0012],
3295                [cx, cy, block_origin[2] - bz_half + 0.0011],
3296                pal_w * 0.36,
3297                pal_w * 0.36,
3298                6,
3299                [50, 108, 46, 255],
3300                [60, 124, 54, 255],
3301            );
3302        }
3303    }
3304    b.end_tissue_layer();
3305
3306    // Layer 5: Spongy Mesophyll Parenchyma & Intercellular Air Spaces
3307    b.begin_tissue_layer(HistologicalTissueLayer::SpongyMesophyllAndAirSpaces, 5);
3308    for sx in 0..7 {
3309        for sy in 0..5 {
3310            let cx = block_origin[0] - bx_half * 0.84 + (sx as f32 * 0.0044);
3311            let cy = block_origin[1] - by_half * 0.82 + (sy as f32 * 0.0052);
3312            let dist_vein = (cx - vein_center[0]).abs();
3313            let dist_gland =
3314                ((cx - (block_origin[0] + 0.0048)).powi(2) + (cy - block_origin[1]).powi(2)).sqrt();
3315            if dist_vein < 0.0024 || dist_gland < 0.0038 {
3316                continue;
3317            }
3318            let z_jitter = ((sx + sy) % 3) as f32 * 0.00035 - 0.00035;
3319            b.add_ellipsoid(
3320                [cx, cy, block_origin[2] + z_jitter],
3321                [0.0012, 0.0011, 0.00075],
3322                4,
3323                6,
3324                [96, 148, 90, 235],
3325            );
3326        }
3327    }
3328    b.end_tissue_layer();
3329
3330    // Layer 7: Sclerenchyma Bundle Sheath Girders (Lignified I-beam fiber columns along Z)
3331    b.begin_tissue_layer(HistologicalTissueLayer::SclerenchymaBundleSheathGirders, 6);
3332    // Adaxial (+Z) sclerenchyma girder anchoring vascular bundle to upper epidermis
3333    b.add_box_cell(
3334        [vein_center[0], block_origin[1], block_origin[2] + 0.0026],
3335        [0.0019, by_half * 0.86, 0.0012],
3336        [210, 194, 138, 255],
3337    );
3338    // Abaxial (-Z) sclerenchyma girder anchoring vascular bundle to lower epidermis
3339    b.add_box_cell(
3340        [vein_center[0], block_origin[1], block_origin[2] - 0.0026],
3341        [0.0019, by_half * 0.86, 0.0012],
3342        [204, 188, 132, 255],
3343    );
3344    b.end_tissue_layer();
3345
3346    // Layer 8: Schizogenous Essential Oil Gland Cavities (in Histological Block + Lamina Areoles)
3347    b.begin_tissue_layer(HistologicalTissueLayer::SchizogenousEssentialOilGland, 7);
3348    // 1. Primary magnified schizogenous oil gland cavity inside the histological cutaway block
3349    let gland_center = [block_origin[0] + 0.0048, block_origin[1], block_origin[2]];
3350    b.add_ellipsoid(
3351        gland_center,
3352        [0.0028, 0.0028, 0.0026],
3353        7,
3354        10,
3355        [244, 214, 84, 242], // Translucent golden 1,8-cineole essential oil droplet
3356    );
3357    // Ring of 10 flattened secretory epithelial cells lining the schizogenous cavity
3358    for ep in 0..10 {
3359        let a = (ep as f32) * (2.0 * PI / 10.0);
3360        let ep_pos = [
3361            gland_center[0] + a.cos() * 0.0031,
3362            gland_center[1] + a.sin() * 0.0031,
3363            gland_center[2],
3364        ];
3365        b.add_ellipsoid(
3366            ep_pos,
3367            [0.00065, 0.00095, 0.0014],
3368            3,
3369            5,
3370            [182, 206, 132, 215],
3371        );
3372    }
3373
3374    // 2. Punctate translucent golden oil glands embedded across the macroscopic leaf lamina areoles
3375    for s in (3..n_leaf_segs - 3).step_by(3) {
3376        let frac = s as f32 / n_leaf_segs as f32;
3377        let mid = spine_pts[s];
3378        let w = half_widths[s];
3379        for &side in &[-0.55_f32, 0.55_f32] {
3380            let gx = mid[0] + side * w;
3381            let gy = mid[1];
3382            let gz = leaf_surface_z(frac, side) + 0.00018;
3383            b.add_ellipsoid(
3384                [gx, gy, gz],
3385                [0.00065, 0.00065, 0.00042],
3386                3,
3387                5,
3388                [238, 206, 78, 235],
3389            );
3390        }
3391    }
3392    b.end_tissue_layer();
3393
3394    let recipe_urn = format!(
3395        "urn:qualia:botanical:scale4:{species_id}:histology:cutaway={:.2}",
3396        cutaway_01
3397    );
3398    let container_bytes = seal_botanical_organ_10d(
3399        BotanicalEducationScale::Scale4FoliarVenationAndCellularHistology,
3400        &b.positions,
3401        &b.normals,
3402        &b.colors,
3403        &b.uvs,
3404        &b.indices,
3405        &b.slices,
3406        &recipe_urn,
3407        None,
3408    )?;
3409
3410    let organ = CompiledBotanicalOrgan10d {
3411        scale: BotanicalEducationScale::Scale4FoliarVenationAndCellularHistology,
3412        vertices: b.positions,
3413        normals: b.normals,
3414        uvs: b.uvs,
3415        colors: b.colors,
3416        material_indices: b.material_indices,
3417        indices: b.indices,
3418        tissue_slices: b.slices,
3419        container_bytes,
3420    };
3421
3422    organ.verify_all()?;
3423    Ok(organ)
3424}
3425
3426// ============================================================================
3427// 8. Disk Asset Serializer for Corymbia aparrerinja
3428// ============================================================================
3429
3430/// Write all upgraded educational-grade `.10d` study files to disk for *Corymbia aparrerinja*.
3431///
3432/// Upgrades:
3433/// - `leaf-study-blade.10d`
3434/// - `leaf-study-midrib.10d`
3435/// - `bark-study-surface.10d`
3436/// - `stem-anatomy-wedge.10d`
3437/// - `flower-dissection.10d`
3438/// - `gumnut-dissection.10d`
3439/// - `leaf-anatomy-cutaway.10d`
3440/// - `whole-organism-roots.10d`
3441#[cfg(not(target_arch = "wasm32"))]
3442pub fn write_corymbia_educational_assets_to_disk(repo_root: &Path) -> std::io::Result<usize> {
3443    let target_dir = repo_root.join("assets/models/corymbia-aparrerinja/10d");
3444    fs::create_dir_all(&target_dir)?;
3445
3446    let target_dir_root = repo_root.join("assets/models/corymbia-aparrerinja");
3447
3448    let organ_scale1 =
3449        build_scale1_whole_organism_10d("corymbia-aparrerinja", DevelopmentalStage::Mature)
3450            .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))?;
3451
3452    let organ_scale2 = build_scale2_stem_bark_wedge_10d("corymbia-aparrerinja", 0.0)
3453        .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))?;
3454
3455    let organ_scale3 =
3456        build_scale3_floral_and_gumnut_dissection_10d("corymbia-aparrerinja", 0.75, 0.5)
3457            .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))?;
3458
3459    let organ_scale4 = build_scale4_leaf_venation_and_histology_10d("corymbia-aparrerinja", 0.5)
3460        .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))?;
3461
3462    let files_to_write: [(&str, &[u8]); 8] = [
3463        ("whole-organism-roots.10d", &organ_scale1.container_bytes),
3464        ("stem-anatomy-wedge.10d", &organ_scale2.container_bytes),
3465        ("bark-study-surface.10d", &organ_scale2.container_bytes),
3466        ("flower-dissection.10d", &organ_scale3.container_bytes),
3467        ("gumnut-dissection.10d", &organ_scale3.container_bytes),
3468        ("leaf-anatomy-cutaway.10d", &organ_scale4.container_bytes),
3469        ("leaf-study-blade.10d", &organ_scale4.container_bytes),
3470        ("leaf-study-midrib.10d", &organ_scale4.container_bytes),
3471    ];
3472
3473    let mut total_bytes = 0usize;
3474    for (filename, bytes) in files_to_write {
3475        // Write to assets/models/corymbia-aparrerinja/10d/<filename>
3476        let path_10d = target_dir.join(filename);
3477        let mut f1 = fs::File::create(&path_10d)?;
3478        f1.write_all(bytes)?;
3479
3480        // Also write to assets/models/corymbia-aparrerinja/<filename>
3481        let path_root = target_dir_root.join(filename);
3482        let mut f2 = fs::File::create(&path_root)?;
3483        f2.write_all(bytes)?;
3484
3485        total_bytes += bytes.len();
3486    }
3487
3488    Ok(total_bytes)
3489}
3490
3491// ============================================================================
3492// 9. Comprehensive Verification Tests
3493// ============================================================================
3494
3495#[cfg(test)]
3496mod tests {
3497    use super::*;
3498
3499    #[test]
3500    fn test_scale1_whole_organism_high_density() {
3501        let organ =
3502            build_scale1_whole_organism_10d("corymbia-aparrerinja", DevelopmentalStage::Mature)
3503                .expect("Scale 1 generator must succeed");
3504
3505        assert!(
3506            organ.vertex_count() >= 2500,
3507            "Scale 1 must produce high density geometry (>= 2500 verts), got {}",
3508            organ.vertex_count()
3509        );
3510        assert!(
3511            organ.triangle_count() >= 2000,
3512            "Scale 1 triangle count too low: {}",
3513            organ.triangle_count()
3514        );
3515
3516        // Verify root tissues present
3517        assert!(
3518            organ
3519                .tissue_layer_slice(HistologicalTissueLayer::PhellogenCorkCambium)
3520                .is_some(),
3521            "Scale 1 must contain subterranean root architecture"
3522        );
3523        assert!(
3524            organ
3525                .tissue_layer_slice(HistologicalTissueLayer::OuterRhytidome)
3526                .is_some(),
3527            "Scale 1 must contain chalk-white outer rhytidome bole"
3528        );
3529        assert!(
3530            organ
3531                .tissue_layer_slice(HistologicalTissueLayer::WaxyCuticle)
3532                .is_some(),
3533            "Scale 1 must contain pendulous foliage"
3534        );
3535
3536        organ
3537            .verify_all()
3538            .expect("Scale 1 .10d container must pass verify_all()");
3539    }
3540
3541    #[test]
3542    fn test_scale2_stem_wedge_dissection_and_peel() {
3543        let organ_solid = build_scale2_stem_bark_wedge_10d("corymbia-aparrerinja", 0.0)
3544            .expect("Scale 2 solid wedge must succeed");
3545        let organ_peeled = build_scale2_stem_bark_wedge_10d("corymbia-aparrerinja", 1.0)
3546            .expect("Scale 2 peeled wedge must succeed");
3547
3548        assert!(
3549            organ_solid.vertex_count() >= 1800,
3550            "Scale 2 must produce >= 1800 verts, got {}",
3551            organ_solid.vertex_count()
3552        );
3553
3554        // All 6 concentric stem/bark layers must be populated with non-empty slices!
3555        let stem_layers = [
3556            HistologicalTissueLayer::OuterRhytidome,
3557            HistologicalTissueLayer::PhellogenCorkCambium,
3558            HistologicalTissueLayer::SecondaryPhloemAndKinoDucts,
3559            HistologicalTissueLayer::VascularCambium,
3560            HistologicalTissueLayer::SapwoodSecondaryXylem,
3561            HistologicalTissueLayer::HeartwoodAndPith,
3562        ];
3563
3564        for layer in stem_layers {
3565            let slice = organ_solid
3566                .tissue_layer_slice(layer)
3567                .unwrap_or_else(|| panic!("Missing stem layer: {:?}", layer));
3568            assert!(slice.vertex_count > 0, "Empty vertex count for {:?}", layer);
3569            assert!(slice.index_count > 0, "Empty index count for {:?}", layer);
3570        }
3571
3572        // Peeled version must have displaced coordinates in the outer rhytidome layer
3573        let outer_slice = organ_solid
3574            .tissue_layer_slice(HistologicalTissueLayer::OuterRhytidome)
3575            .expect("OuterRhytidome slice");
3576        assert_ne!(
3577            organ_solid.vertices[outer_slice.vertex_start as usize],
3578            organ_peeled.vertices[outer_slice.vertex_start as usize],
3579            "Peeled stem wedge must have displaced vertices"
3580        );
3581
3582        organ_solid
3583            .verify_all()
3584            .expect("Solid Scale 2 container must pass verify_all()");
3585        organ_peeled
3586            .verify_all()
3587            .expect("Peeled Scale 2 container must pass verify_all()");
3588    }
3589
3590    #[test]
3591    fn test_scale3_floral_and_gumnut_dissection() {
3592        let organ = build_scale3_floral_and_gumnut_dissection_10d("corymbia-aparrerinja", 0.8, 0.5)
3593            .expect("Scale 3 generator must succeed");
3594
3595        assert!(
3596            organ.vertex_count() >= 2200,
3597            "Scale 3 must produce >= 2200 verts, got {}",
3598            organ.vertex_count()
3599        );
3600
3601        // All 9 floral/fruit layers must be populated with non-empty slices!
3602        let floral_layers = [
3603            HistologicalTissueLayer::PeduncleAndPedicel,
3604            HistologicalTissueLayer::HypanthiumCalyxTube,
3605            HistologicalTissueLayer::OperculumCalyptra,
3606            HistologicalTissueLayer::StaminalRingFilaments,
3607            HistologicalTissueLayer::VersatileAnthersAndPollen,
3608            HistologicalTissueLayer::GynoeciumStyleStigma,
3609            HistologicalTissueLayer::OvaryLoculesAndOvules,
3610            HistologicalTissueLayer::WoodyPericarpAndDehiscingValves,
3611            HistologicalTissueLayer::FertileWingedSeedsAndChaff,
3612        ];
3613
3614        for layer in floral_layers {
3615            let slice = organ
3616                .tissue_layer_slice(layer)
3617                .unwrap_or_else(|| panic!("Missing floral layer: {:?}", layer));
3618            assert!(slice.vertex_count > 0, "Empty vertex count for {:?}", layer);
3619            assert!(slice.index_count > 0, "Empty index count for {:?}", layer);
3620        }
3621
3622        organ
3623            .verify_all()
3624            .expect("Scale 3 container must pass verify_all()");
3625    }
3626
3627    #[test]
3628    fn test_scale4_leaf_venation_and_cellular_histology() {
3629        let organ = build_scale4_leaf_venation_and_histology_10d("corymbia-aparrerinja", 0.5)
3630            .expect("Scale 4 generator must succeed");
3631
3632        assert!(
3633            organ.vertex_count() >= 2000,
3634            "Scale 4 must produce >= 2000 verts, got {}",
3635            organ.vertex_count()
3636        );
3637
3638        // All 8 foliar/cellular layers must be populated with non-empty slices!
3639        let foliar_layers = [
3640            HistologicalTissueLayer::WaxyCuticle,
3641            HistologicalTissueLayer::UpperAndLowerEpidermis,
3642            HistologicalTissueLayer::AmphistomaticStomatalGuardCells,
3643            HistologicalTissueLayer::IsobilateralPalisadeMesophyll,
3644            HistologicalTissueLayer::SpongyMesophyllAndAirSpaces,
3645            HistologicalTissueLayer::CollateralVascularBundleXylemPhloem,
3646            HistologicalTissueLayer::SclerenchymaBundleSheathGirders,
3647            HistologicalTissueLayer::SchizogenousEssentialOilGland,
3648        ];
3649
3650        for layer in foliar_layers {
3651            let slice = organ
3652                .tissue_layer_slice(layer)
3653                .unwrap_or_else(|| panic!("Missing foliar layer: {:?}", layer));
3654            assert!(slice.vertex_count > 0, "Empty vertex count for {:?}", layer);
3655            assert!(slice.index_count > 0, "Empty index count for {:?}", layer);
3656        }
3657
3658        organ
3659            .verify_all()
3660            .expect("Scale 4 container must pass verify_all()");
3661    }
3662
3663    #[test]
3664    fn test_all_23_tissue_layers_covered_with_non_empty_slices() {
3665        let organ1 =
3666            build_scale1_whole_organism_10d("corymbia-aparrerinja", DevelopmentalStage::Mature)
3667                .unwrap();
3668        let organ2 = build_scale2_stem_bark_wedge_10d("corymbia-aparrerinja", 0.0).unwrap();
3669        let organ3 =
3670            build_scale3_floral_and_gumnut_dissection_10d("corymbia-aparrerinja", 0.5, 0.5)
3671                .unwrap();
3672        let organ4 =
3673            build_scale4_leaf_venation_and_histology_10d("corymbia-aparrerinja", 0.5).unwrap();
3674
3675        let all_layers = [
3676            HistologicalTissueLayer::OuterRhytidome,
3677            HistologicalTissueLayer::PhellogenCorkCambium,
3678            HistologicalTissueLayer::SecondaryPhloemAndKinoDucts,
3679            HistologicalTissueLayer::VascularCambium,
3680            HistologicalTissueLayer::SapwoodSecondaryXylem,
3681            HistologicalTissueLayer::HeartwoodAndPith,
3682            HistologicalTissueLayer::PeduncleAndPedicel,
3683            HistologicalTissueLayer::HypanthiumCalyxTube,
3684            HistologicalTissueLayer::OperculumCalyptra,
3685            HistologicalTissueLayer::StaminalRingFilaments,
3686            HistologicalTissueLayer::VersatileAnthersAndPollen,
3687            HistologicalTissueLayer::GynoeciumStyleStigma,
3688            HistologicalTissueLayer::OvaryLoculesAndOvules,
3689            HistologicalTissueLayer::WoodyPericarpAndDehiscingValves,
3690            HistologicalTissueLayer::FertileWingedSeedsAndChaff,
3691            HistologicalTissueLayer::WaxyCuticle,
3692            HistologicalTissueLayer::UpperAndLowerEpidermis,
3693            HistologicalTissueLayer::AmphistomaticStomatalGuardCells,
3694            HistologicalTissueLayer::IsobilateralPalisadeMesophyll,
3695            HistologicalTissueLayer::SpongyMesophyllAndAirSpaces,
3696            HistologicalTissueLayer::CollateralVascularBundleXylemPhloem,
3697            HistologicalTissueLayer::SclerenchymaBundleSheathGirders,
3698            HistologicalTissueLayer::SchizogenousEssentialOilGland,
3699        ];
3700
3701        assert_eq!(all_layers.len(), 23);
3702
3703        for layer in all_layers {
3704            let found = organ1
3705                .tissue_layer_slice(layer)
3706                .or_else(|| organ2.tissue_layer_slice(layer))
3707                .or_else(|| organ3.tissue_layer_slice(layer))
3708                .or_else(|| organ4.tissue_layer_slice(layer));
3709
3710            assert!(
3711                found.is_some(),
3712                "Layer {:?} must be populated in at least one educational scale",
3713                layer
3714            );
3715            let slice = found.unwrap();
3716            assert!(
3717                slice.vertex_count > 0,
3718                "Layer {:?} vertex count must be > 0",
3719                layer
3720            );
3721            assert!(
3722                slice.index_count > 0,
3723                "Layer {:?} index count must be > 0",
3724                layer
3725            );
3726            assert!(
3727                !slice.plant_ontology_id.is_empty(),
3728                "Layer {:?} must have a PO ID",
3729                layer
3730            );
3731        }
3732    }
3733
3734    #[test]
3735    fn test_leaf_vascular_skeleton_murray_law_conductance_positive() {
3736        let profile = LeafEconomicsProfile::eucalyptus_sclerophyll();
3737        let skeleton = LeafVascularSkeleton::new(profile, 1.25);
3738
3739        assert!(
3740            skeleton.edge_count > 0,
3741            "Vascular skeleton must contain edges"
3742        );
3743        for i in 0..skeleton.edge_count {
3744            let edge = skeleton.edges[i];
3745            assert!(
3746                edge.radius_mm > 0.0,
3747                "Edge {} radius must be positive, got {}",
3748                i,
3749                edge.radius_mm
3750            );
3751            assert!(
3752                edge.conductance > 0.0,
3753                "Edge {} Murray's Law hydraulic conductance must be positive, got {}",
3754                i,
3755                edge.conductance
3756            );
3757        }
3758    }
3759}