jackdaw_prefab 0.20.0

Prefab instancing for jackdaw scenes: the IsA vocabulary and its resolver
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
//! The file an instance points at: where it lives, how a saved document spells
//! it, and what shape it has to be in to be instanced.
//!
//! A source is written relative to the project's assets folder, one namespace
//! whatever folder the document itself lives in, so a scene travels between
//! machines. An absolute source names a place on one machine, so it is read
//! and reported, never written.

use std::path::{Path, PathBuf};

use path_slash::PathExt as _;

use jackdaw_bsn::{
    BsnField, BsnPatch, BsnStructData, BsnStructFields, BsnTupleStructData, BsnValue, SceneBsnAst,
};

use crate::components::{ISA_TYPE, PREFAB_ENTITY_ID_TYPE, PREFAB_TYPE};
use crate::resolve::{read_isa_deleted, read_isa_source, set_whole_component};

const TRANSFORM_TYPE: &str = "bevy_transform::components::transform::Transform";
const VISIBILITY_INHERITED_TYPE: &str = "bevy_camera::visibility::Visibility::Inherited";

/// The file an `IsA.source` points at.
///
/// A saved source is spelled under the project's assets folder, so that is
/// read first. Documents written before that rule spelled theirs relative to
/// their own folder, so when the assets folder holds no such file the source
/// is read beside `document_dir` as well, and those still open.
///
/// The result is normalized, so the two documents that reach one prefab by
/// different routes name it identically. Both the cycle detector and the
/// prefab cache compare paths, and neither can see through a stray `..`.
pub fn source_path(source: &Path, assets_root: &Path, document_dir: &Path) -> PathBuf {
    if source.is_absolute() {
        return normalize(source);
    }
    let under_assets = normalize(&assets_root.join(source));
    if document_dir.as_os_str().is_empty() || document_dir == assets_root {
        return under_assets;
    }
    if is_a_held_document(&under_assets) {
        return under_assets;
    }
    let beside_document = normalize(&document_dir.join(source));
    match is_a_held_document(&beside_document) {
        true => beside_document,
        false => under_assets,
    }
}

/// Whether a document is held at `path`, in either of the two scene formats.
fn is_a_held_document(path: &Path) -> bool {
    path.exists() || jackdaw_bsn::existing_form(path).is_some()
}

/// Fold away `.` and `..` without touching the filesystem. Purely lexical:
/// the target need not exist yet.
///
/// A caller deciding whether a path is inside a directory has to fold first,
/// or `assets/../../etc` reads as being under `assets`.
pub fn normalize_path(path: &Path) -> PathBuf {
    normalize(path)
}

fn normalize(path: &Path) -> PathBuf {
    use std::path::Component;
    let mut out = PathBuf::new();
    for component in path.components() {
        match component {
            Component::ParentDir => {
                out.pop();
            }
            Component::CurDir => {}
            other => out.push(other.as_os_str()),
        }
    }
    out
}

/// Rewrite every absolute `IsA.source` in `ast` to a path relative to `dir`, so
/// a document with no project around it still travels.
///
/// Call it on the copy being emitted, never on the live document: the editor
/// holds instance sources as absolute paths. A source that cannot be expressed
/// relative to `dir` is left as it stands.
pub fn relativize_isa_sources(ast: &mut SceneBsnAst, dir: &Path) {
    rewrite_absolute_sources(ast, dir, false);
}

/// Rewrite every absolute `IsA.source` in `ast` to its spelling under
/// `assets_root`, and report the ones naming a file the assets folder does not
/// hold, which is a place on one machine rather than a file the project has.
pub fn relativize_isa_sources_under(ast: &mut SceneBsnAst, assets_root: &Path) -> Vec<String> {
    rewrite_absolute_sources(ast, assets_root, true)
}

fn rewrite_absolute_sources(ast: &mut SceneBsnAst, root: &Path, within: bool) -> Vec<String> {
    let mut strays = Vec::new();
    if !root.is_absolute() {
        return strays;
    }
    for node in ast.entities_with_component(ISA_TYPE) {
        let Some(source) = read_isa_source(ast, node) else {
            continue;
        };
        if !source.is_absolute() {
            continue;
        }
        let Some(relative) = pathdiff::diff_paths(&source, root)
            .filter(|relative| !within || !relative.starts_with(".."))
        else {
            strays.push(source.to_slash_lossy().into_owned());
            continue;
        };
        let deleted = read_isa_deleted(ast, node);
        let spelling = relative.to_slash_lossy();
        set_whole_component(ast, node, ISA_TYPE, isa_value(&spelling, &deleted));
    }
    strays
}

/// Rewrite every relative `IsA.source` in `ast` to the file it names under
/// `assets_root`.
///
/// The read half of the pair [`relativize_isa_sources`] writes, so a cache keyed
/// by file can look a prefab up without carrying the assets folder.
///
/// An already-absolute source is folded rather than left alone, so every source
/// afterwards is one a caller can compare.
pub fn absolutize_isa_sources(ast: &mut SceneBsnAst, assets_root: &Path, document_dir: &Path) {
    for node in ast.entities_with_component(ISA_TYPE) {
        let Some(source) = read_isa_source(ast, node) else {
            continue;
        };
        let full = source_path(&source, assets_root, document_dir);
        if full == source {
            continue;
        }
        let deleted = read_isa_deleted(ast, node);
        set_whole_component(
            ast,
            node,
            ISA_TYPE,
            isa_value(&full.to_slash_lossy(), &deleted),
        );
    }
}

/// The whole-component `IsA { source, deleted }` value a document stores.
pub fn isa_value(source: &str, deleted: &[u32]) -> BsnValue {
    BsnValue::Struct(BsnStructData {
        type_path: ISA_TYPE.to_string(),
        fields: BsnStructFields(vec![
            BsnField {
                name: "source".to_string(),
                value: BsnValue::String(source.to_string()),
            },
            BsnField {
                name: "deleted".to_string(),
                value: BsnValue::List(
                    deleted
                        .iter()
                        .map(|&d| BsnValue::Int(i128::from(d)))
                        .collect(),
                ),
            },
        ]),
    })
}

/// Make a source document instanceable as a prefab.
///
/// The resolver only materializes an `IsA` reference whose target has a single
/// root carrying the `Prefab` marker, so a plain scene is wrapped into that
/// shape: a lone root is marked in place, several roots are reparented under a
/// synthetic `Prefab` root, and every entity gets a sequential `PrefabEntityId`.
/// A file that is already a prefab passes through untouched.
///
/// The wrapping happens on the in-memory document; the authored file is never
/// rewritten. `display_name` names the synthetic root when one is made.
pub fn normalize_as_prefab_source(ast: &mut SceneBsnAst, display_name: &str) {
    let roots = ast.roots.clone();
    if roots.is_empty()
        || roots
            .iter()
            .any(|&root| ast.find_patch_by_type_path(root, PREFAB_TYPE).is_some())
    {
        return;
    }

    if roots.len() == 1 {
        let root = roots[0];
        set_whole_component(
            ast,
            root,
            PREFAB_TYPE,
            BsnValue::Type(PREFAB_TYPE.to_string()),
        );
        set_whole_component(ast, root, PREFAB_ENTITY_ID_TYPE, peid_value(0));
        for (i, desc) in ast.descendants_of(root).into_iter().enumerate() {
            set_whole_component(ast, desc, PREFAB_ENTITY_ID_TYPE, peid_value((i + 1) as u32));
        }
    } else {
        let synth = ast.create_entity_node(synthetic_root_patches(display_name));
        let mut next_id: u32 = 1;
        for root in roots {
            ast.move_to_parent(root, None, Some(synth));
            set_whole_component(ast, root, PREFAB_ENTITY_ID_TYPE, peid_value(next_id));
            next_id += 1;
            for desc in ast.descendants_of(root) {
                set_whole_component(ast, desc, PREFAB_ENTITY_ID_TYPE, peid_value(next_id));
                next_id += 1;
            }
        }
        ast.add_to_roots(synth);
    }
}

/// Read a prefab source document from disk, ready to instance.
///
/// The file is parsed as `.bsn` and normalized, so a plain scene comes back
/// instanceable, and its own prefab references are resolved against
/// `assets_root`. The file stem names a synthetic root when the
/// document needs one.
pub fn read_prefab_document(
    path: &Path,
    assets_root: &Path,
) -> Result<SceneBsnAst, std::io::Error> {
    let text = jackdaw_bsn::read_document_text(path)
        .map_err(|err| std::io::Error::new(std::io::ErrorKind::InvalidData, err.to_string()))?;
    let mut ast = jackdaw_bsn::parse_bsn_text(&text)
        .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e.to_string()))?;
    let display_name = path.file_stem().and_then(|s| s.to_str()).unwrap_or("scene");
    normalize_as_prefab_source(&mut ast, display_name);
    absolutize_isa_sources(
        &mut ast,
        assets_root,
        path.parent().unwrap_or(Path::new("")),
    );
    Ok(ast)
}

/// The `PrefabEntityId(id)` whole-component value.
pub fn peid_value(id: u32) -> BsnValue {
    BsnValue::TupleStruct(BsnTupleStructData {
        type_path: PREFAB_ENTITY_ID_TYPE.to_string(),
        values: vec![BsnValue::Int(i128::from(id))],
    })
}

/// The patch list of a synthetic `Prefab` root: the marker, id zero, a name,
/// and the transform and visibility a parent of the real roots needs so they
/// still have a propagation backbone.
pub fn synthetic_root_patches(display_name: &str) -> Vec<BsnPatch> {
    vec![
        BsnPatch::Type(PREFAB_TYPE.to_string()),
        BsnPatch::TupleStruct(BsnTupleStructData {
            type_path: PREFAB_ENTITY_ID_TYPE.to_string(),
            values: vec![BsnValue::Int(0)],
        }),
        BsnPatch::Name(display_name.to_string()),
        BsnPatch::Struct(BsnStructData {
            type_path: TRANSFORM_TYPE.to_string(),
            fields: BsnStructFields(vec![
                field("translation", vec3_value(0.0, 0.0, 0.0)),
                field("rotation", quat_value(0.0, 0.0, 0.0, 1.0)),
                field("scale", vec3_value(1.0, 1.0, 1.0)),
            ]),
        }),
        BsnPatch::Type(VISIBILITY_INHERITED_TYPE.to_string()),
    ]
}

fn field(name: &str, value: BsnValue) -> BsnField {
    BsnField {
        name: name.to_string(),
        value,
    }
}

fn vec3_value(x: f32, y: f32, z: f32) -> BsnValue {
    BsnValue::Struct(BsnStructData {
        type_path: "glam::Vec3".to_string(),
        fields: BsnStructFields(vec![
            field("x", BsnValue::Float(f64::from(x))),
            field("y", BsnValue::Float(f64::from(y))),
            field("z", BsnValue::Float(f64::from(z))),
        ]),
    })
}

fn quat_value(x: f32, y: f32, z: f32, w: f32) -> BsnValue {
    BsnValue::Struct(BsnStructData {
        type_path: "glam::Quat".to_string(),
        fields: BsnStructFields(vec![
            field("x", BsnValue::Float(f64::from(x))),
            field("y", BsnValue::Float(f64::from(y))),
            field("z", BsnValue::Float(f64::from(z))),
            field("w", BsnValue::Float(f64::from(w))),
        ]),
    })
}

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

    fn scene_with_source(source: &str) -> SceneBsnAst {
        let mut ast = SceneBsnAst::default();
        let BsnValue::Struct(data) = isa_value(source, &[]) else {
            unreachable!()
        };
        let node = ast.create_entity_node(vec![BsnPatch::Struct(data)]);
        ast.add_to_roots(node);
        ast
    }

    fn source_of(ast: &SceneBsnAst) -> String {
        match get_bsn_field(ast, ast.roots[0], ISA_TYPE, "source") {
            Some(BsnValue::String(s)) => s,
            other => panic!("expected a source string, got {other:?}"),
        }
    }

    #[test]
    fn a_relative_source_resolves_against_the_assets_folder() {
        let assets = std::path::absolute("/game/assets").expect("cwd");
        assert_eq!(
            source_path(Path::new("props/crate.bsn"), &assets, &assets),
            std::path::absolute("/game/assets/props/crate.bsn").expect("cwd")
        );
    }

    #[test]
    fn a_source_spelled_beside_its_own_document_still_opens() {
        let dir = tempfile::tempdir().expect("tempdir");
        std::fs::create_dir_all(dir.path().join("base")).expect("the base folder");
        std::fs::create_dir_all(dir.path().join("zones")).expect("the zone folder");
        let base = dir.path().join("base/panel.bsn");
        std::fs::write(&base, "#Panel\n").expect("the base file");

        assert_eq!(
            source_path(
                Path::new("../base/panel.bsn"),
                dir.path(),
                &dir.path().join("zones"),
            ),
            normalize(&base),
            "a document written before the assets folder was the namespace still reads",
        );
    }

    #[test]
    fn a_source_the_assets_folder_holds_is_read_there_rather_than_beside_the_document() {
        let dir = tempfile::tempdir().expect("tempdir");
        std::fs::create_dir_all(dir.path().join("props")).expect("the assets folder");
        std::fs::create_dir_all(dir.path().join("zones/props")).expect("the zone folder");
        std::fs::write(dir.path().join("props/crate.bsn"), "#Crate\n").expect("the asset");
        std::fs::write(dir.path().join("zones/props/crate.bsn"), "#Other\n").expect("the twin");

        assert_eq!(
            source_path(
                Path::new("props/crate.bsn"),
                dir.path(),
                &dir.path().join("zones"),
            ),
            normalize(&dir.path().join("props/crate.bsn")),
            "the one namespace wins wherever else a file of that name sits",
        );
    }

    #[test]
    fn an_absolute_source_is_taken_as_written() {
        let source = std::path::absolute("/elsewhere/crate.bsn").expect("cwd");
        assert_eq!(
            source_path(
                &source,
                &std::path::absolute("/game/assets").expect("cwd"),
                Path::new(""),
            ),
            source
        );
    }

    #[test]
    fn saving_spells_a_source_under_the_assets_folder() {
        let source = std::path::absolute("/game/assets/props/crate.bsn")
            .expect("cwd")
            .to_slash_lossy()
            .into_owned();
        let mut ast = scene_with_source(&source);

        let strays = relativize_isa_sources_under(
            &mut ast,
            &std::path::absolute("/game/assets").expect("cwd"),
        );

        assert!(strays.is_empty());
        assert_eq!(source_of(&ast), "props/crate.bsn");
    }

    #[test]
    fn a_source_the_assets_folder_does_not_hold_is_reported_rather_than_spelled() {
        let source = std::path::absolute("/elsewhere/crate.bsn")
            .expect("cwd")
            .to_slash_lossy()
            .into_owned();
        let mut ast = scene_with_source(&source);
        let strays = relativize_isa_sources_under(
            &mut ast,
            &std::path::absolute("/game/assets").expect("cwd"),
        );
        assert_eq!(strays, vec![source.clone()]);
        assert_eq!(source_of(&ast), source, "and it is left as it was written");
    }

    #[test]
    fn a_document_with_no_directory_keeps_the_source_it_had() {
        // The unsaved-scene and in-memory-capture case: relativizing against
        // a placeholder would produce a path that resolves nowhere.
        let source = std::path::absolute("/game/assets/props/crate.bsn")
            .expect("cwd")
            .to_slash_lossy()
            .into_owned();
        let mut ast = scene_with_source(&source);
        relativize_isa_sources(&mut ast, Path::new("."));
        assert_eq!(source_of(&ast), source);
    }

    #[test]
    fn a_source_that_is_already_relative_is_left_alone() {
        let mut ast = scene_with_source("props/crate.bsn");
        relativize_isa_sources_under(&mut ast, &std::path::absolute("/game/assets").expect("cwd"));
        assert_eq!(source_of(&ast), "props/crate.bsn");
    }

    #[test]
    fn an_absolute_source_is_folded_so_a_caller_can_compare_it() {
        // A containment check reads `..` as an ordinary directory name, so an
        // unfolded source can point anywhere while looking like it points
        // inside.
        let source = std::path::absolute("/game/assets/../../etc/passwd.bsn")
            .expect("cwd")
            .to_slash_lossy()
            .into_owned();
        let mut ast = scene_with_source(&source);
        let assets = std::path::absolute("/game/assets").expect("cwd");
        absolutize_isa_sources(&mut ast, &assets, &assets);
        assert_eq!(
            PathBuf::from(source_of(&ast)),
            std::path::absolute("/etc/passwd.bsn").expect("cwd")
        );
    }

    #[test]
    fn loading_names_the_file_a_relative_source_meant() {
        let mut ast = scene_with_source("props/crate.bsn");
        let assets = std::path::absolute("/game/assets").expect("cwd");
        absolutize_isa_sources(&mut ast, &assets, &assets);
        assert_eq!(
            PathBuf::from(source_of(&ast)),
            std::path::absolute("/game/assets/props/crate.bsn").expect("cwd")
        );
    }

    #[test]
    fn a_saved_source_survives_the_round_trip_it_was_written_for() {
        let assets = std::path::absolute("/game/assets").expect("cwd");
        let source = std::path::absolute("/game/assets/props/crate.bsn")
            .expect("cwd")
            .to_slash_lossy()
            .into_owned();
        let mut ast = scene_with_source(&source);
        relativize_isa_sources_under(&mut ast, &assets);
        absolutize_isa_sources(&mut ast, &assets, &assets);
        relativize_isa_sources_under(&mut ast, &assets);
        assert_eq!(
            source_of(&ast),
            "props/crate.bsn",
            "a second save writes what the first one did"
        );
    }
}