openworldformat 0.3.5

The Open World Format Rust reference: the world document, the session fold (log, branches, state), and the ext-physics and ext-cinematography extensions — serde-only, no engine required.
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
//! The one list of entity-reference fields (spec/world.md "Identity",
//! schema/entity-refs.json) — the crate's embedded copy. The canonical
//! list is generated from world.schema.json's `x-entity-ref` markers by
//! schema/generate-entity-refs.mjs, but a published crate can't read
//! the repo's schema/ at runtime, so the passes read this table
//! instead, and tests/entity_refs.rs fails when it drifts from the
//! canonical file.
//!
//! [`EntityRefKind::Bindable`] — a name is accepted at intake and MUST
//! bind to an id at ingestion; [`EntityRefKind::Id`] — numeric only.
//! The scope is the object the path walks from: an entity (or its
//! patch, the same fields), the manifest's avatar, or one creation in
//! `creations[]`. `"*"` walks every array element.
//!
//! Two walks read the table: [`walk_ref_path`] over the raw op JSON
//! (the authoring pass binds names before the typed read) and
//! [`RefWalk`] over the typed model (name binding after apply, merge
//! rewriting) — the same list either way, so the three passes can
//! never drift apart over hand-written field mentions.

use std::collections::BTreeMap;
use std::convert::Infallible;

use serde_json::Value;

use crate::avatar::AvatarDef;
use crate::behavior::BehaviorDef;
use crate::creation::CreationDef;
use crate::entity::{EntityPatch, WorldEntity};
use crate::identity::{EntityId, EntityRef};

/// The object a marked path walks from.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EntityRefScope {
    /// An entity (or its patch — the same fields).
    Entity,
    /// The manifest's avatar.
    Avatar,
    /// One creation in `creations[]`.
    Creation,
}

impl EntityRefScope {
    /// The scope's name in the canonical list.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Entity => "entity",
            Self::Avatar => "avatar",
            Self::Creation => "creation",
        }
    }
}

/// What a marked field accepts.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EntityRefKind {
    /// A name is accepted at intake; it MUST bind to an id at ingestion.
    Bindable,
    /// Numeric only.
    Id,
}

impl EntityRefKind {
    /// The kind's name in the canonical list.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Bindable => "bindable",
            Self::Id => "id",
        }
    }
}

/// One marked entity-reference field: a scope, the path that walks it
/// (`"*"` walks every array element), and what it accepts.
pub struct EntityRefField {
    pub scope: EntityRefScope,
    pub path: &'static [&'static str],
    pub kind: EntityRefKind,
}

/// The one list of entity-reference fields, in the canonical file's
/// order — the embedded copy of schema/entity-refs.json's `refs`.
pub const ENTITY_REFS: &[EntityRefField] = &[
    EntityRefField {
        scope: EntityRefScope::Entity,
        path: &["behaviors", "*", "LookAt", "target"],
        kind: EntityRefKind::Bindable,
    },
    EntityRefField {
        scope: EntityRefScope::Entity,
        path: &["behaviors", "*", "Orbit", "center"],
        kind: EntityRefKind::Bindable,
    },
    EntityRefField {
        scope: EntityRefScope::Entity,
        path: &["ext-cinematography", "camera", "aim_entity"],
        kind: EntityRefKind::Bindable,
    },
    EntityRefField {
        scope: EntityRefScope::Entity,
        path: &["ext-cinematography", "camera", "focus_entity"],
        kind: EntityRefKind::Bindable,
    },
    EntityRefField {
        scope: EntityRefScope::Entity,
        path: &["parent"],
        kind: EntityRefKind::Bindable,
    },
    EntityRefField {
        scope: EntityRefScope::Avatar,
        path: &["model_entity"],
        kind: EntityRefKind::Bindable,
    },
    EntityRefField {
        scope: EntityRefScope::Creation,
        path: &["entities", "*"],
        kind: EntityRefKind::Id,
    },
];

/// The marked refs of one scope.
pub fn refs_of(scope: EntityRefScope) -> impl Iterator<Item = &'static EntityRefField> {
    ENTITY_REFS.iter().filter(move |field| field.scope == scope)
}

/// The marked refs of one scope and kind.
pub fn refs_of_kind(
    scope: EntityRefScope,
    kind: EntityRefKind,
) -> impl Iterator<Item = &'static EntityRefField> {
    refs_of(scope).filter(move |field| field.kind == kind)
}

/// Walk a marked path over raw JSON, calling `f` on each leaf value in
/// place; `"*"` walks every array element. Missing keys walk to
/// nothing. This is the JS reference's `walkRefPath`, on the raw op
/// JSON the authoring pass binds before the typed read.
pub(crate) fn walk_ref_path<E>(
    value: &mut Value,
    path: &[&str],
    f: &mut impl FnMut(&mut Value) -> Result<(), E>,
) -> Result<(), E> {
    let Some((key, rest)) = path.split_first() else {
        return Ok(());
    };
    if *key == "*" {
        if let Value::Array(elements) = value {
            for element in elements {
                if rest.is_empty() {
                    f(element)?;
                } else {
                    walk_ref_path(element, rest, f)?;
                }
            }
        }
        return Ok(());
    }
    let Some(next) = value.get_mut(*key) else {
        return Ok(());
    };
    if rest.is_empty() {
        f(next)
    } else {
        walk_ref_path(next, rest, f)
    }
}

/// A marked leaf in the typed model: a bare id slot, a classed
/// (name-or-id) reference, or a leaf inside an extension block — the
/// `ext-*` paths walk the entity's `extra` JSON, where a reference is a
/// number (an id) or a string (a name). Name binding touches the
/// classed kind and the JSON kind; the merge remaps the ids of all three.
pub(crate) enum RefSlot<'a> {
    /// A numeric-only slot (an entity's `parent`, a creation's member).
    Id(&'a mut EntityId),
    /// A name-or-id reference (a behavior's target, the avatar's model).
    Ref(&'a mut EntityRef),
    /// A reference inside an extension block (`ext-cinematography`'s
    /// `camera.aim_entity`): a JSON number or string, in place.
    Json(&'a mut Value),
}

impl RefSlot<'_> {
    /// Move the id this slot holds through the merge's remap, when it
    /// holds one: a `Ref` or `Json` still holding a name is left alone —
    /// names bind at ingestion, a merge only moves ids.
    pub(crate) fn remap(self, remapped: &BTreeMap<u64, u64>) {
        let held = match self {
            Self::Id(id) => Some(id),
            Self::Ref(EntityRef::Id(id)) => Some(id),
            Self::Ref(EntityRef::Name(_)) => None,
            Self::Json(value) => {
                if let Some(id) = value.as_u64()
                    && let Some(&to) = remapped.get(&id)
                {
                    *value = Value::from(to);
                }
                None
            }
        };
        if let Some(id) = held
            && let Some(&to) = remapped.get(&id.0)
        {
            *id = EntityId(to);
        }
    }
}

/// A typed root a marked scope's paths walk. An entity and its patch
/// share the `entity` scope (a patch sets the entity's fields, so the
/// same paths read both); the avatar and one creation walk theirs.
pub(crate) trait RefWalk {
    /// The scope whose paths this root walks.
    fn scope() -> EntityRefScope;
    /// Walk one marked path, `f` on each leaf it lands on; pieces the
    /// root doesn't have walk to nothing.
    fn walk<E>(
        &mut self,
        path: &[&str],
        f: &mut dyn FnMut(RefSlot<'_>) -> Result<(), E>,
    ) -> Result<(), E>;
}

/// Every marked entity-reference field of a typed root, `f` on each
/// leaf in place — the typed `eachRef`, the merge's one walk.
pub(crate) fn each_ref<R: RefWalk>(root: &mut R, mut f: impl FnMut(RefSlot<'_>)) {
    for field in refs_of(R::scope()) {
        root.walk(field.path, &mut |slot| {
            f(slot);
            Ok::<(), Infallible>(())
        })
        .unwrap_or_else(|never| match never {});
    }
}

impl RefWalk for WorldEntity {
    fn scope() -> EntityRefScope {
        EntityRefScope::Entity
    }

    fn walk<E>(
        &mut self,
        path: &[&str],
        f: &mut dyn FnMut(RefSlot<'_>) -> Result<(), E>,
    ) -> Result<(), E> {
        match path {
            ["parent"] => {
                if let Some(id) = &mut self.parent {
                    f(RefSlot::Id(id))?;
                }
            }
            ["behaviors", "*", variant, leaf] => {
                for behavior in &mut self.behaviors {
                    if let Some(slot) = behavior_slot(behavior, variant, leaf) {
                        f(slot)?;
                    }
                }
            }
            // An extension's marked field: the path's first key is the
            // extension's namespaced key in `extra`, the rest walks its
            // JSON (the raw walk, so an extension never needs a typed
            // arm here to be seen).
            [key, rest @ ..] => {
                if let Some(block) = self.extra.get_mut(*key) {
                    walk_ref_path(block, rest, &mut |leaf| f(RefSlot::Json(leaf)))?;
                }
            }
            [] => {}
        }
        Ok(())
    }
}

impl RefWalk for EntityPatch {
    fn scope() -> EntityRefScope {
        EntityRefScope::Entity
    }

    fn walk<E>(
        &mut self,
        path: &[&str],
        f: &mut dyn FnMut(RefSlot<'_>) -> Result<(), E>,
    ) -> Result<(), E> {
        match path {
            ["parent"] => {
                if let Some(Some(id)) = &mut self.parent {
                    f(RefSlot::Id(id))?;
                }
            }
            ["behaviors", "*", variant, leaf] => {
                for behavior in self.behaviors.iter_mut().flatten() {
                    if let Some(slot) = behavior_slot(behavior, variant, leaf) {
                        f(slot)?;
                    }
                }
            }
            // An extension's marked field, in the block the patch sets
            // (a clearing `null` has no leaves to walk).
            [key, rest @ ..] => {
                if let Some(Some(block)) = self.extra.get_mut(*key) {
                    walk_ref_path(block, rest, &mut |leaf| f(RefSlot::Json(leaf)))?;
                }
            }
            [] => {}
        }
        Ok(())
    }
}

impl RefWalk for AvatarDef {
    fn scope() -> EntityRefScope {
        EntityRefScope::Avatar
    }

    fn walk<E>(
        &mut self,
        path: &[&str],
        f: &mut dyn FnMut(RefSlot<'_>) -> Result<(), E>,
    ) -> Result<(), E> {
        if let ["model_entity"] = path
            && let Some(model) = &mut self.model_entity
        {
            f(RefSlot::Ref(model))?;
        }
        Ok(())
    }
}

impl RefWalk for CreationDef {
    fn scope() -> EntityRefScope {
        EntityRefScope::Creation
    }

    fn walk<E>(
        &mut self,
        path: &[&str],
        f: &mut dyn FnMut(RefSlot<'_>) -> Result<(), E>,
    ) -> Result<(), E> {
        if let ["entities", "*"] = path {
            for id in &mut self.entities {
                f(RefSlot::Id(id))?;
            }
        }
        Ok(())
    }
}

/// The leaf one behavior's marked field holds, by variant and field
/// name — the last two keys of the entity scope's `behaviors/*/…`
/// paths.
fn behavior_slot<'a>(
    behavior: &'a mut BehaviorDef,
    variant: &str,
    leaf: &str,
) -> Option<RefSlot<'a>> {
    match (variant, leaf, behavior) {
        ("Orbit", "center", BehaviorDef::Orbit { center: Some(center), .. }) => {
            Some(RefSlot::Ref(center))
        }
        ("LookAt", "target", BehaviorDef::LookAt { target }) => Some(RefSlot::Ref(target)),
        _ => None,
    }
}

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

    /// Every path the table names must land on a slot in a
    /// fully-populated root: the guard against a walk silently
    /// ignoring a listed field.
    #[test]
    fn every_listed_path_visits_a_slot_in_a_full_root() {
        fn visits<R: RefWalk>(root: &mut R) -> Vec<(String, usize)> {
            refs_of(R::scope())
                .map(|field| {
                    let mut visited = 0;
                    root.walk(field.path, &mut |_| {
                        visited += 1;
                        Ok::<(), Infallible>(())
                    })
                    .unwrap_or_else(|never| match never {});
                    (field.path.join("/"), visited)
                })
                .collect()
        }

        // The extension block every `ext-cinematography` path lands in.
        let camera_block =
            serde_json::json!({"camera": {"aim_entity": 2, "focus_entity": 2}});

        let mut entity = WorldEntity::new(1, "e");
        entity.parent = Some(EntityId(2));
        entity.behaviors = vec![
            BehaviorDef::LookAt {
                target: EntityRef::id(2),
            },
            BehaviorDef::Orbit {
                center: Some(EntityRef::id(2)),
                center_point: None,
                radius: 2.0,
                speed: 10.0,
                axis: [0.0, 1.0, 0.0],
                phase: 0.0,
                tilt: 0.0,
            },
        ];
        entity
            .extra
            .insert("ext-cinematography".into(), camera_block.clone());
        for (path, visited) in visits(&mut entity) {
            assert!(visited > 0, "entity path {path} visited nothing");
        }

        let mut patch = EntityPatch {
            parent: Some(Some(EntityId(2))),
            behaviors: Some(vec![
                BehaviorDef::LookAt {
                    target: EntityRef::id(2),
                },
                BehaviorDef::Orbit {
                    center: Some(EntityRef::id(2)),
                    center_point: None,
                    radius: 2.0,
                    speed: 10.0,
                    axis: [0.0, 1.0, 0.0],
                    phase: 0.0,
                    tilt: 0.0,
                },
            ]),
            ..Default::default()
        };
        patch
            .extra
            .insert("ext-cinematography".into(), Some(camera_block));
        for (path, visited) in visits(&mut patch) {
            assert!(visited > 0, "patch path {path} visited nothing");
        }

        let mut avatar = AvatarDef {
            model_entity: Some(EntityRef::id(2)),
            ..Default::default()
        };
        for (path, visited) in visits(&mut avatar) {
            assert!(visited > 0, "avatar path {path} visited nothing");
        }

        let mut creation = CreationDef {
            id: crate::identity::CreationId(1),
            name: "c".into(),
            semantic_category: None,
            bbox_half: [0.0; 3],
            entities: vec![EntityId(2)],
            parts: Vec::new(),
        };
        for (path, visited) in visits(&mut creation) {
            assert!(visited > 0, "creation path {path} visited nothing");
        }
    }

    #[test]
    fn the_json_walk_matches_walk_ref_path_semantics() {
        // "*" walks every array element, missing keys walk to nothing,
        // the leaf visit sets in place.
        let mut value = serde_json::json!({
            "behaviors": [{"Orbit": {"center": "sun"}}, {"Spin": {}}],
            "parent": "sun",
        });
        walk_ref_path(&mut value, &["behaviors", "*", "Orbit", "center"], &mut |leaf| {
            *leaf = serde_json::json!(1);
            Ok::<(), Infallible>(())
        })
        .unwrap_or_else(|never| match never {});
        walk_ref_path(&mut value, &["missing", "key"], &mut |_| -> Result<(), Infallible> {
            panic!("a missing key walks to nothing")
        })
        .unwrap_or_else(|never| match never {});
        assert_eq!(value["behaviors"][0]["Orbit"]["center"], 1);
        assert_eq!(value["parent"], "sun", "a path not walked is untouched");
    }

    #[test]
    fn an_extension_leaf_remaps_its_id_and_leaves_a_name_alone() {
        let remapped: BTreeMap<u64, u64> = [(1, 7)].into_iter().collect();
        let mut id = serde_json::json!(1);
        RefSlot::Json(&mut id).remap(&remapped);
        assert_eq!(id, 7);
        let mut other = serde_json::json!(3);
        RefSlot::Json(&mut other).remap(&remapped);
        assert_eq!(other, 3, "an id outside the remap stays");
        let mut name = serde_json::json!("maya");
        RefSlot::Json(&mut name).remap(&remapped);
        assert_eq!(name, "maya", "names bind at ingestion, a merge moves ids");
    }
}