scena 1.7.2

A Rust-native scene-graph renderer with typed scene state, glTF assets, and explicit prepare/render lifecycles.
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
use std::collections::BTreeMap;

use super::common::{DiagnosticPathExt, authored_color};
use super::transform::{TransformResolutionInput, transform_from_recipe};
use crate::assets::DefaultAssetFetcher;
use crate::geometry::SkinningMatrix;
use crate::scene::recipe::{
    RecipeBuildPolicy, SceneRecipeBuildTargetV1, SceneRecipeColorV1, SceneRecipeDiagnosticV1,
    SceneRecipeNodeV1,
};
use crate::scene::{MeshLodLevel, SceneSkinBinding};
use crate::scene_host::SceneHostCore;
use crate::{GeometryHandle, MaterialHandle, NodeKey};

use super::super::error_diagnostic;
use super::super::policy::RecipeBuildBudget;

pub(in crate::scene_host::recipe) fn build_authored_nodes(
    policy: &RecipeBuildPolicy,
    host: &mut SceneHostCore<DefaultAssetFetcher>,
    recipes: &[SceneRecipeNodeV1],
    resources: AuthoredNodeResources<'_>,
    manifest: &mut Vec<SceneRecipeBuildTargetV1>,
    diagnostics: &mut Vec<SceneRecipeDiagnosticV1>,
) -> BTreeMap<String, NodeKey> {
    let mut node_keys = BTreeMap::new();
    if recipes.len() > policy.max_nodes() {
        diagnostics.push(error_diagnostic(
            "$.nodes",
            "policy_violation",
            format!(
                "recipe declares {} authored nodes, exceeding RecipeBuildPolicy max_nodes {}",
                recipes.len(),
                policy.max_nodes()
            ),
            "reduce node count or raise the operator-owned max_nodes policy",
        ));
        return node_keys;
    }
    if let Some(diagnostic) = resources
        .build_budget
        .reserve_nodes(policy, "$.nodes", recipes.len())
    {
        diagnostics.push(diagnostic);
        return node_keys;
    }
    let root = host.scene.root();
    let root_handle = host.root_handle();
    for (index, recipe) in recipes.iter().enumerate() {
        let path = format!("$.nodes[{index}]");
        let Some(geometry) = resources.geometries.get(&recipe.geometry).copied() else {
            diagnostics.push(error_diagnostic(
                &path,
                "unknown_geometry_ref",
                format!(
                    "node '{}' references missing geometry '{}'",
                    recipe.id, recipe.geometry
                ),
                "declare the geometry before the node",
            ));
            continue;
        };
        let Some(material) = resources.materials.get(&recipe.material).copied() else {
            diagnostics.push(error_diagnostic(
                &path,
                "unknown_material_ref",
                format!(
                    "node '{}' references missing material '{}'",
                    recipe.id, recipe.material
                ),
                "declare the material before the node",
            ));
            continue;
        };
        let Some(lod_levels) = resolve_lod_levels(recipe, resources.geometries, &path, diagnostics)
        else {
            continue;
        };
        let parent = match &recipe.parent {
            Some(parent) => match node_keys.get(parent).copied() {
                Some(parent) => parent,
                None => {
                    diagnostics.push(error_diagnostic(
                        &path,
                        "unknown_node_ref",
                        format!(
                            "node '{}' references missing or forward parent '{}'",
                            recipe.id, parent
                        ),
                        "declare parent nodes before their children and avoid cycles",
                    ));
                    continue;
                }
            },
            None => root,
        };
        let geometry_bounds = match host.assets.geometry(geometry) {
            Some(geometry) => Some(geometry.bounds()),
            None => {
                diagnostics.push(error_diagnostic(
                    &path,
                    "geometry_bounds_missing",
                    format!("node '{}' geometry could not be resolved", recipe.id),
                    "declare a valid geometry before the node",
                ));
                continue;
            }
        };
        let mut transform_nodes = resources.imported_nodes.clone();
        transform_nodes.extend(node_keys.clone());
        let transform = match transform_from_recipe(
            recipe.transform.as_ref(),
            TransformResolutionInput {
                node_keys: &transform_nodes,
                imports: resources.imports,
                parent: Some(parent),
                current_bounds: geometry_bounds,
            },
            host,
        ) {
            Ok(transform) => transform,
            Err(diagnostic) => {
                diagnostics.push((*diagnostic).with_path(format!("{path}.transform")));
                continue;
            }
        };
        let node = match host
            .scene
            .mesh(geometry, material)
            .parent(parent)
            .transform(transform)
            .add()
        {
            Ok(node) => node,
            Err(error) => {
                diagnostics.push(error_diagnostic(
                    &path,
                    "node_create_failed",
                    format!("failed to create node '{}': {error}", recipe.id),
                    "check the node parent, geometry, and material references",
                ));
                continue;
            }
        };
        if let Err(error) = host.scene.set_mesh_lods(node, lod_levels) {
            diagnostics.push(error_diagnostic(
                &path,
                "lod_create_failed",
                format!(
                    "failed to attach LOD levels to node '{}': {error}",
                    recipe.id
                ),
                "attach LOD levels only to authored mesh nodes",
            ));
            continue;
        }
        apply_node_attributes(host, recipe, node, resources.colors, &path, diagnostics);
        let handle = host.register_node(node);
        node_keys.insert(recipe.id.clone(), node);
        manifest.push(SceneRecipeBuildTargetV1 {
            id: recipe.id.clone(),
            handle,
            kind: "node".to_owned(),
            parent: Some(
                host.node_handle_map
                    .get(&parent)
                    .copied()
                    .unwrap_or(root_handle),
            ),
            name: recipe.name.clone(),
            active: None,
        });
    }
    for (index, recipe) in recipes.iter().enumerate() {
        let path = format!("$.nodes[{index}]");
        if let Some(node) = node_keys.get(&recipe.id).copied() {
            apply_node_deformations(
                host,
                recipe,
                node,
                resources.geometries,
                &node_keys,
                &path,
                diagnostics,
            );
        }
    }
    node_keys
}

fn resolve_lod_levels(
    recipe: &SceneRecipeNodeV1,
    geometries: &BTreeMap<String, GeometryHandle>,
    path: &str,
    diagnostics: &mut Vec<SceneRecipeDiagnosticV1>,
) -> Option<Vec<MeshLodLevel>> {
    let mut levels = Vec::new();
    for (index, lod) in recipe.lods.iter().enumerate() {
        let lod_path = format!("{path}.lods[{index}]");
        let Some(geometry) = geometries.get(&lod.geometry).copied() else {
            diagnostics.push(error_diagnostic(
                &lod_path,
                "unknown_geometry_ref",
                format!(
                    "LOD level for node '{}' references missing geometry '{}'",
                    recipe.id, lod.geometry
                ),
                "declare the LOD geometry before the node",
            ));
            return None;
        };
        if !lod.max_screen_fraction.is_finite()
            || lod.max_screen_fraction <= 0.0
            || lod.max_screen_fraction > 1.0
        {
            diagnostics.push(error_diagnostic(
                format!("{lod_path}.max_screen_fraction"),
                "invalid_lod_threshold",
                "LOD max_screen_fraction must be finite and in (0, 1]",
                "use a fraction such as 0.15 for distant or small-on-screen geometry",
            ));
            return None;
        }
        levels.push(MeshLodLevel::new(lod.max_screen_fraction as f32, geometry));
    }
    Some(levels)
}

pub(in crate::scene_host::recipe) struct AuthoredNodeResources<'a> {
    pub(in crate::scene_host::recipe) colors: &'a BTreeMap<String, SceneRecipeColorV1>,
    pub(in crate::scene_host::recipe) geometries: &'a BTreeMap<String, GeometryHandle>,
    pub(in crate::scene_host::recipe) materials: &'a BTreeMap<String, MaterialHandle>,
    pub(in crate::scene_host::recipe) imported_nodes: &'a BTreeMap<String, NodeKey>,
    pub(in crate::scene_host::recipe) imports: &'a BTreeMap<String, u64>,
    pub(in crate::scene_host::recipe) build_budget: &'a mut RecipeBuildBudget,
}

fn apply_node_attributes(
    host: &mut SceneHostCore<DefaultAssetFetcher>,
    recipe: &SceneRecipeNodeV1,
    node: NodeKey,
    colors: &BTreeMap<String, SceneRecipeColorV1>,
    path: &str,
    diagnostics: &mut Vec<SceneRecipeDiagnosticV1>,
) {
    if let Some(visible) = recipe.visible
        && let Err(error) = host.scene.set_visible(node, visible)
    {
        diagnostics.push(error_diagnostic(
            path,
            "node_visible_failed",
            error.to_string(),
            "check the node reference",
        ));
    }
    for tag in &recipe.tags {
        if let Err(error) = host.scene.add_tag(node, tag.clone()) {
            diagnostics.push(error_diagnostic(
                path,
                "node_tag_failed",
                error.to_string(),
                "check the node reference",
            ));
        }
    }
    if let Some(mask) = recipe.layer_mask
        && let Err(error) = host.scene.set_layer_mask(node, mask)
    {
        diagnostics.push(error_diagnostic(
            path,
            "node_layer_mask_failed",
            error.to_string(),
            "check the node reference",
        ));
    }
    if let Some(group) = recipe.render_group
        && let Err(error) = host.scene.set_render_group(node, group)
    {
        diagnostics.push(error_diagnostic(
            path,
            "node_render_group_failed",
            error.to_string(),
            "check the node reference",
        ));
    }
    if let Some(tint) = &recipe.tint {
        match authored_color(colors, tint) {
            Ok(tint) => {
                if let Err(error) = host.scene.set_node_tint(node, Some(tint)) {
                    diagnostics.push(error_diagnostic(
                        path,
                        "node_tint_failed",
                        error.to_string(),
                        "check the node reference",
                    ));
                }
            }
            Err(diagnostic) => diagnostics.push((*diagnostic).with_path(format!("{path}.tint"))),
        }
    }
}

fn apply_node_deformations(
    host: &mut SceneHostCore<DefaultAssetFetcher>,
    recipe: &SceneRecipeNodeV1,
    node: NodeKey,
    geometries: &BTreeMap<String, GeometryHandle>,
    node_keys: &BTreeMap<String, NodeKey>,
    path: &str,
    diagnostics: &mut Vec<SceneRecipeDiagnosticV1>,
) {
    if !recipe.morph_weights.is_empty() {
        match validate_morph_weight_count(host, recipe, geometries) {
            Ok(()) => {
                let weights = recipe
                    .morph_weights
                    .iter()
                    .map(|weight| *weight as f32)
                    .collect::<Vec<_>>();
                if let Err(error) = host.scene.set_morph_weights(node, weights) {
                    diagnostics.push(error_diagnostic(
                        path,
                        "morph_weights_failed",
                        error.to_string(),
                        "check the node and morph target references",
                    ));
                }
            }
            Err(diagnostic) => {
                diagnostics.push((*diagnostic).with_path(format!("{path}.morph_weights")))
            }
        }
    }
    if let Some(binding) = &recipe.skin_binding {
        match scene_skin_binding(host, recipe, binding, geometries, node_keys) {
            Ok(binding) => {
                if let Err(error) = host.scene.set_skin_binding(node, binding) {
                    diagnostics.push(error_diagnostic(
                        path,
                        "skin_binding_failed",
                        error.to_string(),
                        "check the node and skin binding references",
                    ));
                }
            }
            Err(diagnostic) => {
                diagnostics.push((*diagnostic).with_path(format!("{path}.skin_binding")))
            }
        }
    }
}

fn validate_morph_weight_count(
    host: &SceneHostCore<DefaultAssetFetcher>,
    recipe: &SceneRecipeNodeV1,
    geometries: &BTreeMap<String, GeometryHandle>,
) -> Result<(), Box<SceneRecipeDiagnosticV1>> {
    let Some(handle) = geometries.get(&recipe.geometry).copied() else {
        return Err(Box::new(error_diagnostic(
            "$",
            "unknown_geometry_ref",
            format!(
                "node '{}' references missing geometry '{}'",
                recipe.id, recipe.geometry
            ),
            "declare the geometry before the node",
        )));
    };
    let Some(geometry) = host.assets.geometry(handle) else {
        return Err(Box::new(error_diagnostic(
            "$",
            "geometry_missing",
            format!(
                "node '{}' geometry '{}' could not be resolved",
                recipe.id, recipe.geometry
            ),
            "declare a valid geometry before the node",
        )));
    };
    let target_count = geometry.morph_targets().len();
    if target_count == 0 || recipe.morph_weights.len() != target_count {
        return Err(Box::new(error_diagnostic(
            "$",
            "invalid_morph",
            format!(
                "node '{}' has {} morph weights but geometry '{}' has {target_count} morph targets",
                recipe.id,
                recipe.morph_weights.len(),
                recipe.geometry
            ),
            "emit exactly one morph weight per target",
        )));
    }
    Ok(())
}

fn scene_skin_binding(
    host: &SceneHostCore<DefaultAssetFetcher>,
    recipe: &SceneRecipeNodeV1,
    binding: &crate::SceneRecipeNodeSkinBindingV1,
    geometries: &BTreeMap<String, GeometryHandle>,
    node_keys: &BTreeMap<String, NodeKey>,
) -> Result<SceneSkinBinding, Box<SceneRecipeDiagnosticV1>> {
    let Some(handle) = geometries.get(&recipe.geometry).copied() else {
        return Err(Box::new(error_diagnostic(
            "$",
            "unknown_geometry_ref",
            format!(
                "node '{}' references missing geometry '{}'",
                recipe.id, recipe.geometry
            ),
            "declare the geometry before the node",
        )));
    };
    let Some(geometry) = host.assets.geometry(handle) else {
        return Err(Box::new(error_diagnostic(
            "$",
            "geometry_missing",
            format!(
                "node '{}' geometry '{}' could not be resolved",
                recipe.id, recipe.geometry
            ),
            "declare a valid geometry before the node",
        )));
    };
    let Some(skin) = geometry.skin() else {
        return Err(Box::new(error_diagnostic(
            "$",
            "invalid_skin",
            format!(
                "node '{}' declares skin_binding for non-skinned geometry '{}'",
                recipe.id, recipe.geometry
            ),
            "remove skin_binding or use a skin-derived geometry",
        )));
    };
    let binding_nodes = binding
        .binding_nodes()
        .iter()
        .map(|node_id| {
            node_keys.get(node_id).copied().ok_or_else(|| {
                Box::new(error_diagnostic(
                    "$",
                    "unknown_node_ref",
                    format!("skin_binding references unknown node '{node_id}'"),
                    "target an authored node id",
                ))
            })
        })
        .collect::<Result<Vec<_>, _>>()?;
    if skin
        .influence_indices()
        .iter()
        .flatten()
        .any(|influence| *influence >= binding_nodes.len())
    {
        return Err(Box::new(error_diagnostic(
            "$",
            "invalid_skin",
            format!(
                "node '{}' skin geometry '{}' references an influence index outside its {}-node binding",
                recipe.id,
                recipe.geometry,
                binding_nodes.len()
            ),
            "make skin influence indices reference entries in skin_binding",
        )));
    }
    let matrices = binding
        .inverse_bind_matrices
        .iter()
        .map(|values| SkinningMatrix::from_gltf_column_major(values.map(|value| value as f32)))
        .collect();
    Ok(SceneSkinBinding::new(binding_nodes, matrices))
}