pub(crate) use concinnity_cook::build_compiled;
use crate::ecs::{ComponentAsset, World};
use concinnity_cook::world::LoadedWorld;
pub(crate) fn prepare(content: &str) -> std::io::Result<LoadedWorld> {
concinnity_shader::install();
let loaded =
concinnity_cook::prepare_world(content, super::assets_root::assets_dir().as_deref())
.map_err(|errs| concinnity_cook::check::report_validation_errors(&errs))?;
Ok(loaded)
}
fn type_is(asset: &concinnity_cook::world::WorldJsonlAsset, norm_type: &str) -> bool {
asset.asset_type.to_lowercase().replace('_', "") == norm_type
}
fn scan_color_lut_source(assets: &[concinnity_cook::world::WorldJsonlAsset]) -> Option<String> {
assets
.iter()
.find(|a| type_is(a, "colorlut"))
.and_then(|a| a.args.get("source").and_then(|v| v.as_str()))
.filter(|s| !s.is_empty())
.map(str::to_string)
}
fn scan_environment_map_source(
assets: &[concinnity_cook::world::WorldJsonlAsset],
) -> Option<crate::resource::EnvironmentMapSourceInfo> {
let a = assets.iter().find(|a| type_is(a, "environmentmap"))?;
let generator = a
.args
.get("generator")
.and_then(|v| v.as_str())
.unwrap_or("");
let source = a.args.get("source").and_then(|v| v.as_str()).unwrap_or("");
if !generator.is_empty() || source.is_empty() {
return None;
}
let u32_arg = |key: &str, default: u32| {
a.args
.get(key)
.and_then(|v| v.as_u64())
.map(|v| v as u32)
.unwrap_or(default)
};
Some(crate::resource::EnvironmentMapSourceInfo {
source: source.to_string(),
prefilter_face_size: u32_arg("prefilter_face_size", 512),
irradiance_face_size: u32_arg("irradiance_face_size", 8),
prefilter_samples: u32_arg("prefilter_samples", 1024),
prefilter_clamp: a
.args
.get("prefilter_clamp")
.and_then(|v| v.as_f64())
.map(|v| v as f32)
.unwrap_or(12.0),
})
}
pub fn world_from_loaded(loaded: LoadedWorld) -> std::io::Result<World> {
let color_lut_source = scan_color_lut_source(&loaded.assets);
let environment_map_source = scan_environment_map_source(&loaded.assets);
let mut result = build_compiled(
loaded.assets,
super::assets_root::assets_dir().as_deref(),
None,
)?;
let material_names = crate::resource::MaterialNames(
result.resource_names(concinnity_cook::resource_handles::ResourceKind::Material),
);
let payload_sections: Vec<Option<Vec<u8>>> = result.payloads.into_iter().map(Some).collect();
let mut world =
concinnity_engine::blob::world_from(crate::blob::BlobData::new(payload_sections));
let mut by_name = std::collections::BTreeMap::new();
for def in &result.defs {
let mut component = ComponentAsset::from_baked(def).map_err(|e| {
std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!("Asset construction failed: {:?}", e),
)
})?;
if let Some(locator) = &def.payload {
component.inject_locator(locator.clone());
}
let entity = world.add(component);
if let Some(id) = def.name {
by_name.insert(id, entity);
}
}
world.insert_resource(concinnity_core::ecs::EntityByName(by_name));
crate::resource::install_resource_tables(&mut world, &mut result.resources);
world.insert_resource(crate::ecs::BlobSceneGroups(result.scene_groups));
world.insert_resource(crate::ecs::BlobMeshBounds(result.mesh_bounds));
if let Some(budget) = result.physics_budget {
world.insert_resource(concinnity_core::ecs::WorldPhysicsBudget(budget));
}
world.insert_resource(crate::resource::ColorLutSources(color_lut_source));
world.insert_resource(crate::resource::EnvironmentMapSources(
environment_map_source,
));
world.insert_resource(crate::resource::TextureSources(
result
.texture_sources
.iter()
.map(|t| crate::resource::TextureSource {
name_id: t.name_id,
source: t.source.clone(),
image_index: t.image_index,
})
.collect(),
));
world.insert_resource(material_names);
world.insert_resource(crate::resource::MeshSources(
result
.mesh_sources
.iter()
.map(|m| crate::resource::MeshSource {
source: m.source.clone(),
primitive_index: m.primitive_index,
lod_levels: m.lod_levels,
lod_distances: m.lod_distances.clone(),
})
.collect(),
));
Ok(world)
}
pub fn build_world_from_str(content: &str) -> std::io::Result<World> {
Ok(build_world_and_shadows(content)?.0)
}
pub(crate) fn build_world_and_shadows(
content: &str,
) -> std::io::Result<(World, Vec<concinnity_cook::world::ShadowedAsset>)> {
let loaded = prepare(content)?;
let shadowed = loaded.shadowed.clone();
Ok((world_from_loaded(loaded)?, shadowed))
}
pub fn build_world_from_path(world_path: &str) -> std::io::Result<World> {
let content = std::fs::read_to_string(world_path)?;
build_world_from_str(&content)
}
pub fn build_world_to_disk(world_path: &str) -> std::io::Result<()> {
let content = std::fs::read_to_string(world_path)?;
build_world_str_to_disk(&content)
}
pub(crate) fn build_world_str_to_disk(content: &str) -> std::io::Result<()> {
build_world_str_to_disk_with_progress(content, None)
}
pub(crate) fn build_world_str_to_disk_with_progress(
content: &str,
progress: Option<&(dyn Fn(concinnity_cook::BuildProgress) + Sync)>,
) -> std::io::Result<()> {
let loaded = prepare(content)?;
let result = concinnity_cook::build_compiled_with_progress(
loaded.assets,
super::assets_root::assets_dir().as_deref(),
None,
progress,
)?;
if let Some(p) = progress {
p(concinnity_cook::BuildProgress {
stage: "write",
done: 0,
total: 0,
});
}
concinnity_cook::write_build_outputs(&result, &loaded.injected, &loaded.shadowed)?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn prepare_accepts_a_valid_world() {
let loaded =
prepare("{\"name\":\"phys\",\"type\":\"PhysicsConfig\",\"args\":{}}\n").unwrap();
assert!(loaded.assets.iter().any(|a| a.name == "phys"));
assert!(loaded.authored.contains(&"phys".to_string()));
}
#[test]
fn prepare_rejects_an_invalid_world() {
assert!(prepare("{\"name\":\"odd\",\"type\":\"NotARealAssetType\"}\n").is_err());
assert!(prepare("{ not json\n").is_err());
}
fn asset(json: serde_json::Value) -> concinnity_cook::world::WorldJsonlAsset {
concinnity_cook::world::WorldJsonlAsset::from_value(&json)
}
#[test]
fn the_lut_scan_takes_the_first_source_however_the_type_is_spelled() {
for ty in ["ColorLut", "color_lut", "colorlut", "COLOR_LUT"] {
let assets = [asset(
serde_json::json!({"name":"grade","type":ty,"args":{"source":"luts/warm.cube"}}),
)];
assert_eq!(
scan_color_lut_source(&assets),
Some("luts/warm.cube".to_string()),
"type {ty}"
);
}
let assets = [
asset(serde_json::json!({"name":"a","type":"ColorLut","args":{"source":"first.cube"}})),
asset(
serde_json::json!({"name":"b","type":"ColorLut","args":{"source":"second.cube"}}),
),
];
assert_eq!(
scan_color_lut_source(&assets),
Some("first.cube".to_string())
);
}
#[test]
fn the_lut_scan_yields_nothing_without_a_source() {
assert_eq!(scan_color_lut_source(&[]), None);
let no_source = [asset(
serde_json::json!({"name":"grade","type":"ColorLut","args":{}}),
)];
assert_eq!(scan_color_lut_source(&no_source), None);
let empty = [asset(
serde_json::json!({"name":"grade","type":"ColorLut","args":{"source":""}}),
)];
assert_eq!(scan_color_lut_source(&empty), None);
let other_kind = [asset(
serde_json::json!({"name":"sky","type":"EnvironmentMap","args":{"source":"x.hdr"}}),
)];
assert_eq!(scan_color_lut_source(&other_kind), None);
}
#[test]
fn the_environment_map_scan_defaults_the_unset_bake_inputs() {
let assets = [asset(
serde_json::json!({"name":"sky","type":"EnvironmentMap","args":{"source":"studio.hdr"}}),
)];
let info = scan_environment_map_source(&assets).expect("a file-backed map");
assert_eq!(info.source, "studio.hdr");
assert_eq!(info.prefilter_face_size, 512);
assert_eq!(info.irradiance_face_size, 8);
assert_eq!(info.prefilter_samples, 1024);
assert_eq!(info.prefilter_clamp, 12.0);
}
#[test]
fn the_environment_map_scan_carries_the_authored_bake_inputs() {
let assets = [asset(serde_json::json!({
"name":"sky","type":"environment_map","args":{
"source":"studio.hdr",
"prefilter_face_size": 256,
"irradiance_face_size": 16,
"prefilter_samples": 64,
"prefilter_clamp": 4.5
}
}))];
let info = scan_environment_map_source(&assets).expect("a file-backed map");
assert_eq!(info.prefilter_face_size, 256);
assert_eq!(info.irradiance_face_size, 16);
assert_eq!(info.prefilter_samples, 64);
assert_eq!(info.prefilter_clamp, 4.5);
}
#[test]
fn the_environment_map_scan_skips_a_procedural_map() {
let generated = [asset(serde_json::json!({
"name":"sky","type":"EnvironmentMap","args":{"generator":"sky"}
}))];
assert!(scan_environment_map_source(&generated).is_none());
let both = [asset(serde_json::json!({
"name":"sky","type":"EnvironmentMap","args":{"generator":"sky","source":"studio.hdr"}
}))];
assert!(scan_environment_map_source(&both).is_none());
assert!(scan_environment_map_source(&[]).is_none());
let no_source = [asset(
serde_json::json!({"name":"sky","type":"EnvironmentMap","args":{}}),
)];
assert!(scan_environment_map_source(&no_source).is_none());
}
#[test]
fn the_assembled_world_publishes_the_watcher_source_catalogues() {
let loaded =
prepare("{\"name\":\"phys\",\"type\":\"PhysicsConfig\",\"args\":{}}\n").unwrap();
let world = world_from_loaded(loaded).unwrap();
assert!(
world
.resource::<crate::resource::ColorLutSources>()
.is_some_and(|s| s.0.is_none()),
"a world with no LUT publishes an empty catalogue, not none at all"
);
assert!(
world
.resource::<crate::resource::EnvironmentMapSources>()
.is_some()
);
}
#[test]
fn world_from_loaded_assembles_an_in_memory_world() {
let loaded =
prepare("{\"name\":\"phys\",\"type\":\"PhysicsConfig\",\"args\":{}}\n").unwrap();
let expanded = loaded.assets.len();
let world = world_from_loaded(loaded).unwrap();
assert_eq!(world.component_count(), expanded);
let index = world
.resource::<concinnity_core::ecs::EntityByName>()
.expect("assembly publishes the name -> entity index");
assert_eq!(index.0.len(), expanded);
}
#[test]
fn build_world_from_str_assembles_an_in_memory_world() {
let world =
build_world_from_str("{\"name\":\"phys\",\"type\":\"PhysicsConfig\",\"args\":{}}\n")
.unwrap();
assert!(world.component_count() >= 1);
}
#[test]
fn build_world_from_missing_path_is_not_found() {
let err = build_world_from_path("/no/such/concinnity-world-xyz.jsonl")
.expect_err("a missing world path must error");
assert_eq!(err.kind(), std::io::ErrorKind::NotFound);
}
struct CwdGuard(std::path::PathBuf);
impl Drop for CwdGuard {
fn drop(&mut self) {
let _ = std::env::set_current_dir(&self.0);
}
}
struct StateDirGuard;
impl Drop for StateDirGuard {
fn drop(&mut self) {
concinnity_host::store::paths::clear_state_dir();
}
}
#[test]
fn an_in_memory_build_records_its_material_identities() {
let _guard = crate::test_support::lock();
crate::test_support::isolate_state_dir();
let world = build_world_from_str(concat!(
"{\"name\":\"steel\",\"type\":\"Material\",\"args\":{\"roughness\":0.4}}\n",
"{\"name\":\"glass\",\"type\":\"Material\",\"args\":{\"transparent\":true}}\n",
))
.expect("a material-only world compiles");
let names = world
.resource::<crate::resource::MaterialNames>()
.expect("the catalogue is installed");
assert_eq!(
names.0,
vec![
crate::ecs::asset_id::intern("steel").0,
crate::ecs::asset_id::intern("glass").0,
],
"declaration order is handle order"
);
}
#[test]
fn build_world_to_disk_writes_blobs_and_lock() {
let _guard = crate::test_support::lock();
let dir = tempfile::tempdir().unwrap();
let prev = std::env::current_dir().unwrap();
std::env::set_current_dir(dir.path()).unwrap();
let _cwd = CwdGuard(prev);
concinnity_host::store::paths::set_state_dir(dir.path());
let _state = StateDirGuard;
std::fs::write(
"world.jsonl",
"{\"name\":\"phys\",\"type\":\"PhysicsConfig\",\"args\":{}}\n",
)
.unwrap();
build_world_to_disk("world.jsonl").expect("compile + write should succeed");
assert!(
concinnity_host::store::paths::data_dir()
.expect("the test installs a state dir")
.join("0")
.exists(),
"data/0 blob written"
);
assert!(
dir.path().join("world-lock.json").exists(),
"world-lock.json written"
);
}
}