imaginu 0.1.0

AI-drivable procedural 3D asset compiler: JSON recipes -> beautiful game-ready GLB for Babylon.js
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
//! Recipe schema — the JSON surface an AI agent writes. Small, forgiving
//! (everything except `kind` has a default), deterministic via `seed`.

use serde::{Deserialize, Serialize};

use crate::gltf::Asset;
use crate::palette;

fn d_seed() -> u64 {
    1
}
fn d_palette() -> String {
    "verdant".into()
}
fn d_true() -> bool {
    true
}
/// exposed for the custom-DSL serde defaults
pub fn d_true_pub() -> bool {
    true
}

#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum TreeStyle {
    #[default]
    Oak,
    Pine,
    Palm,
    Dead,
}

#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum PropKind {
    #[default]
    Barrel,
    Crate,
    Lantern,
    Campfire,
}

#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum CharacterClass {
    #[default]
    Villager,
    Warrior,
    Mage,
    Rogue,
}

#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum TerrainShape {
    #[default]
    Hills,
    Mountains,
    Island,
    Archipelago,
    Canyon,
    Mesa,
    Crater,
    Valley,
    Dunes,
}

#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct TerrainParams {
    #[serde(default = "d_seed")]
    pub seed: u64,
    #[serde(default = "d_terrain_size")]
    pub size: f32,
    #[serde(default = "d_terrain_res")]
    pub resolution: u32,
    #[serde(default = "d_one")]
    pub mountainousness: f32,
    /// 0 disables water; fraction of the height range that floods.
    #[serde(default = "d_water")]
    pub water_level: f32,
    #[serde(default = "d_true")]
    pub scatter: bool,
    /// Macro-shape mask applied to the heightfield.
    #[serde(default)]
    pub shape: TerrainShape,
    /// World-space chunk offset: adjacent chunks with matching offsets tile
    /// seamlessly (noise is sampled in world coordinates).
    #[serde(default)]
    pub offset_x: f32,
    #[serde(default)]
    pub offset_z: f32,
    /// Quantize heights into steps (0 = off). ~6-12 gives stepped mesas.
    #[serde(default)]
    pub terrace: f32,
    /// Diorama side walls + bottom. Turn OFF for tiled world chunks.
    #[serde(default = "d_true")]
    pub skirt: bool,
    /// Hydraulic erosion strength 0..1 (deterministic droplet simulation).
    /// Chunk-local — do not combine with seamless tiling.
    #[serde(default)]
    pub erosion: f32,
    /// Number of rivers traced downhill from high springs (carved channel
    /// + water ribbon). Chunk-local like erosion.
    #[serde(default)]
    pub rivers: u32,
    /// Dirt paths/roads: splines flattened into the terrain.
    #[serde(default)]
    pub paths: Vec<PathSpec>,
    /// Optional baked texture over the terrain (e.g. rock strata on cliffs).
    #[serde(default)]
    pub texture: Option<crate::texture::TextureSpec>,
    /// Scatter density multiplier (1.0 = default coverage).
    #[serde(default = "d_one")]
    pub scatter_density: f32,
}

#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct PathSpec {
    /// Waypoints in local chunk XZ coordinates.
    pub points: Vec<[f32; 2]>,
    #[serde(default = "d_path_w")]
    pub width: f32,
}
fn d_path_w() -> f32 {
    2.0
}

fn d_terrain_size() -> f32 {
    48.0
}
fn d_terrain_res() -> u32 {
    110
}
fn d_one() -> f32 {
    1.0
}
fn d_water() -> f32 {
    0.28
}

#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct TreeParams {
    #[serde(default = "d_seed")]
    pub seed: u64,
    #[serde(default)]
    pub style: TreeStyle,
    #[serde(default = "d_tree_h")]
    pub height: f32,
}
fn d_tree_h() -> f32 {
    6.0
}

#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct RockParams {
    #[serde(default = "d_seed")]
    pub seed: u64,
    #[serde(default = "d_one")]
    pub size: f32,
    #[serde(default = "d_jag")]
    pub jaggedness: f32,
}
fn d_jag() -> f32 {
    0.6
}

#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct CrystalParams {
    #[serde(default = "d_seed")]
    pub seed: u64,
    #[serde(default = "d_one")]
    pub size: f32,
    #[serde(default = "d_crystal_count")]
    pub count: u32,
}
fn d_crystal_count() -> u32 {
    7
}

#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct BuildingParams {
    #[serde(default = "d_seed")]
    pub seed: u64,
    #[serde(default = "d_bwidth")]
    pub width: f32,
    #[serde(default = "d_floors")]
    pub floors: u32,
}
fn d_bwidth() -> f32 {
    6.0
}
fn d_floors() -> u32 {
    1
}

#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct PropParams {
    #[serde(default = "d_seed")]
    pub seed: u64,
    #[serde(default)]
    pub prop: PropKind,
    #[serde(default = "d_one")]
    pub size: f32,
}

#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct CharacterParams {
    #[serde(default = "d_seed")]
    pub seed: u64,
    #[serde(default)]
    pub class: CharacterClass,
    #[serde(default = "d_char_h")]
    pub height: f32,
    #[serde(default = "d_one")]
    pub bulk: f32,
    #[serde(default = "d_true")]
    pub animate: bool,
    /// short | ponytail | bun | bald | long | topknot (default: seeded pick)
    #[serde(default)]
    pub hair: Option<String>,
    /// none | mustache | short | long — ribbon-card facial hair.
    #[serde(default)]
    pub beard: Option<String>,
    /// Override hair/beard color (#rrggbb), e.g. "#e8e6e0" for elders.
    #[serde(default)]
    pub hair_color: Option<String>,
    /// 0..=3 light→dark (default: seeded pick)
    #[serde(default)]
    pub skin_tone: Option<u32>,
    /// Export facial morph targets (smile, blink, angry, surprised).
    #[serde(default = "d_true")]
    pub expressions: bool,
    /// Painted garment stack: robe (layered under-robe + open coat + sash +
    /// mantle) | tunic (belted knee tunic) | plain (bare v2 body).
    #[serde(default)]
    pub outfit: Option<String>,
    /// 0..1 — how much painted trim/motif detail garments get.
    #[serde(default = "d_ornament")]
    pub ornamentation: f32,
    /// Trim motif for garment borders: meander|zigzag|dots|diamonds|scroll|runes.
    #[serde(default)]
    pub trim_motif: Option<String>,
    /// 0..1 — painted age detail on the face (forehead lines, crow's feet,
    /// nasolabial folds).
    #[serde(default)]
    pub age: f32,
    /// Extra props: necklace | belt_knot | staff.
    #[serde(default)]
    pub accessories: Vec<String>,
    /// Tessellation multiplier 0.5..2.0 — 2.0 doubles segment counts and
    /// subdivision for hero-quality close-ups.
    #[serde(default = "d_one")]
    pub detail: f32,
}
fn d_ornament() -> f32 {
    0.6
}
fn d_char_h() -> f32 {
    1.7
}

#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum Recipe {
    Terrain {
        #[serde(default = "d_palette")]
        palette: String,
        #[serde(flatten)]
        params: TerrainParams,
    },
    Tree {
        #[serde(default = "d_palette")]
        palette: String,
        #[serde(flatten)]
        params: TreeParams,
    },
    Rock {
        #[serde(default = "d_palette")]
        palette: String,
        #[serde(flatten)]
        params: RockParams,
    },
    Crystal {
        #[serde(default = "d_palette")]
        palette: String,
        #[serde(flatten)]
        params: CrystalParams,
    },
    Building {
        #[serde(default = "d_palette")]
        palette: String,
        #[serde(flatten)]
        params: BuildingParams,
    },
    Prop {
        #[serde(default = "d_palette")]
        palette: String,
        #[serde(flatten)]
        params: PropParams,
    },
    Character {
        #[serde(default = "d_palette")]
        palette: String,
        #[serde(flatten)]
        params: CharacterParams,
    },
    /// Fully generic declarative geometry DSL — build anything.
    Custom {
        #[serde(flatten)]
        params: crate::generators::custom::CustomParams,
    },
}

impl Recipe {
    pub fn parse(json: &str) -> Result<Self, String> {
        serde_json::from_str(json).map_err(|e| format!("invalid recipe: {e}"))
    }

    pub fn palette_name(&self) -> &str {
        match self {
            Recipe::Terrain { palette, .. }
            | Recipe::Tree { palette, .. }
            | Recipe::Rock { palette, .. }
            | Recipe::Crystal { palette, .. }
            | Recipe::Building { palette, .. }
            | Recipe::Prop { palette, .. }
            | Recipe::Character { palette, .. } => palette,
            Recipe::Custom { .. } => "verdant",
        }
    }

    /// Compile the recipe into an asset.
    pub fn build(&self) -> Result<Asset, String> {
        if !palette::PALETTES.contains(&self.palette_name()) {
            return Err(format!(
                "unknown palette '{}' (available: {})",
                self.palette_name(),
                palette::PALETTES.join(", ")
            ));
        }
        let pal = palette::by_name(self.palette_name());
        let asset = match self {
            Recipe::Terrain { params, .. } => crate::generators::terrain::generate(params, &pal),
            Recipe::Tree { params, .. } => crate::generators::tree::generate(params, &pal),
            Recipe::Rock { params, .. } => crate::generators::rock::generate(params, &pal),
            Recipe::Crystal { params, .. } => crate::generators::crystal::generate(params, &pal),
            Recipe::Building { params, .. } => crate::generators::building::generate(params, &pal),
            Recipe::Prop { params, .. } => crate::generators::prop::generate(params, &pal),
            Recipe::Character { params, .. } => {
                crate::generators::character::generate(params, &pal)
            }
            Recipe::Custom { params } => crate::generators::custom::generate(params)?,
        };
        asset.validate()?;
        Ok(asset)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn minimal_recipes_parse_and_build() {
        for kind in ["tree", "rock", "crystal", "building", "prop", "character"] {
            let r = Recipe::parse(&format!("{{\"kind\": \"{kind}\"}}")).unwrap();
            let a = r.build().unwrap();
            assert!(
                a.parts
                    .iter()
                    .map(|p| p.mesh.triangle_count())
                    .sum::<usize>()
                    > 0
            );
        }
    }

    #[test]
    fn bad_palette_rejected() {
        let r = Recipe::parse(r#"{"kind": "tree", "palette": "nope"}"#).unwrap();
        assert!(r.build().is_err());
    }

    #[test]
    fn custom_dsl_builds_anything() {
        let j = r##"{"kind":"custom","name":"totem",
          "physics":{"collider":"auto","mass":0},
          "bones":[{"name":"root"},{"name":"top","parent":"root","translation":[0,2,0]}],
          "animations":[{"name":"spin","duration":2,
            "channels":[{"bone":"top","path":"rotation","axis":[0,1,0],"keys":[0,360]}]}],
          "parts":[{"material":{"roughness":0.7},
            "nodes":[
              {"shape":"lathe","profile":[[0.5,0],[0.4,2]],"color":"#886644"},
              {"shape":"sphere","radius":0.4,"color":[0.8,0.2,0.2],"bone":"top",
               "transform":{"translate":[0,2.3,0]},"displace":{"amplitude":0.05}},
              {"shape":"box","size":[0.2,0.2,0.2],"color":"#ffffff",
               "repeat":{"count":6,"radius":1.0,"orient":true}}]}]}"##;
        let a = Recipe::parse(j).unwrap().build().unwrap();
        assert_eq!(a.animations.len(), 1);
        assert!(a.skeleton.is_some());
        assert!(a.parts[0].mesh.triangle_count() > 50);
        // regression: node without explicit transform must keep scale 1
        let (lo, hi) = a.parts[0].mesh.bounds();
        assert!((hi.y - lo.y) > 1.5, "lathe collapsed: {lo:?} {hi:?}");
    }

    #[test]
    fn dsl_geometry_v2() {
        // csg subtract carves, bevel/subdivide/curve all build valid meshes
        let j = r##"{"kind":"custom","name":"geo","parts":[{"nodes":[
          {"shape":"box","size":[2,2,2],"color":"#888888","bevel":0.2,
           "csg":[{"op":"subtract","shape":"cylinder","radius":0.6,"height":3,
                   "color":"#888888","transform":{"translate":[0,-1.5,0]}}]},
          {"shape":"sphere","radius":0.5,"subdiv":1,"color":"#ffffff",
           "subdivide":1,"smooth":true,"flat":false},
          {"shape":"curve","points":[[2,0,0],[2.5,1,0],[2,2,0.5]],
           "radius":[0.2,0.1],"samples":12,"color":"#aa6644"}
        ]}]}"##;
        let a = Recipe::parse(j).unwrap().build().unwrap();
        a.validate().unwrap();
        let m = &a.parts[0].mesh;
        assert!(m.triangle_count() > 100);
        // the cylinder bored a hole through the box floor: vertices exist
        // on the cylinder wall inside the box
        let wall = m
            .positions
            .iter()
            .any(|p| (p.x * p.x + p.z * p.z).sqrt() < 0.65 && p.y.abs() < 0.9);
        assert!(wall, "expected carved cylinder wall");
        // bad csg op rejected
        let bad = j.replace("\"op\":\"subtract\"", "\"op\":\"xor\"");
        assert!(Recipe::parse(&bad).unwrap().build().is_err());
    }

    #[test]
    fn dsl_easing_and_euler_keys() {
        let j = r##"{"kind":"custom","name":"nod",
          "bones":[{"name":"root"},{"name":"top","parent":"root","translation":[0,1,0]}],
          "animations":[{"name":"nod","duration":1,
            "channels":[{"bone":"top","path":"rotation","ease":"cubic_in_out",
                         "keys_euler":[[0,0,0],[30,45,0],[0,0,0]]}]}],
          "parts":[{"nodes":[{"shape":"box","size":[0.5,0.5,0.5],"color":"#ffffff","bone":"top"}]}]}"##;
        let a = Recipe::parse(j).unwrap().build().unwrap();
        let ch = &a.animations[0].channels[0];
        // easing bakes to dense keys
        assert!(ch.times.len() > 3);
        match &ch.data {
            crate::gltf::ChannelData::Rotation(qs) => {
                assert_eq!(qs.len(), ch.times.len());
                // multi-axis euler key produces a non-single-axis quaternion mid-clip
                let mid = qs[qs.len() / 2];
                assert!(mid.x.abs() > 0.01 && mid.y.abs() > 0.01);
            }
            _ => panic!("expected rotation channel"),
        }
        // bad ease rejected
        let bad = j.replace("cubic_in_out", "bounce");
        assert!(Recipe::parse(&bad).unwrap().build().is_err());
    }

    #[test]
    fn character_v2_features() {
        let a = Recipe::parse(r#"{"kind":"character","seed":4,"hair":"ponytail"}"#)
            .unwrap()
            .build()
            .unwrap();
        let names: Vec<&str> = a.parts[0]
            .mesh
            .morphs
            .iter()
            .map(|m| m.name.as_str())
            .collect();
        for e in ["smile", "blink", "angry", "surprised"] {
            assert!(names.contains(&e), "missing morph {e}");
        }
        // expressions off removes morphs
        let b = Recipe::parse(r#"{"kind":"character","seed":4,"expressions":false}"#)
            .unwrap()
            .build()
            .unwrap();
        assert!(b.parts[0].mesh.morphs.is_empty());
        // hair styles change geometry
        let bald = Recipe::parse(r#"{"kind":"character","seed":4,"hair":"bald"}"#)
            .unwrap()
            .build()
            .unwrap();
        assert!(
            a.parts[0].mesh.vertex_count() > bald.parts[0].mesh.vertex_count(),
            "ponytail should add geometry over bald"
        );
    }

    #[test]
    fn hair_and_beard_cards() {
        let base = Recipe::parse(r#"{"kind":"character","seed":4,"hair":"bald"}"#)
            .unwrap()
            .build()
            .unwrap();
        let long = Recipe::parse(
            r##"{"kind":"character","seed":4,"hair":"long","beard":"long","hair_color":"#eae7e0"}"##,
        )
        .unwrap()
        .build()
        .unwrap();
        assert!(
            long.parts[0].mesh.vertex_count() > base.parts[0].mesh.vertex_count() + 200,
            "ribbon cards should add real geometry"
        );
        // determinism with cards
        let again = Recipe::parse(
            r##"{"kind":"character","seed":4,"hair":"long","beard":"long","hair_color":"#eae7e0"}"##,
        )
        .unwrap()
        .build()
        .unwrap();
        assert_eq!(crate::gltf::to_glb(&long), crate::gltf::to_glb(&again));
    }

    #[test]
    fn accessories_and_ao() {
        let j = r#"{"kind":"character","seed":3,"accessories":["necklace","staff","belt_knot"]}"#;
        let a = Recipe::parse(j).unwrap().build().unwrap();
        a.validate().unwrap();
        let bare = Recipe::parse(r#"{"kind":"character","seed":3}"#)
            .unwrap()
            .build()
            .unwrap();
        assert!(
            a.parts[0].mesh.vertex_count() > bare.parts[0].mesh.vertex_count() + 100,
            "accessories should add geometry"
        );
        // staff reaches above the head
        let (_, hi) = a.parts[0].mesh.bounds();
        let (_, bare_hi) = bare.parts[0].mesh.bounds();
        assert!(
            hi.y > bare_hi.y + 0.05,
            "staff orb should top the silhouette"
        );
        // AO darkened somewhere without blowing out colors
        assert!(
            a.parts[0]
                .mesh
                .colors
                .iter()
                .all(|c| c.max_element() <= 4.0)
        );
        let b = Recipe::parse(j).unwrap().build().unwrap();
        assert_eq!(crate::gltf::to_glb(&a), crate::gltf::to_glb(&b));
    }

    #[test]
    fn character_outfits() {
        let j = r#"{"kind":"character","seed":9,"outfit":"robe","ornamentation":0.7}"#;
        let a = Recipe::parse(j).unwrap().build().unwrap();
        a.validate().unwrap();
        // body + under-robe + coat + 2 sleeves + sash + tail + mantle
        assert!(
            a.parts.len() >= 7,
            "robe outfit should add garment parts: {}",
            a.parts.len()
        );
        // garments carry painted textures and skin weights
        let dressed_parts = a
            .parts
            .iter()
            .filter(|p| p.material.texture.is_some())
            .count();
        assert!(dressed_parts >= 5);
        assert!(a.parts[1].mesh.is_skinned());
        // deterministic incl. baked garment paint
        let b = Recipe::parse(j).unwrap().build().unwrap();
        assert_eq!(crate::gltf::to_glb(&a), crate::gltf::to_glb(&b));
        // plain = body + painted-face head only
        let p = Recipe::parse(r#"{"kind":"character","seed":9}"#)
            .unwrap()
            .build()
            .unwrap();
        assert_eq!(p.parts.len(), 2);
    }

    #[test]
    fn character_ships_clip_library() {
        let a = Recipe::parse(r#"{"kind":"character","seed":2}"#)
            .unwrap()
            .build()
            .unwrap();
        let names: Vec<&str> = a.animations.iter().map(|c| c.name.as_str()).collect();
        for expected in [
            "idle", "walk", "run", "attack", "sit", "wave", "death", "dance",
        ] {
            assert!(names.contains(&expected), "missing clip {expected}");
        }
        // posing at mid-clip moves vertices
        let posed = crate::anim::pose_asset(&a, "walk", 0.25).unwrap();
        let moved = posed.parts[0]
            .mesh
            .positions
            .iter()
            .zip(&a.parts[0].mesh.positions)
            .any(|(p, q)| p.distance(*q) > 0.01);
        assert!(moved, "walk pose should deform the mesh");
    }

    #[test]
    fn terrain_tiles_seamlessly() {
        let mk = |ox: f32| {
            let j = format!(
                concat!(
                    "{{\"kind\":\"terrain\",\"seed\":5,\"size\":16,\"resolution\":32,",
                    "\"scatter\":false,\"skirt\":false,\"water_level\":0,\"offset_x\":{}}}"
                ),
                ox
            );
            Recipe::parse(&j).unwrap().build().unwrap()
        };
        let a = mk(0.0);
        let b = mk(16.0);
        let edge = |asset: &crate::gltf::Asset, x: f32| -> Vec<(i32, i32)> {
            let mut v: Vec<(i32, i32)> = asset.parts[0]
                .mesh
                .positions
                .iter()
                .filter(|p| (p.x - x).abs() < 1e-4)
                .map(|p| ((p.z * 1000.0) as i32, (p.y * 1000.0) as i32))
                .collect();
            v.sort_unstable();
            v.dedup();
            v
        };
        assert_eq!(edge(&a, 8.0), edge(&b, -8.0));
    }

    #[test]
    fn terrain_v3_features() {
        let j = r#"{"kind":"terrain","seed":7,"size":24,"resolution":48,"erosion":0.6,
            "rivers":1,"water_level":0.1,
            "paths":[{"points":[[-10,-10],[0,0],[10,10]],"width":2.0}]}"#;
        let a = Recipe::parse(j).unwrap().build().unwrap();
        a.validate().unwrap();
        // deterministic (erosion + rivers + paths + instanced scatter)
        let b = Recipe::parse(j).unwrap().build().unwrap();
        assert_eq!(
            crate::gltf::to_glb(&a),
            crate::gltf::to_glb(&b),
            "terrain v3 must stay byte-deterministic"
        );
        // scatter exports as GPU instances
        assert!(!a.instanced.is_empty());
        let glb = crate::gltf::to_glb(&a);
        let json_len = u32::from_le_bytes(glb[12..16].try_into().unwrap()) as usize;
        let doc: serde_json::Value = serde_json::from_slice(&glb[20..20 + json_len]).unwrap();
        let exts = doc["extensionsUsed"].as_array().unwrap();
        assert!(exts.iter().any(|e| e == "EXT_mesh_gpu_instancing"));
        let inst_node = doc["nodes"]
            .as_array()
            .unwrap()
            .iter()
            .find(|n| n["extensions"]["EXT_mesh_gpu_instancing"].is_object())
            .expect("instanced node");
        let attrs = &inst_node["extensions"]["EXT_mesh_gpu_instancing"]["attributes"];
        for k in ["TRANSLATION", "ROTATION", "SCALE"] {
            let acc = attrs[k].as_u64().unwrap() as usize;
            assert!(doc["accessors"][acc]["count"].as_u64().unwrap() > 0);
        }
        // erosion actually changes the heightfield
        let flat = Recipe::parse(&j.replace("\"erosion\":0.6", "\"erosion\":0.0"))
            .unwrap()
            .build()
            .unwrap();
        assert!(
            !(a.parts[0].mesh.positions.len() == flat.parts[0].mesh.positions.len()
                && a.parts[0].mesh.positions == flat.parts[0].mesh.positions),
            "erosion should alter geometry"
        );
    }

    #[test]
    fn deterministic_build() {
        let j = r#"{"kind": "tree", "seed": 9, "style": "oak"}"#;
        let a = crate::gltf::to_glb(&Recipe::parse(j).unwrap().build().unwrap());
        let b = crate::gltf::to_glb(&Recipe::parse(j).unwrap().build().unwrap());
        assert_eq!(a, b);
    }
}