bevy_symbios_shape 0.4.0

Bevy integration for Symbios Shape.
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
//! Ergonomic command extension for spawning CGA shape grammar results as Bevy entities.
//!
//! # Usage
//!
//! ```ignore
//! use bevy::prelude::*;
//! use bevy_symbios_shape::prelude::*;
//! use symbios_shape::{Interpreter, Scope, grammar::parse_ops};
//!
//! fn setup(
//!     mut commands: Commands,
//!     registry: Res<ShapeRegistry>,
//!     mut meshes: ResMut<Assets<Mesh>>,
//!     mut materials: ResMut<Assets<StandardMaterial>>,
//!     mut cache: ResMut<ShapeMeshCache>,
//! ) {
//!     let mut interp = Interpreter::new();
//!     interp.add_rule("Lot", parse_ops("Extrude(12) I(\"Building\")").unwrap());
//!
//!     let footprint = Scope::new(
//!         symbios_shape::Vec3::ZERO,
//!         symbios_shape::Quat::IDENTITY,
//!         symbios_shape::Vec3::new(10.0, 0.0, 10.0),
//!     );
//!
//!     commands
//!         .spawn_shape(&interp, footprint, "Lot", &registry, &mut meshes, &mut materials, &mut cache)
//!         .unwrap();
//! }
//! ```

use bevy::color::Color;
use bevy::prelude::*;
use symbios_shape::{Interpreter, Scope, ShapeError};

use crate::cache::{MeshCacheKey, ProfileKey, ShapeMeshCache};
use crate::mass::TerminalMass;
use crate::mesh::build_profiled_mesh;
use crate::query::LastDerivedModel;
use crate::registry::ShapeRegistry;
use crate::snap::{SnapPlane, SnapPlanes};
use crate::transform::scope_to_transform;

/// Extension trait on [`Commands`] for spawning CGA shape grammar outputs as Bevy entities.
#[allow(clippy::too_many_arguments)]
pub trait SpawnShapeExt {
    /// Derives the shape grammar starting from `root_scope` / `root_rule`, then
    /// spawns the resulting [`Terminal`] nodes as a hierarchy of Bevy entities.
    ///
    /// Returns the root [`Entity`] (a spatial grouping node at world origin) on
    /// success, or a [`ShapeError`] if derivation fails.
    ///
    /// # Asset resolution
    ///
    /// For each terminal:
    /// - If `mesh_id` is registered in `registry` → spawn a [`SceneRoot`] child.
    /// - Otherwise → generate a procedural mesh via [`build_profiled_mesh`]
    ///   (supports tapered prisms, triangles, trapezoids, and arbitrary polygons)
    ///   and spawn [`Mesh3d`] + [`MeshMaterial3d`].
    ///
    /// [`build_profiled_mesh`]: crate::mesh::build_profiled_mesh
    ///
    /// For materials:
    /// - If `terminal.material` is registered in `registry` → use that handle.
    /// - Otherwise → use `registry.default_material`, or a generated grey material.
    ///
    /// # Transform
    ///
    /// Each terminal's [`Transform`] is computed by [`scope_to_transform`], which
    /// converts the double-precision scope (corner-anchored) to a Bevy centroid-
    /// anchored `Transform` with proper f64→f32 downcasting.
    ///
    /// [`Terminal`]: symbios_shape::Terminal
    fn spawn_shape(
        &mut self,
        interpreter: &Interpreter,
        root_scope: Scope,
        root_rule: &str,
        registry: &ShapeRegistry,
        meshes: &mut Assets<Mesh>,
        materials: &mut Assets<StandardMaterial>,
        cache: &mut ShapeMeshCache,
    ) -> Result<Entity, ShapeError>;
}

impl SpawnShapeExt for Commands<'_, '_> {
    fn spawn_shape(
        &mut self,
        interpreter: &Interpreter,
        root_scope: Scope,
        root_rule: &str,
        registry: &ShapeRegistry,
        meshes: &mut Assets<Mesh>,
        materials: &mut Assets<StandardMaterial>,
        cache: &mut ShapeMeshCache,
    ) -> Result<Entity, ShapeError> {
        let model = interpreter.derive(root_scope, root_rule)?;

        // Surface this derivation's snap-plane recordings as a resource so
        // downstream systems can read them. Last-spawn wins; consumers that
        // need to retain older planes should clone in a post-update system.
        let snap_planes: Vec<SnapPlane> = model.snap_planes.iter().map(SnapPlane::from).collect();
        self.insert_resource(SnapPlanes(snap_planes));

        // Root grouping entity — children use world-space transforms as their local
        // transforms, so the root sits at the world origin with no offset.
        // Visibility is required so that `commands.entity(root).insert(Visibility::Hidden)`
        // propagates through the hierarchy via InheritedVisibility/ViewVisibility.
        let root = self
            .spawn((Transform::default(), Visibility::default()))
            .id();

        for terminal in &model.terminals {
            let transform = scope_to_transform(&terminal.scope);

            let child = if let Some(scene_handle) = registry.get_mesh(&terminal.mesh_id) {
                // Registered asset: spawn as a scene child.
                // The scene is assumed to be unit-scale; scope_to_transform provides scale.
                self.spawn((SceneRoot(scene_handle.clone()), transform))
                    .id()
            } else {
                // Procedural fallback: generate a tapered cuboid mesh.
                let size = Vec3::new(
                    terminal.scope.size.x as f32,
                    terminal.scope.size.y as f32,
                    terminal.scope.size.z as f32,
                );

                let stretch_uvs = registry.should_stretch_uvs(
                    &terminal.mesh_id,
                    terminal.material.as_ref().map(|m| m.id.as_str()),
                );

                let mesh_key = MeshCacheKey {
                    profile: ProfileKey::from_profile(&terminal.face_profile),
                    size_x_bits: size.x.to_bits(),
                    size_y_bits: size.y.to_bits(),
                    size_z_bits: size.z.to_bits(),
                    stretch_uvs,
                };

                let mesh_handle = cache.get_or_insert_with(mesh_key, || {
                    meshes.add(build_profiled_mesh(
                        &terminal.face_profile,
                        size,
                        stretch_uvs,
                    ))
                });

                let material_handle = registry
                    .resolve_material(terminal.material.as_ref().map(|m| m.id.as_str()))
                    .unwrap_or_else(|| {
                        // Derive a stable grey-ish color from the mesh_id string so
                        // different unknown IDs are visually distinguishable.
                        let hue = string_to_hue(&terminal.mesh_id);
                        materials.add(StandardMaterial {
                            base_color: Color::hsl(hue, 0.4, 0.6),
                            ..Default::default()
                        })
                    });

                self.spawn((
                    Mesh3d(mesh_handle),
                    MeshMaterial3d(material_handle),
                    transform,
                ))
                .id()
            };

            if let Some(mp) = terminal.mass_properties.as_ref() {
                self.entity(child).insert(TerminalMass::from(mp));
            }

            self.entity(root).add_child(child);
        }

        // Hand the full derivation to downstream systems for spatial queries.
        // Moves the model after the for-loop borrow ends.
        self.insert_resource(LastDerivedModel(model));

        Ok(root)
    }
}

/// Maps a string to a hue value in `[0, 360)` via a simple hash,
/// giving visually distinct but stable colors for unknown mesh IDs.
fn string_to_hue(s: &str) -> f32 {
    let hash = s.bytes().fold(5381u32, |acc, b| {
        acc.wrapping_mul(31).wrapping_add(b as u32)
    });
    (hash % 360) as f32
}

#[cfg(test)]
mod tests {
    use super::*;
    use bevy::ecs::system::RunSystemOnce;
    use symbios_shape::grammar::parse_ops;
    use symbios_shape::{Interpreter, Quat as DQuat, Scope, Vec3 as DVec3};

    #[test]
    fn string_to_hue_is_in_range() {
        for id in ["Window", "Door", "Roof", "Ground", "Wall", ""] {
            let h = string_to_hue(id);
            assert!((0.0..360.0).contains(&h), "hue {h} out of range for '{id}'");
        }
    }

    #[test]
    fn string_to_hue_is_stable() {
        assert_eq!(string_to_hue("Building"), string_to_hue("Building"));
    }

    /// Builds a minimal Bevy world with the asset registries needed by `spawn_shape`.
    fn make_app() -> App {
        let mut app = App::new();
        app.add_plugins(bevy::asset::AssetPlugin::default())
            .init_resource::<Assets<Mesh>>()
            .init_resource::<Assets<StandardMaterial>>()
            .init_resource::<Assets<Scene>>()
            .init_resource::<ShapeRegistry>()
            .init_resource::<ShapeMeshCache>();
        app
    }

    #[test]
    fn mass_component_inserted_when_density_present() {
        let mut interp = Interpreter::new();
        interp.add_rule(
            "Lot",
            parse_ops(r#"Extrude(2) Mat("Stone", 1800) I("Wall")"#).unwrap(),
        );
        let footprint = Scope::new(DVec3::ZERO, DQuat::IDENTITY, DVec3::new(2.0, 0.0, 2.0));

        let mut app = make_app();
        app.world_mut()
            .run_system_once(
                move |mut commands: Commands,
                      registry: Res<ShapeRegistry>,
                      mut meshes: ResMut<Assets<Mesh>>,
                      mut materials: ResMut<Assets<StandardMaterial>>,
                      mut cache: ResMut<ShapeMeshCache>| {
                    commands
                        .spawn_shape(
                            &interp,
                            footprint,
                            "Lot",
                            &registry,
                            &mut meshes,
                            &mut materials,
                            &mut cache,
                        )
                        .unwrap();
                },
            )
            .unwrap();

        let count = app
            .world_mut()
            .query::<&TerminalMass>()
            .iter(app.world())
            .count();
        assert!(
            count >= 1,
            "expected at least one TerminalMass component, got {count}"
        );
        let masses: Vec<_> = app
            .world_mut()
            .query::<&TerminalMass>()
            .iter(app.world())
            .map(|m| m.mass)
            .collect();
        assert!(
            masses.iter().all(|&m| m > 0.0 && m.is_finite()),
            "expected positive finite masses, got {masses:?}"
        );
    }

    #[test]
    fn snap_planes_resource_populated_after_spawn() {
        // RegSnap("walls") records all six face planes of the current scope.
        let mut interp = Interpreter::new();
        interp.add_rule(
            "Lot",
            parse_ops(r#"Extrude(2) RegSnap("walls") I("Wall")"#).unwrap(),
        );
        let footprint = Scope::new(DVec3::ZERO, DQuat::IDENTITY, DVec3::new(2.0, 0.0, 2.0));

        let mut app = make_app();
        app.world_mut()
            .run_system_once(
                move |mut commands: Commands,
                      registry: Res<ShapeRegistry>,
                      mut meshes: ResMut<Assets<Mesh>>,
                      mut materials: ResMut<Assets<StandardMaterial>>,
                      mut cache: ResMut<ShapeMeshCache>| {
                    commands
                        .spawn_shape(
                            &interp,
                            footprint,
                            "Lot",
                            &registry,
                            &mut meshes,
                            &mut materials,
                            &mut cache,
                        )
                        .unwrap();
                },
            )
            .unwrap();

        let planes = app.world().resource::<SnapPlanes>();
        assert_eq!(planes.len(), 6, "RegSnap should record 6 face planes");
        assert!(
            planes.iter().all(|p| p.label == "walls"),
            "all planes should carry the RegSnap label"
        );
        assert!(
            planes.iter().all(|p| p.normal.length() > 0.99),
            "normals should be unit length"
        );
    }

    #[test]
    fn last_derived_model_populated_and_overlaps_query_works() {
        let mut interp = Interpreter::new();
        // Single terminal at the origin spanning (2, 2, 2).
        interp.add_rule("Lot", parse_ops(r#"Extrude(2) I("Wall")"#).unwrap());
        let footprint = Scope::new(DVec3::ZERO, DQuat::IDENTITY, DVec3::new(2.0, 0.0, 2.0));

        let mut app = make_app();
        app.world_mut()
            .run_system_once(
                move |mut commands: Commands,
                      registry: Res<ShapeRegistry>,
                      mut meshes: ResMut<Assets<Mesh>>,
                      mut materials: ResMut<Assets<StandardMaterial>>,
                      mut cache: ResMut<ShapeMeshCache>| {
                    commands
                        .spawn_shape(
                            &interp,
                            footprint,
                            "Lot",
                            &registry,
                            &mut meshes,
                            &mut materials,
                            &mut cache,
                        )
                        .unwrap();
                },
            )
            .unwrap();

        let derived = app.world().resource::<LastDerivedModel>();
        assert!(
            !derived.model().terminals.is_empty(),
            "expected at least one terminal in LastDerivedModel"
        );

        // A query scope sitting on top of the terminal must overlap.
        let near = Scope::new(
            DVec3::new(0.5, 0.5, 0.5),
            DQuat::IDENTITY,
            DVec3::new(0.5, 0.5, 0.5),
        );
        assert!(derived.overlaps(&near), "near scope should overlap");

        // A query scope 100 units away must not overlap.
        let far = Scope::new(
            DVec3::new(100.0, 100.0, 100.0),
            DQuat::IDENTITY,
            DVec3::new(0.5, 0.5, 0.5),
        );
        assert!(!derived.overlaps(&far), "far scope should not overlap");
    }

    #[test]
    fn snap_planes_resource_empty_when_no_regsnap() {
        let mut interp = Interpreter::new();
        interp.add_rule("Lot", parse_ops(r#"Extrude(2) I("Wall")"#).unwrap());
        let footprint = Scope::new(DVec3::ZERO, DQuat::IDENTITY, DVec3::new(2.0, 0.0, 2.0));

        let mut app = make_app();
        app.world_mut()
            .run_system_once(
                move |mut commands: Commands,
                      registry: Res<ShapeRegistry>,
                      mut meshes: ResMut<Assets<Mesh>>,
                      mut materials: ResMut<Assets<StandardMaterial>>,
                      mut cache: ResMut<ShapeMeshCache>| {
                    commands
                        .spawn_shape(
                            &interp,
                            footprint,
                            "Lot",
                            &registry,
                            &mut meshes,
                            &mut materials,
                            &mut cache,
                        )
                        .unwrap();
                },
            )
            .unwrap();

        let planes = app.world().resource::<SnapPlanes>();
        assert!(
            planes.is_empty(),
            "expected no snap planes, got {}",
            planes.len()
        );
    }

    #[test]
    fn mesh_cache_reuses_handles_across_spawns() {
        // Same grammar, two spawns: the second spawn should hit the cache for
        // every procedural mesh it generates. Interpreter isn't Clone, so we
        // build it twice with the same rules.
        fn make_interp() -> Interpreter {
            let mut interp = Interpreter::new();
            interp.add_rule("Lot", parse_ops(r#"Extrude(2) I("Wall")"#).unwrap());
            interp
        }
        let footprint = Scope::new(DVec3::ZERO, DQuat::IDENTITY, DVec3::new(2.0, 0.0, 2.0));

        let mut app = make_app();
        let interp = make_interp();
        app.world_mut()
            .run_system_once(
                move |mut commands: Commands,
                      registry: Res<ShapeRegistry>,
                      mut meshes: ResMut<Assets<Mesh>>,
                      mut materials: ResMut<Assets<StandardMaterial>>,
                      mut cache: ResMut<ShapeMeshCache>| {
                    commands
                        .spawn_shape(
                            &interp,
                            footprint,
                            "Lot",
                            &registry,
                            &mut meshes,
                            &mut materials,
                            &mut cache,
                        )
                        .unwrap();
                },
            )
            .unwrap();

        let (hits_after_first, misses_after_first, len_after_first) = {
            let cache = app.world().resource::<ShapeMeshCache>();
            (cache.hits(), cache.misses(), cache.len())
        };
        assert!(
            misses_after_first >= 1,
            "first spawn should miss at least once"
        );
        assert_eq!(hits_after_first, 0, "first spawn should not hit");

        // Second spawn with an identical grammar.
        let interp = make_interp();
        app.world_mut()
            .run_system_once(
                move |mut commands: Commands,
                      registry: Res<ShapeRegistry>,
                      mut meshes: ResMut<Assets<Mesh>>,
                      mut materials: ResMut<Assets<StandardMaterial>>,
                      mut cache: ResMut<ShapeMeshCache>| {
                    commands
                        .spawn_shape(
                            &interp,
                            footprint,
                            "Lot",
                            &registry,
                            &mut meshes,
                            &mut materials,
                            &mut cache,
                        )
                        .unwrap();
                },
            )
            .unwrap();

        let cache = app.world().resource::<ShapeMeshCache>();
        assert_eq!(
            cache.misses(),
            misses_after_first,
            "second spawn must not miss (no new keys)"
        );
        assert!(
            cache.hits() > hits_after_first,
            "second spawn must register hits"
        );
        assert_eq!(
            cache.len(),
            len_after_first,
            "cache size should not grow on identical second spawn"
        );
    }

    #[test]
    fn mass_component_absent_when_no_density() {
        let mut interp = Interpreter::new();
        // No Mat() => no density => no MassProperties => no TerminalMass.
        interp.add_rule("Lot", parse_ops(r#"Extrude(2) I("Wall")"#).unwrap());
        let footprint = Scope::new(DVec3::ZERO, DQuat::IDENTITY, DVec3::new(2.0, 0.0, 2.0));

        let mut app = make_app();
        app.world_mut()
            .run_system_once(
                move |mut commands: Commands,
                      registry: Res<ShapeRegistry>,
                      mut meshes: ResMut<Assets<Mesh>>,
                      mut materials: ResMut<Assets<StandardMaterial>>,
                      mut cache: ResMut<ShapeMeshCache>| {
                    commands
                        .spawn_shape(
                            &interp,
                            footprint,
                            "Lot",
                            &registry,
                            &mut meshes,
                            &mut materials,
                            &mut cache,
                        )
                        .unwrap();
                },
            )
            .unwrap();

        let count = app
            .world_mut()
            .query::<&TerminalMass>()
            .iter(app.world())
            .count();
        assert_eq!(count, 0, "expected no TerminalMass components, got {count}");
    }
}