Skip to main content

concinnity_dev/authoring/
build.rs

1// src/build.rs: shared in-memory build orchestration
2
3pub(crate) use concinnity_cook::build_compiled;
4
5use crate::ecs::{ComponentAsset, World};
6use concinnity_cook::world::LoadedWorld;
7
8// Load, validate, and (when server credentials are present) fetch the missing
9// source files for a world. The returned LoadedWorld has passed the full
10// validation front half and is ready for concinnity_cook::build_compiled.
11//
12// This is the shared front half of every in-memory build: `build_world_from_path`
13// (the CLI interpreted `run` and the FFI preview) funnels through here so
14// validation and asset fetching behave identically. The `cn build` blob path
15// prepares through concinnity_cook directly and does not use this.
16pub(crate) fn prepare(content: &str) -> std::io::Result<LoadedWorld> {
17    // Install this build's shader toolchain (and the backend's shader-layout
18    // validator, where it ships one) before any shader compiles: the cook has no
19    // compiler of its own, and a user shader that mis-declares an engine buffer
20    // struct should fail the build with a clear message instead of faulting the
21    // GPU at run time. Idempotent, so covering `run` and the FFI entry points
22    // here costs nothing when the CLI already installed at startup.
23    concinnity_shader::install();
24
25    let loaded =
26        concinnity_cook::prepare_world(content, super::assets_root::assets_dir().as_deref())
27            .map_err(|errs| concinnity_cook::check::report_validation_errors(&errs))?;
28
29    Ok(loaded)
30}
31
32// Normalized asset-type match (lowercase, underscores stripped), matching the
33// convention used across the cook world passes.
34fn type_is(asset: &concinnity_cook::world::WorldJsonlAsset, norm_type: &str) -> bool {
35    asset.asset_type.to_lowercase().replace('_', "") == norm_type
36}
37
38// The first declared ColorLut's authored `source` path (non-empty), or `None`.
39// Dev-only; feeds the hot-reload watcher.
40fn scan_color_lut_source(assets: &[concinnity_cook::world::WorldJsonlAsset]) -> Option<String> {
41    assets
42        .iter()
43        .find(|a| type_is(a, "colorlut"))
44        .and_then(|a| a.args.get("source").and_then(|v| v.as_str()))
45        .filter(|s| !s.is_empty())
46        .map(str::to_string)
47}
48
49// The first declared file-backed EnvironmentMap's re-bake inputs, or `None` (a
50// procedural `generator` has no file to watch). The face-size / sample defaults
51// mirror the EnvironmentMap schema defaults in `concinnity-core/src/components/environment_map.rs`.
52fn scan_environment_map_source(
53    assets: &[concinnity_cook::world::WorldJsonlAsset],
54) -> Option<crate::resource::EnvironmentMapSourceInfo> {
55    let a = assets.iter().find(|a| type_is(a, "environmentmap"))?;
56    let generator = a
57        .args
58        .get("generator")
59        .and_then(|v| v.as_str())
60        .unwrap_or("");
61    let source = a.args.get("source").and_then(|v| v.as_str()).unwrap_or("");
62    if !generator.is_empty() || source.is_empty() {
63        return None;
64    }
65    let u32_arg = |key: &str, default: u32| {
66        a.args
67            .get(key)
68            .and_then(|v| v.as_u64())
69            .map(|v| v as u32)
70            .unwrap_or(default)
71    };
72    Some(crate::resource::EnvironmentMapSourceInfo {
73        source: source.to_string(),
74        prefilter_face_size: u32_arg("prefilter_face_size", 512),
75        irradiance_face_size: u32_arg("irradiance_face_size", 8),
76        prefilter_samples: u32_arg("prefilter_samples", 1024),
77        prefilter_clamp: a
78            .args
79            .get("prefilter_clamp")
80            .and_then(|v| v.as_f64())
81            .map(|v| v as f32)
82            .unwrap_or(12.0),
83    })
84}
85
86/// Compile a prepared world and assemble it into an in-memory World, ready to
87/// run without touching any blob files on disk.
88pub fn world_from_loaded(loaded: LoadedWorld) -> std::io::Result<World> {
89    // Capture the dev-only hot-reload source info for the singleton ColorLut and
90    // EnvironmentMap resources BEFORE `build_compiled` consumes the asset list.
91    // These kinds are authored (never injected by an expansion pass), so the raw
92    // world list carries every one; the renderer's `capture_sources` path reads
93    // these to seed the file-reload watcher now that the drained `source` field is
94    // gone. Only the first of each is used (the runtime uses handle 0).
95    let color_lut_source = scan_color_lut_source(&loaded.assets);
96    let environment_map_source = scan_environment_map_source(&loaded.assets);
97
98    let mut result = build_compiled(
99        loaded.assets,
100        super::assets_root::assets_dir().as_deref(),
101        None,
102    )?;
103
104    // The material name catalogue, read before the result is taken apart below.
105    let material_names = crate::resource::MaterialNames(
106        result.resource_names(concinnity_cook::resource_handles::ResourceKind::Material),
107    );
108
109    let payload_sections: Vec<Option<Vec<u8>>> = result.payloads.into_iter().map(Some).collect();
110    let mut world =
111        concinnity_engine::blob::world_from(crate::blob::BlobData::new(payload_sections));
112    // Index every named component's entity as it is minted, matching the
113    // shipped runtime's `load_blob`, so name references resolve for any type.
114    let mut by_name = std::collections::BTreeMap::new();
115    for def in &result.defs {
116        let mut component = ComponentAsset::from_baked(def).map_err(|e| {
117            std::io::Error::new(
118                std::io::ErrorKind::InvalidData,
119                format!("Asset construction failed: {:?}", e),
120            )
121        })?;
122        if let Some(locator) = &def.payload {
123            component.inject_locator(locator.clone());
124        }
125        let entity = world.add(component);
126        if let Some(id) = def.name {
127            by_name.insert(id, entity);
128        }
129    }
130    world.insert_resource(concinnity_core::ecs::EntityByName(by_name));
131    // Load the compiled resource stream into its per-kind tables, exactly as the
132    // shipped runtime's `load_blob` does, so the in-memory `cn debug` world reads
133    // audio clips and textures by handle too.
134    crate::resource::install_resource_tables(&mut world, &mut result.resources);
135    world.insert_resource(crate::ecs::BlobSceneGroups(result.scene_groups));
136    world.insert_resource(crate::ecs::BlobMeshBounds(result.mesh_bounds));
137    if let Some(budget) = result.physics_budget {
138        world.insert_resource(concinnity_core::ecs::WorldPhysicsBudget(budget));
139    }
140    // Dev-only source catalogues for the hot-reload watcher (see the scan above).
141    world.insert_resource(crate::resource::ColorLutSources(color_lut_source));
142    world.insert_resource(crate::resource::EnvironmentMapSources(
143        environment_map_source,
144    ));
145    // Dev-only: the texture source catalogue, so the renderer's hot-reload
146    // capture and the runtime spawn-by-name path can map a texture handle back to
147    // its file / name. Not present in the shipped `load_blob` path.
148    world.insert_resource(crate::resource::TextureSources(
149        result
150            .texture_sources
151            .iter()
152            .map(|t| crate::resource::TextureSource {
153                name_id: t.name_id,
154                source: t.source.clone(),
155                image_index: t.image_index,
156            })
157            .collect(),
158    ));
159    // Dev-only: the material name catalogue, so the editor's live draw seam can
160    // resolve a material an edit names to the handle it was compiled at.
161    world.insert_resource(material_names);
162    // Dev-only: the mesh source catalogue, so the renderer's hot-reload capture
163    // can map a mesh handle back to the `.glb`/`.fbx` that backs it.
164    world.insert_resource(crate::resource::MeshSources(
165        result
166            .mesh_sources
167            .iter()
168            .map(|m| crate::resource::MeshSource {
169                source: m.source.clone(),
170                primitive_index: m.primitive_index,
171                lod_levels: m.lod_levels,
172                lod_distances: m.lod_distances.clone(),
173            })
174            .collect(),
175    ));
176    Ok(world)
177}
178
179/// Run the full in-memory pipeline on a world.jsonl string, returning a
180/// ready-to-run World without touching any blob files on disk. The editor uses
181/// this to boot an empty (or otherwise non-renderable) world from a seeded
182/// GraphicsConfig so a window still opens.
183pub fn build_world_from_str(content: &str) -> std::io::Result<World> {
184    Ok(build_world_and_shadows(content)?.0)
185}
186
187/// `build_world_from_str`, plus the pre-merge args of every generated asset the
188/// world patches. An authored line over a generated asset is a sparse patch, so
189/// a tool that re-derives one asset's effective args from its line alone needs
190/// the baseline the patch merges over.
191pub(crate) fn build_world_and_shadows(
192    content: &str,
193) -> std::io::Result<(World, Vec<concinnity_cook::world::ShadowedAsset>)> {
194    let loaded = prepare(content)?;
195    let shadowed = loaded.shadowed.clone();
196    Ok((world_from_loaded(loaded)?, shadowed))
197}
198
199/// Read a world.jsonl file from disk and run the full in-memory pipeline on it,
200/// returning a ready-to-run World. The interpreted `run` (in the CLI crate)
201/// loads its world through here; it is the file-backed counterpart of `prepare`
202/// + `world_from_loaded`.
203pub fn build_world_from_path(world_path: &str) -> std::io::Result<World> {
204    let content = std::fs::read_to_string(world_path)?;
205    build_world_from_str(&content)
206}
207
208/// Compile a world.jsonl file and write the compiled blobs + world-lock.json to
209/// the active state dir's `data/`, exactly as `cn build` does. This is
210/// `cn build` as a library call: the editor's SAVE goes through here to persist
211/// edits, reusing the validated compile + blob-write tail rather than patching
212/// blobs directly. Same-process recompiles are fast because the payload / expand
213/// caches are warm.
214pub fn build_world_to_disk(world_path: &str) -> std::io::Result<()> {
215    let content = std::fs::read_to_string(world_path)?;
216    build_world_str_to_disk(&content)
217}
218
219// The string-backed tail of `build_world_to_disk`: compile world content and
220// write the blobs + lock without reading (or writing) a world.jsonl. The
221// editor console's build command goes through here so it compiles the
222// in-memory entries as they stand, saved or not.
223pub(crate) fn build_world_str_to_disk(content: &str) -> std::io::Result<()> {
224    build_world_str_to_disk_with_progress(content, None)
225}
226
227// `build_world_str_to_disk` with a compile-progress callback (the editor's
228// cook workers feed their operation card through it).
229pub(crate) fn build_world_str_to_disk_with_progress(
230    content: &str,
231    progress: Option<&(dyn Fn(concinnity_cook::BuildProgress) + Sync)>,
232) -> std::io::Result<()> {
233    let loaded = prepare(content)?;
234    let result = concinnity_cook::build_compiled_with_progress(
235        loaded.assets,
236        super::assets_root::assets_dir().as_deref(),
237        None,
238        progress,
239    )?;
240    if let Some(p) = progress {
241        p(concinnity_cook::BuildProgress {
242            stage: "write",
243            done: 0,
244            total: 0,
245        });
246    }
247    concinnity_cook::write_build_outputs(&result, &loaded.injected, &loaded.shadowed)?;
248    Ok(())
249}
250
251#[cfg(test)]
252mod tests {
253    use super::*;
254
255    #[test]
256    fn prepare_accepts_a_valid_world() {
257        let loaded =
258            prepare("{\"name\":\"phys\",\"type\":\"PhysicsConfig\",\"args\":{}}\n").unwrap();
259        assert!(loaded.assets.iter().any(|a| a.name == "phys"));
260        assert!(loaded.authored.contains(&"phys".to_string()));
261    }
262
263    #[test]
264    fn prepare_rejects_an_invalid_world() {
265        assert!(prepare("{\"name\":\"odd\",\"type\":\"NotARealAssetType\"}\n").is_err());
266        assert!(prepare("{ not json\n").is_err());
267    }
268
269    fn asset(json: serde_json::Value) -> concinnity_cook::world::WorldJsonlAsset {
270        concinnity_cook::world::WorldJsonlAsset::from_value(&json)
271    }
272
273    // The type match is the cook's normalized one, so `color_lut`, `ColorLut`,
274    // and `colorlut` all name the same kind.
275    #[test]
276    fn the_lut_scan_takes_the_first_source_however_the_type_is_spelled() {
277        for ty in ["ColorLut", "color_lut", "colorlut", "COLOR_LUT"] {
278            let assets = [asset(
279                serde_json::json!({"name":"grade","type":ty,"args":{"source":"luts/warm.cube"}}),
280            )];
281            assert_eq!(
282                scan_color_lut_source(&assets),
283                Some("luts/warm.cube".to_string()),
284                "type {ty}"
285            );
286        }
287
288        // Only the first is used: the runtime binds handle 0.
289        let assets = [
290            asset(serde_json::json!({"name":"a","type":"ColorLut","args":{"source":"first.cube"}})),
291            asset(
292                serde_json::json!({"name":"b","type":"ColorLut","args":{"source":"second.cube"}}),
293            ),
294        ];
295        assert_eq!(
296            scan_color_lut_source(&assets),
297            Some("first.cube".to_string())
298        );
299    }
300
301    // Nothing to watch: no LUT at all, or one with no authored source path.
302    #[test]
303    fn the_lut_scan_yields_nothing_without_a_source() {
304        assert_eq!(scan_color_lut_source(&[]), None);
305        let no_source = [asset(
306            serde_json::json!({"name":"grade","type":"ColorLut","args":{}}),
307        )];
308        assert_eq!(scan_color_lut_source(&no_source), None);
309        let empty = [asset(
310            serde_json::json!({"name":"grade","type":"ColorLut","args":{"source":""}}),
311        )];
312        assert_eq!(scan_color_lut_source(&empty), None);
313        let other_kind = [asset(
314            serde_json::json!({"name":"sky","type":"EnvironmentMap","args":{"source":"x.hdr"}}),
315        )];
316        assert_eq!(scan_color_lut_source(&other_kind), None);
317    }
318
319    // A file-backed environment map carries its re-bake inputs so the watcher
320    // can reproduce the original bake; unset ones fall back to the schema
321    // defaults rather than zero.
322    #[test]
323    fn the_environment_map_scan_defaults_the_unset_bake_inputs() {
324        let assets = [asset(
325            serde_json::json!({"name":"sky","type":"EnvironmentMap","args":{"source":"studio.hdr"}}),
326        )];
327        let info = scan_environment_map_source(&assets).expect("a file-backed map");
328        assert_eq!(info.source, "studio.hdr");
329        assert_eq!(info.prefilter_face_size, 512);
330        assert_eq!(info.irradiance_face_size, 8);
331        assert_eq!(info.prefilter_samples, 1024);
332        assert_eq!(info.prefilter_clamp, 12.0);
333    }
334
335    #[test]
336    fn the_environment_map_scan_carries_the_authored_bake_inputs() {
337        let assets = [asset(serde_json::json!({
338            "name":"sky","type":"environment_map","args":{
339                "source":"studio.hdr",
340                "prefilter_face_size": 256,
341                "irradiance_face_size": 16,
342                "prefilter_samples": 64,
343                "prefilter_clamp": 4.5
344            }
345        }))];
346        let info = scan_environment_map_source(&assets).expect("a file-backed map");
347        assert_eq!(info.prefilter_face_size, 256);
348        assert_eq!(info.irradiance_face_size, 16);
349        assert_eq!(info.prefilter_samples, 64);
350        assert_eq!(info.prefilter_clamp, 4.5);
351    }
352
353    // A procedural map has no file behind it, so there is nothing to watch --
354    // even when a stale `source` is still authored alongside the generator.
355    #[test]
356    fn the_environment_map_scan_skips_a_procedural_map() {
357        let generated = [asset(serde_json::json!({
358            "name":"sky","type":"EnvironmentMap","args":{"generator":"sky"}
359        }))];
360        assert!(scan_environment_map_source(&generated).is_none());
361
362        let both = [asset(serde_json::json!({
363            "name":"sky","type":"EnvironmentMap","args":{"generator":"sky","source":"studio.hdr"}
364        }))];
365        assert!(scan_environment_map_source(&both).is_none());
366
367        assert!(scan_environment_map_source(&[]).is_none());
368        let no_source = [asset(
369            serde_json::json!({"name":"sky","type":"EnvironmentMap","args":{}}),
370        )];
371        assert!(scan_environment_map_source(&no_source).is_none());
372    }
373
374    // The assembled world publishes both dev-only source catalogues, which is
375    // what seeds the hot-reload watcher.
376    #[test]
377    fn the_assembled_world_publishes_the_watcher_source_catalogues() {
378        let loaded =
379            prepare("{\"name\":\"phys\",\"type\":\"PhysicsConfig\",\"args\":{}}\n").unwrap();
380        let world = world_from_loaded(loaded).unwrap();
381        assert!(
382            world
383                .resource::<crate::resource::ColorLutSources>()
384                .is_some_and(|s| s.0.is_none()),
385            "a world with no LUT publishes an empty catalogue, not none at all"
386        );
387        assert!(
388            world
389                .resource::<crate::resource::EnvironmentMapSources>()
390                .is_some()
391        );
392    }
393
394    #[test]
395    fn world_from_loaded_assembles_an_in_memory_world() {
396        let loaded =
397            prepare("{\"name\":\"phys\",\"type\":\"PhysicsConfig\",\"args\":{}}\n").unwrap();
398        let expanded = loaded.assets.len();
399        let world = world_from_loaded(loaded).unwrap();
400        // Every expanded asset landed as a component; nothing was dropped on
401        // the way through compile + assembly.
402        assert_eq!(world.component_count(), expanded);
403        // Every named component's entity is indexed, so name references
404        // resolve for any type, not just decomposed Props.
405        let index = world
406            .resource::<concinnity_core::ecs::EntityByName>()
407            .expect("assembly publishes the name -> entity index");
408        assert_eq!(index.0.len(), expanded);
409    }
410
411    #[test]
412    fn build_world_from_str_assembles_an_in_memory_world() {
413        // The string path is what the editor uses to seed an empty world; it
414        // must produce the same assembled world as the file-backed path.
415        let world =
416            build_world_from_str("{\"name\":\"phys\",\"type\":\"PhysicsConfig\",\"args\":{}}\n")
417                .unwrap();
418        assert!(world.component_count() >= 1);
419    }
420
421    #[test]
422    fn build_world_from_missing_path_is_not_found() {
423        let err = build_world_from_path("/no/such/concinnity-world-xyz.jsonl")
424            .expect_err("a missing world path must error");
425        assert_eq!(err.kind(), std::io::ErrorKind::NotFound);
426    }
427
428    // Restores the previous working directory on drop, so a chdir-in-test does
429    // not leak into other tests (they run in parallel threads of one process).
430    struct CwdGuard(std::path::PathBuf);
431    impl Drop for CwdGuard {
432        fn drop(&mut self) {
433            let _ = std::env::set_current_dir(&self.0);
434        }
435    }
436
437    // Clears the process-global state root on the way out, for the same reason.
438    struct StateDirGuard;
439    impl Drop for StateDirGuard {
440        fn drop(&mut self) {
441            concinnity_host::store::paths::clear_state_dir();
442        }
443    }
444
445    // The in-memory build records each compiled Material's identity, dense by
446    // the handle cook assigned it, so the live draw seam can resolve a
447    // material an edit names against the running world.
448    #[test]
449    fn an_in_memory_build_records_its_material_identities() {
450        let _guard = crate::test_support::lock();
451        crate::test_support::isolate_state_dir();
452        let world = build_world_from_str(concat!(
453            "{\"name\":\"steel\",\"type\":\"Material\",\"args\":{\"roughness\":0.4}}\n",
454            "{\"name\":\"glass\",\"type\":\"Material\",\"args\":{\"transparent\":true}}\n",
455        ))
456        .expect("a material-only world compiles");
457        let names = world
458            .resource::<crate::resource::MaterialNames>()
459            .expect("the catalogue is installed");
460        assert_eq!(
461            names.0,
462            vec![
463                crate::ecs::asset_id::intern("steel").0,
464                crate::ecs::asset_id::intern("glass").0,
465            ],
466            "declaration order is handle order"
467        );
468    }
469
470    // build_world_to_disk compiles a world.jsonl and writes the blobs + lock to
471    // the installed state tree, exactly as `cn build` does. Runs under the
472    // process cwd lock in an isolated temp dir so it neither races other tests
473    // nor pollutes the repo. Uses a payload-free world (PhysicsConfig) so it
474    // needs no source files or shader compilation.
475    #[test]
476    fn build_world_to_disk_writes_blobs_and_lock() {
477        let _guard = crate::test_support::lock();
478        let dir = tempfile::tempdir().unwrap();
479        let prev = std::env::current_dir().unwrap();
480        std::env::set_current_dir(dir.path()).unwrap();
481        let _cwd = CwdGuard(prev);
482        // The lock file is written relative to the cwd; the blobs go wherever
483        // the state root points, which nothing installs by default.
484        concinnity_host::store::paths::set_state_dir(dir.path());
485        let _state = StateDirGuard;
486
487        std::fs::write(
488            "world.jsonl",
489            "{\"name\":\"phys\",\"type\":\"PhysicsConfig\",\"args\":{}}\n",
490        )
491        .unwrap();
492
493        build_world_to_disk("world.jsonl").expect("compile + write should succeed");
494
495        // The primary blob (data/0) and the provenance lock are both written.
496        assert!(
497            concinnity_host::store::paths::data_dir()
498                .expect("the test installs a state dir")
499                .join("0")
500                .exists(),
501            "data/0 blob written"
502        );
503        assert!(
504            dir.path().join("world-lock.json").exists(),
505            "world-lock.json written"
506        );
507    }
508}