concinnity-dev 0.19.2

The Concinnity dev tooling library: world authoring, the in-engine editor, the debug server, docs and packaging
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
// src/cli/list.rs
use concinnity_cook::authoring::registry::RegisteredType;
use concinnity_cook::authoring::world::{find_world_jsonl, parse_world_jsonl, resolve_includes};

// Authoring metadata for a type name, whichever group of the registry it is in.
fn registration_for(type_str: &str) -> Option<concinnity_cook::authoring::registry::Registration> {
    RegisteredType::parse(type_str).map(RegisteredType::registration)
}

// Resolve the world path the same way every other subcommand does: an explicit
// existing path wins, otherwise discover from .concinnity/worlds/ or cwd.
pub(crate) fn resolve_world_path(json_path: Option<&str>) -> std::io::Result<String> {
    match json_path {
        Some(p) if std::path::Path::new(p).exists() => Ok(p.to_string()),
        _ => find_world_jsonl(crate::project::worlds_dir().as_deref(), None),
    }
}

// Provenance of one expanded-world row: declared in the file, added by an
// injection pass, or generated by a build-time macro expansion. The
// classification lives in cook (`LoadedWorld::provenance`), shared with the
// editor's Expanded tab; this is its printed form.
pub(crate) fn provenance(loaded: &concinnity_cook::build_only::LoadedWorld, name: &str) -> String {
    loaded.provenance(name).to_string()
}

/// Print every declared asset. `expanded` includes the assets the build
/// injects; `systems` adds the system manifest the world resolves to.
pub fn list(json_path: Option<&str>, expanded: bool, systems: bool) -> std::io::Result<()> {
    let json_path = resolve_world_path(json_path)?;

    let content = std::fs::read_to_string(&json_path).map_err(|e| {
        tracing::error!("Could not read {}: {}", json_path, e);
        e
    })?;

    if systems {
        return list_systems(&content, &json_path);
    }
    if expanded {
        return list_expanded(&content, &json_path);
    }

    let assets = parse_world_jsonl(&content).map_err(|e| {
        std::io::Error::new(
            std::io::ErrorKind::InvalidData,
            format!("Failed to parse {}: {}", json_path, e),
        )
    })?;

    let raw = resolve_includes(assets)?;

    if raw.is_empty() {
        println!("{} has no assets.", json_path);
        return Ok(());
    }

    // collect rows, then print aligned
    struct Row {
        name: String,
        type_str: String,
        origin: String,
        payload: String,
    }

    let rows: Vec<Row> = raw
        .iter()
        .map(|v| {
            let name = v
                .get("name")
                .and_then(|n| n.as_str())
                .unwrap_or("(unnamed)")
                .to_string();
            let type_str = v
                .get("type")
                .and_then(|t| t.as_str())
                .unwrap_or("?")
                .to_string();

            let (origin, payload) = if let Some(r) = registration_for(&type_str) {
                (format!("{:?}", r.origin), format!("{:?}", r.payload))
            } else {
                ("?".to_string(), "?".to_string())
            };

            Row {
                name,
                type_str,
                origin,
                payload,
            }
        })
        .collect();

    let w_name = rows.iter().map(|r| r.name.len()).max().unwrap_or(4).max(4);
    let w_type = rows
        .iter()
        .map(|r| r.type_str.len())
        .max()
        .unwrap_or(4)
        .max(4);
    let w_origin = rows
        .iter()
        .map(|r| r.origin.len())
        .max()
        .unwrap_or(6)
        .max(6);

    println!(
        "{:<w_name$}  {:<w_type$}  {:<w_origin$}  PAYLOAD",
        "NAME",
        "TYPE",
        "ORIGIN",
        w_name = w_name,
        w_type = w_type,
        w_origin = w_origin,
    );
    println!("{}", "-".repeat(w_name + w_type + w_origin + 16));

    for r in &rows {
        println!(
            "{:<w_name$}  {:<w_type$}  {:<w_origin$}  {}",
            r.name,
            r.type_str,
            r.origin,
            r.payload,
            w_name = w_name,
            w_type = w_type,
            w_origin = w_origin,
        );
    }

    println!("\n{} asset(s) in {}", rows.len(), json_path);
    Ok(())
}

// The expanded world: every asset the build produces, with its provenance.
// Runs the same front half as `cn build` (expansion passes, injection,
// semantic validation), so the listing is exactly what lands in the blob.
fn list_expanded(content: &str, json_path: &str) -> std::io::Result<()> {
    let loaded = concinnity_cook::prepare_world(
        content,
        crate::project::assets_dir().as_deref(),
        crate::cook_platform(),
    )
    .map_err(|errs| concinnity_cook::check::report_validation_errors(&errs))?;

    if loaded.assets.is_empty() {
        println!("{} expands to no assets.", json_path);
        return Ok(());
    }

    let rows: Vec<(String, String, String)> = loaded
        .assets
        .iter()
        .map(|a| {
            (
                a.name.clone(),
                a.asset_type.clone(),
                provenance(&loaded, &a.name),
            )
        })
        .collect();

    let w_name = rows.iter().map(|r| r.0.len()).max().unwrap_or(4).max(4);
    let w_type = rows.iter().map(|r| r.1.len()).max().unwrap_or(4).max(4);

    println!(
        "{:<w_name$}  {:<w_type$}  PROVENANCE",
        "NAME",
        "TYPE",
        w_name = w_name,
        w_type = w_type,
    );
    println!("{}", "-".repeat(w_name + w_type + 14));

    for (name, type_str, prov) in &rows {
        println!(
            "{:<w_name$}  {:<w_type$}  {}",
            name,
            type_str,
            prov,
            w_name = w_name,
            w_type = w_type,
        );
    }

    let injected = loaded.injected.len();
    println!(
        "\n{} asset(s) after expansion ({} injected) in {}",
        rows.len(),
        injected,
        json_path
    );
    println!("Use `cn explain <name>` to print an entry for overriding.");
    Ok(())
}

// Print the system schedule this world runs: the manifest gates (the same ones
// `World::start` runs) applied to the built world, each system paired with the
// condition from its registry entry. The world is built exactly as the runtime
// would, so the reported schedule cannot drift from what actually runs.
fn list_systems(content: &str, json_path: &str) -> std::io::Result<()> {
    let mut world = crate::build_world_from_str(content)?;
    complete(&mut world)?;
    let lines = manifest_lines(&world);

    if lines.is_empty() {
        println!("{} runs no systems.", json_path);
        return Ok(());
    }

    println!("{} runs {} system(s), in order:", json_path, lines.len());
    for line in &lines {
        println!("  {}", line);
    }
    Ok(())
}

// Run the table's own completion pass, the way `World::start` does before it
// gates: a HUD or overlay the engine injects brings its own system with it, so
// a manifest taken before the pass would be missing them.
fn complete(world: &mut concinnity_engine::ecs::World) -> std::io::Result<()> {
    let Some(complete) = concinnity_engine::ecs::SYSTEMS.complete_world else {
        return Ok(());
    };
    complete(&mut world.context())
        .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e.to_string()))
}

// One "<name>  <present_when>" row per system the world's content gates in, in
// run order. Split out from the printing so it is unit-testable without
// capturing stdout. The reason column is the `present_when` from the static
// schedule table (`ecs::SYSTEMS`), keyed by the manifest's system name.
fn manifest_lines(world: &concinnity_engine::ecs::World) -> Vec<String> {
    let manifest = world.system_manifest(concinnity_engine::ecs::SYSTEMS);
    let width = manifest.iter().map(|n| n.len()).max().unwrap_or(0);
    manifest
        .iter()
        .map(|name| {
            let reason = concinnity_engine::ecs::SYSTEMS
                .entries
                .iter()
                .find(|e| e.name == *name)
                .map(|e| e.present_when)
                .unwrap_or("");
            format!("{name:<width$}  {reason}")
        })
        .collect()
}

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

    fn write_world(content: &str) -> (tempfile::TempDir, String) {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("world.jsonl");
        std::fs::write(&path, content).unwrap();
        (dir, path.to_string_lossy().into_owned())
    }

    #[test]
    fn resolve_world_path_prefers_an_explicit_existing_path() {
        let (_dir, path) = write_world("");
        assert_eq!(resolve_world_path(Some(&path)).unwrap(), path);
    }

    // A minimal rendering world with a controlled camera gates in the graphics,
    // overlay, and camera systems; each manifest line names the system and the
    // condition that includes it.
    #[test]
    fn manifest_lines_report_the_world_schedule_with_reasons() {
        let world = crate::build_world_from_str(
            "{\"name\":\"gfx\",\"type\":\"GraphicsConfig\",\"args\":{}}\n\
             {\"name\":\"cam\",\"type\":\"Camera3D\",\"args\":{\"controller\":{\"free_fly\":true}}}\n",
        )
        .unwrap();
        let lines = manifest_lines(&world);
        let joined = lines.join("\n");
        assert!(joined.contains("GraphicsSystem"), "{joined}");
        assert!(joined.contains("Camera3DSystem"), "{joined}");
        // The reason column is present (GraphicsSystem gates on a GraphicsConfig).
        assert!(joined.contains("GraphicsConfig"), "{joined}");
    }

    // A system only an injected default turns on is still reported: the
    // listing completes the world first, exactly as `World::start` does.
    #[test]
    fn the_manifest_reports_systems_the_engine_defaults_turn_on() {
        let mut world = crate::build_world_from_str(
            "{\"name\":\"gfx\",\"type\":\"GraphicsConfig\",\"args\":{}}\n",
        )
        .unwrap();
        assert!(
            !manifest_lines(&world).join("\n").contains("DebugHud"),
            "the world declares no DebugHud of its own"
        );
        complete(&mut world).unwrap();
        assert!(
            manifest_lines(&world).join("\n").contains("DebugHud"),
            "the injected debug HUD brings its system with it"
        );
    }

    // The `--systems` path drives end to end on a valid world.
    #[test]
    fn list_with_systems_flag_is_ok() {
        let (_dir, path) =
            write_world("{\"name\":\"gfx\",\"type\":\"GraphicsConfig\",\"args\":{}}\n");
        list(Some(&path), false, true).unwrap();
    }

    fn loaded_world_fixture() -> concinnity_cook::build_only::LoadedWorld {
        concinnity_cook::build_only::LoadedWorld {
            assets: Vec::new(),
            injected: vec![concinnity_cook::build_only::InjectedAsset {
                name: "debug_hud".to_string(),
                asset_type: "DebugHud".to_string(),
                args: serde_json::json!({}),
                injected_by: "debug_hud",
            }],
            generated: vec![concinnity_cook::build_only::GeneratedAsset {
                name: "bistro_mat_wood".to_string(),
                asset_type: "Material".to_string(),
                generated_by: "bistro".to_string(),
            }],
            shadowed: vec![concinnity_cook::build_only::ShadowedAsset {
                name: "bistro_mat_glass".to_string(),
                asset_type: "Material".to_string(),
                generated_by: "bistro".to_string(),
                args: serde_json::json!({}),
            }],
            authored: vec!["cam".to_string(), "bistro_mat_glass".to_string()],
        }
    }

    #[test]
    fn provenance_reports_authored_names() {
        assert_eq!(provenance(&loaded_world_fixture(), "cam"), "authored");
    }

    #[test]
    fn provenance_reports_the_injection_pass() {
        assert_eq!(
            provenance(&loaded_world_fixture(), "debug_hud"),
            "injected:debug_hud"
        );
    }

    // A generated asset names the import that produced it, so a listing of a
    // scene import's thousands of entries stays attributable.
    #[test]
    fn provenance_reports_the_generating_import() {
        assert_eq!(
            provenance(&loaded_world_fixture(), "bistro_mat_wood"),
            "generated:bistro"
        );
    }

    // An authored copy of a generated asset is authored, but the listing says
    // what it overrides: the import no longer drives that asset.
    #[test]
    fn provenance_reports_what_an_authored_copy_shadows() {
        assert_eq!(
            provenance(&loaded_world_fixture(), "bistro_mat_glass"),
            "authored (shadows bistro)"
        );
    }

    #[test]
    fn provenance_falls_back_to_expanded() {
        assert_eq!(provenance(&loaded_world_fixture(), "anything"), "expanded");
    }

    #[test]
    fn list_of_an_empty_world_is_ok() {
        let (_dir, path) = write_world("");
        list(Some(&path), false, false).unwrap();
    }

    #[test]
    fn list_prints_known_and_unknown_types() {
        // GraphicsConfig resolves through the component registry, AudioClip
        // through the resource-asset registry; the made-up type falls back
        // to "?" origin / payload without erroring.
        let (_dir, path) = write_world(concat!(
            "{\"name\":\"gfx\",\"type\":\"GraphicsConfig\",\"args\":{}}\n",
            "{\"name\":\"clip\",\"type\":\"AudioClip\",\"args\":{}}\n",
            "{\"name\":\"odd\",\"type\":\"NotARealAssetType\",\"args\":{}}\n",
            "{\"type\":\"GraphicsConfig\",\"args\":{}}\n",
        ));
        list(Some(&path), false, false).unwrap();
    }

    #[test]
    fn registration_for_resolves_component_types() {
        let r = registration_for("GraphicsConfig").unwrap();
        assert_eq!(r.type_name, "GraphicsConfig");
    }

    #[test]
    fn registration_for_resolves_resource_assets() {
        // A resource asset is a registered type like any other; what marks it is
        // the handle space it reports, not a separate registry.
        for name in ["AudioClip", "Texture"] {
            assert!(RegisteredType::parse(name).is_some_and(|t| t.is_resource()));
            let r = registration_for(name).unwrap();
            assert_eq!(
                r.origin,
                concinnity_cook::authoring::registry::AssetOrigin::External
            );
            assert_eq!(
                r.payload,
                concinnity_cook::authoring::registry::AssetPayload::Compiled
            );
        }
    }

    #[test]
    fn registration_for_unknown_type_is_none() {
        assert!(registration_for("NotARealAssetType").is_none());
    }

    #[test]
    fn list_with_invalid_json_errors() {
        let (_dir, path) = write_world("{ not json\n");
        let err = list(Some(&path), false, false).unwrap_err();
        assert_eq!(err.kind(), std::io::ErrorKind::InvalidData);
    }

    #[test]
    fn list_expanded_runs_the_build_front_half() {
        let (_dir, path) =
            write_world("{\"name\":\"gfx\",\"type\":\"GraphicsConfig\",\"args\":{}}\n");
        list(Some(&path), true, false).unwrap();
    }

    #[test]
    fn list_expanded_rejects_an_unknown_asset_type() {
        let (_dir, path) =
            write_world("{\"name\":\"odd\",\"type\":\"NotARealAssetType\",\"args\":{}}\n");
        assert!(list(Some(&path), true, false).is_err());
    }

    // An unreadable world is reported rather than panicking. A directory stands
    // in for the unreadable file: it passes the exists() check that selects the
    // explicit path, then fails the read.
    #[test]
    fn list_of_an_unreadable_world_surfaces_the_read_error() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().to_string_lossy().into_owned();
        assert!(list(Some(&path), false, false).is_err());
    }

    // An empty world expands to nothing (injection is conditional on what the
    // world declares), so the expanded listing has no table to print.
    #[test]
    fn list_expanded_of_an_empty_world_is_ok() {
        let (_dir, path) = write_world("");
        list(Some(&path), true, false).unwrap();
    }

    // Likewise the schedule: with nothing declared, no system gates in.
    #[test]
    fn list_systems_of_an_empty_world_is_ok() {
        let (_dir, path) = write_world("");
        list(Some(&path), false, true).unwrap();
    }

    #[test]
    fn manifest_lines_of_an_empty_world_are_empty() {
        let world = crate::build_world_from_str("").unwrap();
        assert!(manifest_lines(&world).is_empty());
    }
}