concinnity-dev 0.19.119

The Concinnity dev tooling library: world authoring, the in-engine editor, the debug server, docs and packaging
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
//! The closed vocabulary a behavior is built from: its event sources, its
//! nodes, and its expressions, each with the JSON a fresh one starts as. The
//! schema fixes this set (`concinnity-core/src/components/behavior.rs`), so the panel
//! offers a fixed palette rather than free text and the checker never sees an
//! invented verb.

use serde_json::{Value, json};

// What an expression's body looks like. Replacing a verb with one of the same
// shape keeps the operands already built, so stepping `lt` to `gt` (or `add`
// to `sub`) does not throw the subtree away.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Shape {
    // A bare string with no body: `self`, `dt`, `elapsed`.
    Unit,
    // A typed constant, whose payload the value field edits.
    Literal,
    // A single name: a variable, local, binding, asset, or query.
    Name,
    // One nested expression.
    Unary,
    // Exactly two nested expressions.
    Binary,
    // Any number of nested expressions.
    List,
    // Named operands, the way a node's settings are: the spatial expressions,
    // whose operands do not read as `a` and `b`.
    Fields,
}

// One named operand of a `Shape::Fields` expression: the key it sits under, and
// whether it names a declared query rather than holding an expression.
pub(crate) struct Operand {
    pub key: &'static str,
    pub query: bool,
}

// The named operands each `Shape::Fields` expression takes, in the order their
// rows draw.
pub(crate) fn operands(verb: &str) -> &'static [Operand] {
    const QUERY: Operand = Operand {
        key: "query",
        query: true,
    };
    const fn expr(key: &'static str) -> Operand {
        Operand { key, query: false }
    }
    const NEAREST: &[Operand] = &[QUERY, expr("of")];
    const COUNT_WITHIN: &[Operand] = &[QUERY, expr("of"), expr("radius")];
    const RAYCAST: &[Operand] = &[QUERY, expr("from"), expr("dir"), expr("distance")];
    match verb {
        "nearest" => NEAREST,
        "count_within" => COUNT_WITHIN,
        "raycast" => RAYCAST,
        _ => &[],
    }
}

// One offerable verb: the JSON key, and the hint shown beside it.
pub(crate) struct Entry {
    pub verb: &'static str,
    pub hint: &'static str,
}

// The event sources, in the order the source row cycles through them.
pub(crate) const SOURCES: &[Entry] = &[
    Entry {
        verb: "start",
        hint: "once, when the world starts",
    },
    Entry {
        verb: "tick",
        hint: "every frame",
    },
    Entry {
        verb: "timer",
        hint: "after an interval, once or repeating",
    },
    Entry {
        verb: "variable",
        hint: "whenever a world variable changes",
    },
    Entry {
        verb: "enter",
        hint: "on entering a trigger volume",
    },
    Entry {
        verb: "exit",
        hint: "on leaving a trigger volume",
    },
    Entry {
        verb: "interact",
        hint: "on interacting with an entity",
    },
    Entry {
        verb: "spawned",
        hint: "the tick after an entity spawns",
    },
];

// The nodes, grouped flow / state / lifecycle / world.
pub(crate) const NODES: &[Entry] = &[
    Entry {
        verb: "if",
        hint: "run nodes when a condition holds",
    },
    Entry {
        verb: "for_each",
        hint: "run nodes per entity a query matched",
    },
    Entry {
        verb: "after",
        hint: "run nodes once, after a wait",
    },
    Entry {
        verb: "let",
        hint: "bind an expression to a name",
    },
    Entry {
        verb: "set",
        hint: "write a world variable",
    },
    Entry {
        verb: "set_local",
        hint: "write a per-entity local",
    },
    Entry {
        verb: "set_transform",
        hint: "move, rotate, or scale an entity",
    },
    Entry {
        verb: "spawn",
        hint: "copy a placement into the world",
    },
    Entry {
        verb: "despawn",
        hint: "remove an entity and its children",
    },
    Entry {
        verb: "reparent",
        hint: "re-point an entity's parent",
    },
    Entry {
        verb: "show",
        hint: "reveal a hidden entity",
    },
    Entry {
        verb: "hide",
        hint: "hide an entity without removing it",
    },
    Entry {
        verb: "wake",
        hint: "wake an entity's physics body",
    },
    Entry {
        verb: "sound",
        hint: "play an audio clip",
    },
    Entry {
        verb: "scene",
        hint: "jump to a scene",
    },
    Entry {
        verb: "screen",
        hint: "show a screen",
    },
    Entry {
        verb: "story",
        hint: "start or continue the story",
    },
    Entry {
        verb: "save",
        hint: "persist world variables and once state",
    },
];

// The expressions, constants first, then reads, then operators.
pub(crate) const EXPRS: &[Entry] = &[
    Entry {
        verb: "bool",
        hint: "a true / false constant",
    },
    Entry {
        verb: "int",
        hint: "a whole-number constant",
    },
    Entry {
        verb: "float",
        hint: "a decimal constant",
    },
    Entry {
        verb: "vec3",
        hint: "a three-component constant",
    },
    Entry {
        verb: "var",
        hint: "read a world variable",
    },
    Entry {
        verb: "local",
        hint: "read a per-entity local",
    },
    Entry {
        verb: "bind",
        hint: "read a bound name",
    },
    Entry {
        verb: "named",
        hint: "an entity declared in the world",
    },
    Entry {
        verb: "self",
        hint: "the entity this behavior runs for",
    },
    Entry {
        verb: "dt",
        hint: "seconds since the previous tick",
    },
    Entry {
        verb: "elapsed",
        hint: "seconds since the world started",
    },
    Entry {
        verb: "position",
        hint: "an entity's world position",
    },
    Entry {
        verb: "distance",
        hint: "distance between two entities",
    },
    Entry {
        verb: "alive",
        hint: "whether an entity still exists",
    },
    Entry {
        verb: "first",
        hint: "the first entity a query matched",
    },
    Entry {
        verb: "count",
        hint: "how many entities a query matched",
    },
    Entry {
        verb: "nearest",
        hint: "the entity of a query nearest a point",
    },
    Entry {
        verb: "count_within",
        hint: "how many of a query sit within a radius",
    },
    Entry {
        verb: "raycast",
        hint: "the entity of a query a ray meets first",
    },
    Entry {
        verb: "add",
        hint: "sum",
    },
    Entry {
        verb: "sub",
        hint: "difference",
    },
    Entry {
        verb: "mul",
        hint: "product",
    },
    Entry {
        verb: "div",
        hint: "quotient",
    },
    Entry {
        verb: "normalize",
        hint: "a vector rescaled to unit length",
    },
    Entry {
        verb: "eq",
        hint: "equal",
    },
    Entry {
        verb: "ne",
        hint: "not equal",
    },
    Entry {
        verb: "lt",
        hint: "less than",
    },
    Entry {
        verb: "le",
        hint: "less than or equal",
    },
    Entry {
        verb: "gt",
        hint: "greater than",
    },
    Entry {
        verb: "ge",
        hint: "greater than or equal",
    },
    Entry {
        verb: "all",
        hint: "every condition holds",
    },
    Entry {
        verb: "any",
        hint: "some condition holds",
    },
    Entry {
        verb: "not",
        hint: "logical negation",
    },
];

// The typed constants, offered where only a literal fits (a local's declared
// value).
pub(crate) const LITERALS: &[Entry] = &[
    Entry {
        verb: "bool",
        hint: "true / false",
    },
    Entry {
        verb: "int",
        hint: "a whole number",
    },
    Entry {
        verb: "float",
        hint: "a decimal",
    },
    Entry {
        verb: "vec3",
        hint: "three components",
    },
];

// Whether `verb` is one of the vocabulary's own, so authored JSON naming
// something else is shown as-is instead of being given a subtree it has no
// schema for.
pub(crate) fn known(entries: &[Entry], verb: &str) -> bool {
    entries.iter().any(|e| e.verb == verb)
}

// The single key of a node / expression object, or the whole word when the
// value is a bare string (`"self"`, `"tick"`).
pub(crate) fn verb_of(value: &Value) -> &str {
    if let Some(word) = value.as_str() {
        return word;
    }
    match value.as_object() {
        Some(map) if map.len() == 1 => map.keys().next().map(String::as_str).unwrap_or(""),
        _ => "",
    }
}

pub(crate) fn shape(verb: &str) -> Shape {
    match verb {
        "self" | "dt" | "elapsed" => Shape::Unit,
        "bool" | "int" | "float" | "vec3" => Shape::Literal,
        "var" | "local" | "bind" | "named" | "first" | "count" => Shape::Name,
        "nearest" | "count_within" | "raycast" => Shape::Fields,
        "position" | "alive" | "normalize" | "not" => Shape::Unary,
        "all" | "any" => Shape::List,
        _ => Shape::Binary,
    }
}

// A single-key object, the shape every node, expression, and parameterized
// source takes.
pub(crate) fn single(verb: &str, body: Value) -> Value {
    let mut map = serde_json::Map::new();
    map.insert(verb.to_string(), body);
    Value::Object(map)
}

pub(crate) fn source_default(verb: &str) -> Value {
    match verb {
        "timer" => json!({"timer": {"interval": 1.0, "repeat": false}}),
        "variable" => json!({"variable": ""}),
        "enter" | "exit" | "interact" => single(verb, Value::Null),
        other => json!(other),
    }
}

pub(crate) fn node_default(verb: &str) -> Value {
    match verb {
        "if" => json!({"if": {"cond": {"bool": true}, "then": [], "else": []}}),
        "after" => json!({"after": {"seconds": {"float": 1.0}, "do": []}}),
        "for_each" => json!({"for_each": {"query": "", "bind": "each", "do": []}}),
        "let" => json!({"let": {"name": "value", "value": {"int": 0}}}),
        "set" => json!({"set": {"var": "", "value": {"int": 0}, "add": false}}),
        "set_local" => json!({"set_local": {"local": "", "value": {"int": 0}, "add": false}}),
        "set_transform" => json!({"set_transform": {
            "entity": "self", "position": null, "rotation_deg": null, "scale": null}}),
        "spawn" => json!({"spawn": {
            "template": null, "position": [0.0, 0.0, 0.0], "rotation_deg": [0.0, 0.0, 0.0],
            "scale": [1.0, 1.0, 1.0], "lifetime": 0.0, "bind": null}}),
        "despawn" | "show" | "hide" | "wake" => single(verb, json!({"target": "self"})),
        "reparent" => json!({"reparent": {"child": "self", "parent": null}}),
        "sound" => json!({"sound": {"clip": null, "kind": "sound", "volume": 1.0}}),
        "scene" => json!({"scene": {"scene": null, "transition": "FadeBlack"}}),
        "screen" => json!({"screen": {"screen": null}}),
        "story" => json!({"story": "start"}),
        _ => single("save", Value::Null),
    }
}

// A typed constant of `verb` holding that type's zero, for a slot that has to
// start somewhere.
pub(crate) fn literal_default(verb: &str) -> Value {
    single(verb, literal_body(&Value::Null, verb))
}

// The body of a name-shaped expression reading `text`. A `named` entity is an
// asset reference, so naming nothing is null rather than an empty name.
pub(crate) fn name_body(verb: &str, text: &str) -> Value {
    if verb == "named" && text.is_empty() {
        Value::Null
    } else {
        Value::String(text.to_string())
    }
}

pub(crate) fn expr_default(verb: &str) -> Value {
    match shape(verb) {
        Shape::Unit => json!(verb),
        Shape::Literal => literal_default(verb),
        Shape::Name => single(verb, name_body(verb, "")),
        Shape::Unary => single(verb, unary_operand(verb)),
        Shape::List => single(verb, json!([])),
        Shape::Binary => single(verb, binary_operands(verb)),
        Shape::Fields => single(verb, named_operands(verb)),
    }
}

// A fresh body for a named-operand expression, with every operand of the type
// it needs so a newly picked one type-checks.
fn named_operands(verb: &str) -> Value {
    match verb {
        "nearest" => json!({"query": "", "of": "self"}),
        "count_within" => json!({"query": "", "of": "self", "radius": {"float": 5.0}}),
        _ => json!({
            "query": "",
            "from": "self",
            "dir": {"vec3": [0.0, 0.0, -1.0]},
            "distance": {"float": 20.0},
        }),
    }
}

// A fresh unary operand of the type the verb needs, so a newly picked
// expression type-checks instead of arriving broken.
fn unary_operand(verb: &str) -> Value {
    match verb {
        "position" | "alive" => json!("self"),
        "normalize" => json!({"vec3": [0.0, 0.0, 0.0]}),
        _ => json!({"bool": true}),
    }
}

fn binary_operands(verb: &str) -> Value {
    match verb {
        "distance" => json!(["self", "self"]),
        _ => json!([{"float": 0.0}, {"float": 0.0}]),
    }
}

// Replace the verb of the expression `current`, keeping its operands when the
// new verb takes the same shape.
pub(crate) fn swap_expr(current: &Value, verb: &str) -> Value {
    let (from, to) = (shape(verb_of(current)), shape(verb));
    // A named-operand expression keys its operands differently from every
    // other, so swapping to or from one starts fresh rather than carrying keys
    // the new verb does not read.
    if from != to || to == Shape::Fields {
        return expr_default(verb);
    }
    let body = body_of(current);
    match to {
        Shape::Unit => json!(verb),
        Shape::Literal => single(verb, literal_body(body.unwrap_or(&Value::Null), verb)),
        Shape::Name => single(
            verb,
            name_body(verb, body.and_then(Value::as_str).unwrap_or("")),
        ),
        _ => single(verb, body.cloned().unwrap_or(Value::Null)),
    }
}

// Replace the type of the literal `current`, carrying its number across when
// both types hold one.
pub(crate) fn swap_literal(current: &Value, verb: &str) -> Value {
    let body = body_of(current);
    single(verb, literal_body(body.unwrap_or(&Value::Null), verb))
}

// The body under a single-key object; `None` for a bare-string expression or
// anything malformed.
pub(crate) fn body_of(value: &Value) -> Option<&Value> {
    match value.as_object() {
        Some(map) if map.len() == 1 => map.values().next(),
        _ => None,
    }
}

// A literal's payload retyped as `verb`: a number carries across the numeric
// types, and anything else starts from zero.
fn literal_body(from: &Value, verb: &str) -> Value {
    let number = from.as_f64();
    match verb {
        "bool" => json!(from.as_bool().unwrap_or(number.is_some_and(|n| n != 0.0))),
        "int" => json!(number.unwrap_or(0.0) as i64),
        "float" => json!(number.unwrap_or(0.0)),
        _ => match from.as_array() {
            Some(a) if a.len() == 3 => from.clone(),
            _ => json!([0.0, 0.0, 0.0]),
        },
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use concinnity_core::components::BehaviorExpr;
    use concinnity_core::components::BehaviorNode;
    use concinnity_core::components::BehaviorSource;

    // Every offered verb produces JSON the schema parses back into the type it
    // names, so nothing the palette inserts can be a shape the runtime rejects.
    #[test]
    fn every_node_default_parses_as_a_node() {
        for entry in NODES {
            let v = node_default(entry.verb);
            assert_eq!(verb_of(&v), entry.verb);
            serde_json::from_value::<BehaviorNode>(v)
                .unwrap_or_else(|e| panic!("node `{}` does not parse: {e}", entry.verb));
        }
    }

    // A named-operand expression keys its operands differently from every
    // other, so swapping to or from one starts fresh instead of carrying keys
    // the new verb does not read.
    #[test]
    fn swapping_a_named_operand_expression_starts_fresh() {
        let nearest = expr_default("nearest");
        let raycast = swap_expr(&nearest, "raycast");
        assert_eq!(raycast, expr_default("raycast"));

        // And the other way: an expression with positional operands does not
        // keep them when it becomes a named-operand one.
        let distance = expr_default("distance");
        assert_eq!(swap_expr(&distance, "nearest"), expr_default("nearest"));
        assert_eq!(swap_expr(&raycast, "distance"), expr_default("distance"));
    }

    // Every named operand a `Shape::Fields` expression declares is present in
    // the body the palette inserts, so a freshly picked one is complete rather
    // than half-filled.
    #[test]
    fn a_named_operand_default_carries_every_operand() {
        for verb in ["nearest", "count_within", "raycast"] {
            assert_eq!(shape(verb), Shape::Fields, "{verb}");
            let body = body_of(&expr_default(verb)).cloned().unwrap_or(Value::Null);
            for operand in operands(verb) {
                assert!(
                    body.get(operand.key).is_some(),
                    "`{verb}` default is missing `{}`: {body}",
                    operand.key,
                );
            }
        }
    }

    #[test]
    fn every_expr_default_parses_as_an_expression() {
        for entry in EXPRS {
            let v = expr_default(entry.verb);
            assert_eq!(verb_of(&v), entry.verb);
            serde_json::from_value::<BehaviorExpr>(v)
                .unwrap_or_else(|e| panic!("expression `{}` does not parse: {e}", entry.verb));
        }
    }

    #[test]
    fn every_source_default_parses_as_a_source() {
        for entry in SOURCES {
            let v = source_default(entry.verb);
            serde_json::from_value::<BehaviorSource>(v)
                .unwrap_or_else(|e| panic!("source `{}` does not parse: {e}", entry.verb));
        }
    }

    // A freshly picked expression is well typed on its own terms, so the
    // status line reports what the user still has to fill in, not the palette's
    // own leftovers.
    #[test]
    fn fresh_operands_match_the_operator() {
        assert_eq!(
            expr_default("position"),
            serde_json::json!({"position": "self"})
        );
        assert_eq!(
            expr_default("normalize"),
            serde_json::json!({"normalize": {"vec3": [0.0, 0.0, 0.0]}})
        );
        assert_eq!(
            expr_default("distance"),
            serde_json::json!({"distance": ["self", "self"]})
        );
        assert_eq!(
            expr_default("not"),
            serde_json::json!({"not": {"bool": true}})
        );
    }

    #[test]
    fn swapping_within_a_shape_keeps_the_operands() {
        let lt = serde_json::json!({"lt": [{"float": 1.0}, {"float": 2.0}]});
        assert_eq!(
            swap_expr(&lt, "ge"),
            serde_json::json!({"ge": [{"float": 1.0}, {"float": 2.0}]})
        );
        let var = serde_json::json!({"var": "health"});
        assert_eq!(
            swap_expr(&var, "local"),
            serde_json::json!({"local": "health"})
        );
    }

    #[test]
    fn an_empty_name_swapped_to_named_names_nothing() {
        let var = serde_json::json!({"var": ""});
        assert_eq!(swap_expr(&var, "named"), serde_json::json!({"named": null}));
        let named = serde_json::json!({"named": null});
        assert_eq!(swap_expr(&named, "var"), serde_json::json!({"var": ""}));
        assert_eq!(swap_expr(&named, "named"), named);
    }

    #[test]
    fn swapping_across_shapes_starts_from_the_default() {
        let lt = serde_json::json!({"lt": [{"float": 1.0}, {"float": 2.0}]});
        assert_eq!(swap_expr(&lt, "not"), expr_default("not"));
        assert_eq!(swap_expr(&lt, "self"), serde_json::json!("self"));
    }

    #[test]
    fn literals_carry_their_number_across_the_numeric_types() {
        let f = serde_json::json!({"float": 2.75});
        assert_eq!(swap_literal(&f, "int"), serde_json::json!({"int": 2}));
        assert_eq!(swap_literal(&f, "bool"), serde_json::json!({"bool": true}));
        let v = serde_json::json!({"vec3": [1.0, 2.0, 3.0]});
        assert_eq!(swap_literal(&v, "vec3"), v);
        assert_eq!(swap_literal(&v, "float"), serde_json::json!({"float": 0.0}));
    }

    #[test]
    fn verb_of_reads_bare_words_and_single_key_objects() {
        assert_eq!(verb_of(&serde_json::json!("self")), "self");
        assert_eq!(verb_of(&serde_json::json!({"int": 3})), "int");
        assert_eq!(verb_of(&serde_json::json!({"a": 1, "b": 2})), "");
        assert_eq!(verb_of(&Value::Null), "");
    }

    // Every entry carries a hint, so no palette row draws a bare verb.
    #[test]
    fn every_entry_has_a_hint() {
        for entries in [SOURCES, NODES, EXPRS, LITERALS] {
            for e in entries {
                assert!(!e.hint.is_empty(), "`{}` has no hint", e.verb);
            }
        }
    }
}