Build production-ready editor authoring workflows
CI / Format, lint, test, build (push) Waiting to run

This commit is contained in:
Rbanh committed 2026-07-11 12:41:04 -04:00
1 parent cc1fa6ea3b
commit 0553a85220
163 files changed
+34547 -1565

No files matched your search

+3
View File
@@ -6,6 +6,9 @@ license.workspace = true
description = "Level scene schema versioning and validation (no Bevy dependency)"
[dependencies]
blake3 = "1"
serde = { workspace = true }
ron = "0.8"
ron-edit = "=0.2.0"
shared.workspace = true
settings.workspace = true
+279
View File
@@ -0,0 +1,279 @@
//! Stable subscene reference validation for authored level compositions.
use std::collections::{HashMap, HashSet};
use std::path::{Component, Path, PathBuf};
use shared::SceneComposition;
use crate::document::SceneDocument;
pub fn validate_scene_composition(composition: &SceneComposition) -> Result<(), String> {
if composition.scene_id.trim().is_empty() {
return Err("scene composition has an empty scene_id".to_string());
}
let mut reference_ids = HashSet::new();
for reference in &composition.subscenes {
if reference.id.trim().is_empty() {
return Err("subscene reference has an empty id".to_string());
}
if !reference_ids.insert(reference.id.as_str()) {
return Err(format!(
"scene composition contains duplicate subscene id `{}`",
reference.id
));
}
validate_project_relative_path(&reference.path)?;
}
Ok(())
}
pub fn validate_composition_graph(entry: &Path, project_root: &Path) -> Result<(), String> {
let entry = canonical_existing(entry)?;
let project_root = canonical_existing(project_root)?;
let mut visiting = Vec::new();
let mut visited = HashSet::new();
let mut scene_ids = HashMap::<String, PathBuf>::new();
visit_scene(
&entry,
&project_root,
&mut visiting,
&mut visited,
&mut scene_ids,
)
}
pub(crate) fn find_project_root(path: &Path) -> Option<PathBuf> {
let absolute = if path.is_absolute() {
path.to_path_buf()
} else {
std::env::current_dir().ok()?.join(path)
};
absolute.ancestors().find_map(|ancestor| {
ancestor
.join("assets/project.ron")
.is_file()
.then(|| ancestor.to_path_buf())
})
}
fn visit_scene(
path: &Path,
project_root: &Path,
visiting: &mut Vec<PathBuf>,
visited: &mut HashSet<PathBuf>,
scene_ids: &mut HashMap<String, PathBuf>,
) -> Result<(), String> {
if let Some(cycle_start) = visiting.iter().position(|candidate| candidate == path) {
let mut cycle: Vec<String> = visiting[cycle_start..]
.iter()
.map(|candidate| project_label(candidate, project_root))
.collect();
cycle.push(project_label(path, project_root));
return Err(format!("cyclic subscene reference: {}", cycle.join(" -> ")));
}
if !visited.insert(path.to_path_buf()) {
return Ok(());
}
let text = std::fs::read_to_string(path)
.map_err(|error| format!("could not read {}: {error}", path.display()))?;
let document = SceneDocument::from_ron_text(&text)
.map_err(|error| format!("{}: {error}", path.display()))?;
let Some(composition) = document.composition else {
return Ok(());
};
validate_scene_composition(&composition)
.map_err(|error| format!("{}: {error}", path.display()))?;
if let Some(existing) = scene_ids.insert(composition.scene_id.clone(), path.to_path_buf()) {
if existing != path {
return Err(format!(
"duplicate scene_id `{}` in {} and {}",
composition.scene_id,
existing.display(),
path.display()
));
}
}
visiting.push(path.to_path_buf());
for reference in composition.subscenes {
let target = canonical_project_path(project_root, &reference.path)?;
visit_scene(&target, project_root, visiting, visited, scene_ids)?;
}
visiting.pop();
Ok(())
}
fn canonical_project_path(project_root: &Path, relative: &str) -> Result<PathBuf, String> {
validate_project_relative_path(relative)?;
let target = project_root.join(relative);
let target = canonical_existing(&target).map_err(|error| {
format!(
"missing subscene `{relative}` under {}: {error}",
project_root.display()
)
})?;
if !target.starts_with(project_root) {
return Err(format!("subscene `{relative}` escapes the project root"));
}
Ok(target)
}
fn validate_project_relative_path(path: &str) -> Result<(), String> {
let path = Path::new(path);
if path.as_os_str().is_empty() || path.is_absolute() {
return Err(format!(
"subscene path `{}` must be project-relative",
path.display()
));
}
if path.components().any(|component| {
matches!(
component,
Component::ParentDir | Component::RootDir | Component::Prefix(_)
)
}) {
return Err(format!(
"subscene path `{}` may not escape the project root",
path.display()
));
}
if !path
.file_name()
.and_then(|name| name.to_str())
.is_some_and(|name| name.ends_with(".scn.ron"))
{
return Err(format!(
"subscene path `{}` must name a .scn.ron file",
path.display()
));
}
Ok(())
}
fn canonical_existing(path: &Path) -> Result<PathBuf, String> {
path.canonicalize()
.map_err(|error| format!("{}: {error}", path.display()))
}
fn project_label(path: &Path, project_root: &Path) -> String {
path.strip_prefix(project_root)
.unwrap_or(path)
.display()
.to_string()
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
use std::sync::atomic::{AtomicU64, Ordering};
static NEXT_FIXTURE: AtomicU64 = AtomicU64::new(1);
fn fixture_root() -> PathBuf {
let root = std::env::temp_dir().join(format!(
"blacksite-composition-{}-{}",
std::process::id(),
NEXT_FIXTURE.fetch_add(1, Ordering::Relaxed)
));
fs::create_dir_all(root.join("assets/levels")).unwrap();
fs::write(root.join("assets/project.ron"), "()").unwrap();
root
}
fn scene(scene_id: &str, references: &[(&str, &str)]) -> String {
let refs = references
.iter()
.map(|(id, path)| format!("(id:\"{id}\",path:\"{path}\",visible:true,locked:true)"))
.collect::<Vec<_>>()
.join(",");
format!(
"(schema_version:2,resources:{{\"shared::components::SceneComposition\":(scene_id:\"{scene_id}\",subscenes:[{refs}])}},entities:{{}})"
)
}
#[test]
fn valid_two_subscene_graph_passes() {
let root = fixture_root();
let main = root.join("assets/levels/main.scn.ron");
fs::write(
&main,
scene(
"main",
&[
("geometry", "assets/levels/geometry.scn.ron"),
("lighting", "assets/levels/lighting.scn.ron"),
],
),
)
.unwrap();
fs::write(
root.join("assets/levels/geometry.scn.ron"),
scene("geometry", &[]),
)
.unwrap();
fs::write(
root.join("assets/levels/lighting.scn.ron"),
scene("lighting", &[]),
)
.unwrap();
validate_composition_graph(&main, &root).unwrap();
fs::remove_dir_all(root).unwrap();
}
#[test]
fn missing_and_cyclic_references_are_rejected() {
let root = fixture_root();
let main = root.join("assets/levels/main.scn.ron");
fs::write(
&main,
scene("main", &[("missing", "assets/levels/missing.scn.ron")]),
)
.unwrap();
assert!(validate_composition_graph(&main, &root)
.unwrap_err()
.contains("missing subscene"));
let child = root.join("assets/levels/child.scn.ron");
fs::write(
&main,
scene("main", &[("child", "assets/levels/child.scn.ron")]),
)
.unwrap();
fs::write(
&child,
scene("child", &[("main", "assets/levels/main.scn.ron")]),
)
.unwrap();
assert!(validate_composition_graph(&main, &root)
.unwrap_err()
.contains("cyclic subscene reference"));
fs::remove_dir_all(root).unwrap();
}
#[test]
fn unsafe_paths_and_duplicate_reference_ids_are_rejected() {
let mut composition = SceneComposition {
scene_id: "main".to_string(),
subscenes: vec![
shared::SubsceneReference {
id: "same".to_string(),
path: "../outside.scn.ron".to_string(),
..Default::default()
},
shared::SubsceneReference {
id: "same".to_string(),
path: "assets/levels/other.scn.ron".to_string(),
..Default::default()
},
],
};
assert!(validate_scene_composition(&composition).is_err());
composition.subscenes[0].path = "assets/levels/one.scn.ron".to_string();
assert!(validate_scene_composition(&composition)
.unwrap_err()
.contains("duplicate subscene id"));
}
}
+442 -17
View File
@@ -8,6 +8,7 @@ use std::collections::BTreeMap;
use ron::ser::PrettyConfig;
use serde::{Deserialize, Serialize};
use shared::{ActorId, PrefabInstance, PrefabRef, SceneComposition};
use crate::{
migrate_scene_text, read_schema_version, stamp_schema_version, strip_schema_version,
@@ -18,23 +19,37 @@ use crate::{
pub struct SceneDocument {
pub schema_version: u32,
pub entities: Vec<SceneEntity>,
pub composition: Option<SceneComposition>,
pub resource_types: Vec<String>,
pub prefab_instances: Vec<PrefabInstance>,
pub prefab_refs: Vec<PrefabRef>,
normalized_ron: String,
resources: BTreeMap<String, String>,
source_keys: BTreeMap<SceneEntityId, u64>,
}
impl SceneDocument {
pub fn from_ron_text(text: &str) -> Result<Self, String> {
let normalized = migrate_scene_text(text)?;
validate_scene_authoring_only(&normalized)?;
validate_hierarchy_references(&normalized)?;
let body = strip_schema_version(&normalized)?;
let parsed: DynamicSceneBody = ron::from_str(&body)
.map_err(|err| format!("could not parse scene document body: {err}"))?;
let (resources, mut raw_entities) = extract_raw_scene_values(&normalized)?;
let composition = extract_scene_composition(&parsed.resources)?;
let resource_types = parsed.resources.keys().cloned().collect();
let prefab_instances = extract_prefab_instances(&parsed.entities)?;
let prefab_refs = extract_prefab_refs(&parsed.entities)?;
let mut entities = Vec::with_capacity(parsed.entities.len());
for (index, (_source_key, entity)) in parsed.entities.into_iter().enumerate() {
let components = entity
.components
let mut source_keys = BTreeMap::new();
for (index, (source_key, _entity)) in parsed.entities.into_iter().enumerate() {
let components = raw_entities
.remove(&source_key)
.ok_or_else(|| format!("scene entity `{source_key}` has no lossless syntax node"))?
.into_iter()
.map(|(type_name, value)| SceneComponentBlob::from_value(type_name, value))
.map(|(type_name, ron)| SceneComponentBlob::from_ron(type_name, ron))
.collect::<Result<Vec<_>, _>>()?;
let actor_id = extract_actor_id(&components);
@@ -45,23 +60,93 @@ impl SceneDocument {
.unwrap_or_else(|| SceneEntityId::Anonymous(format!("anonymous:{index}")));
entities.push(SceneEntity {
document_id,
document_id: document_id.clone(),
actor_id,
name,
parent_actor_id: None,
components,
});
source_keys.insert(document_id, source_key);
}
let key_to_actor: BTreeMap<u64, String> = entities
.iter()
.filter_map(|entity| {
let source_key = source_keys.get(&entity.document_id).copied()?;
Some((source_key, entity.actor_id.clone()?))
})
.collect();
for entity in &mut entities {
entity.parent_actor_id = entity
.components
.iter()
.find(|component| component.type_name == CHILD_OF_COMPONENT)
.and_then(|component| parse_child_of_source_key(&component.ron))
.and_then(|source_key| key_to_actor.get(&source_key).cloned());
}
Ok(Self {
schema_version: read_schema_version(&normalized),
entities,
composition,
resource_types,
prefab_instances,
prefab_refs,
normalized_ron: normalized,
resources,
source_keys,
})
}
pub fn to_ron_text(&self) -> Result<String, String> {
stamp_schema_version(&self.normalized_ron)
let mut resources = self.resources.clone();
match &self.composition {
Some(composition) => {
let composition_ron = ron::to_string(composition)
.map_err(|error| format!("could not encode scene composition: {error}"))?;
resources.insert(SCENE_COMPOSITION_RESOURCE.to_string(), composition_ron);
}
None => {
resources.remove(SCENE_COMPOSITION_RESOURCE);
}
}
let mut used_keys: std::collections::HashSet<u64> =
self.source_keys.values().copied().collect();
let mut next_key = used_keys
.iter()
.copied()
.max()
.unwrap_or(0)
.saturating_add(1);
let mut entities = BTreeMap::new();
for entity in &self.entities {
let source_key = self
.source_keys
.get(&entity.document_id)
.copied()
.unwrap_or_else(|| {
while used_keys.contains(&next_key) {
next_key = next_key.saturating_add(1);
}
let assigned = next_key;
used_keys.insert(assigned);
next_key = next_key.saturating_add(1);
assigned
});
let components = entity
.components
.iter()
.map(|component| {
ron::from_str::<ron::Value>(&component.ron).map_err(|error| {
format!("invalid component RON `{}`: {error}", component.type_name)
})?;
Ok((component.type_name.clone(), component.ron.clone()))
})
.collect::<Result<BTreeMap<_, _>, String>>()?;
entities.insert(source_key, components);
}
encode_lossless_scene_body(&resources, &entities)
}
pub fn normalized_ron(&self) -> &str {
@@ -108,28 +193,109 @@ impl SceneDocument {
entity.document_id
));
}
let next_key = self
.source_keys
.values()
.copied()
.max()
.unwrap_or(0)
.saturating_add(1);
self.source_keys
.insert(entity.document_id.clone(), next_key);
self.entities.push(entity);
}
ScenePatch::DeleteEntity { target } => {
let before = self.entities.len();
self.entities.retain(|entity| entity.document_id != target);
if self.entities.len() == before {
let Some(target_actor_id) = self
.find_entity(&target)
.and_then(|entity| entity.actor_id.clone())
else {
return Err(format!("scene entity `{target}` not found"));
};
let mut removed_actor_ids = std::collections::HashSet::from([target_actor_id]);
let mut changed = true;
while changed {
changed = false;
for entity in &self.entities {
if entity
.parent_actor_id
.as_ref()
.is_some_and(|parent| removed_actor_ids.contains(parent))
{
if let Some(actor_id) = entity.actor_id.clone() {
changed |= removed_actor_ids.insert(actor_id);
}
}
}
}
let removed_ids: Vec<_> = self
.entities
.iter()
.filter(|entity| {
entity
.actor_id
.as_ref()
.is_some_and(|actor_id| removed_actor_ids.contains(actor_id))
})
.map(|entity| entity.document_id.clone())
.collect();
self.entities
.retain(|entity| !removed_ids.contains(&entity.document_id));
for removed in removed_ids {
self.source_keys.remove(&removed);
}
}
ScenePatch::Reparent {
target,
parent_actor_id,
} => {
let parent_source_key = parent_actor_id
.as_ref()
.map(|parent| {
self.source_keys
.get(&SceneEntityId::ActorId(parent.clone()))
.copied()
.ok_or_else(|| format!("parent actor `{parent}` not found"))
})
.transpose()?;
let entity = self
.find_entity_mut(&target)
.ok_or_else(|| format!("scene entity `{target}` not found"))?;
match parent_source_key {
Some(parent_source_key) => {
let component = SceneComponentBlob::from_ron(
CHILD_OF_COMPONENT,
format!("({parent_source_key})"),
)?;
if let Some(existing) = entity
.components
.iter_mut()
.find(|component| component.type_name == CHILD_OF_COMPONENT)
{
*existing = component;
} else {
entity.components.push(component);
}
}
None => entity
.components
.retain(|component| component.type_name != CHILD_OF_COMPONENT),
}
entity.parent_actor_id = parent_actor_id;
}
ScenePatch::Rename { target, name } => {
let entity = self
.find_entity_mut(&target)
.ok_or_else(|| format!("scene entity `{target}` not found"))?;
let component = SceneComponentBlob::from_serializable(NAME_COMPONENT, &name)?;
if let Some(existing) = entity
.components
.iter_mut()
.find(|existing| existing.type_name == NAME_COMPONENT)
{
*existing = component;
} else {
entity.components.push(component);
}
entity.name = Some(name);
}
ScenePatch::SetTransform { target, transform } => {
@@ -203,12 +369,18 @@ impl SceneComponentBlob {
})
}
fn from_value(type_name: String, value: ron::Value) -> Result<Self, String> {
let pretty = PrettyConfig::new();
let ron = ron::ser::to_string_pretty(&value, pretty)
.map_err(|err| format!("could not serialize component value `{type_name}`: {err}"))?;
pub fn from_ron(type_name: impl Into<String>, ron: impl Into<String>) -> Result<Self, String> {
let type_name = type_name.into();
let ron = ron.into();
ron::from_str::<ron::Value>(&ron)
.map_err(|error| format!("invalid component RON `{type_name}`: {error}"))?;
Ok(Self { type_name, ron })
}
pub fn to_value(&self) -> Result<ron::Value, String> {
ron::from_str(&self.ron)
.map_err(|error| format!("invalid component RON `{}`: {error}", self.type_name))
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
@@ -258,22 +430,254 @@ impl Default for SceneTransform {
}
}
#[derive(Debug, Deserialize)]
#[derive(Debug, Clone, Serialize, Deserialize)]
struct DynamicSceneBody {
#[serde(default)]
resources: BTreeMap<String, ron::Value>,
#[serde(default)]
entities: BTreeMap<u64, DynamicSceneEntity>,
}
#[derive(Debug, Deserialize)]
#[derive(Debug, Clone, Serialize, Deserialize)]
struct DynamicSceneEntity {
#[serde(default)]
components: BTreeMap<String, ron::Value>,
}
const ACTOR_ID_COMPONENT: &str = "shared::components::ActorId";
const CHILD_OF_COMPONENT: &str = "bevy_ecs::hierarchy::ChildOf";
const NAME_COMPONENT: &str = "bevy_ecs::name::Name";
const SCENE_COMPOSITION_RESOURCE: &str = "shared::components::SceneComposition";
const PREFAB_INSTANCE_COMPONENT: &str = "shared::components::PrefabInstance";
const PREFAB_REF_COMPONENT: &str = "shared::components::PrefabRef";
pub const TRANSFORM_COMPONENT: &str = "bevy_transform::components::transform::Transform";
type RawSceneEntities = BTreeMap<u64, BTreeMap<String, String>>;
fn extract_raw_scene_values(
text: &str,
) -> Result<(BTreeMap<String, String>, RawSceneEntities), String> {
let file = ron_edit::File::try_from(text)
.map_err(|error| format!("could not parse lossless scene syntax: {error}"))?;
let root = as_struct(&file.value.content, "scene root")?;
let resources = as_map(struct_field(root, "resources")?, "scene resources")?;
let entities = as_map(struct_field(root, "entities")?, "scene entities")?;
let resources = resources
.0
.values
.iter()
.map(|entry| {
Ok((
parse_string_key(&entry.content.key)?,
entry.content.value.content.to_string(),
))
})
.collect::<Result<BTreeMap<_, _>, String>>()?;
let entities = entities
.0
.values
.iter()
.map(|entry| {
let source_key = entry
.content
.key
.to_string()
.parse::<u64>()
.map_err(|error| format!("invalid scene entity key: {error}"))?;
let entity = as_struct(&entry.content.value.content, "scene entity")?;
let components = as_map(struct_field(entity, "components")?, "entity components")?;
let components = components
.0
.values
.iter()
.map(|component| {
Ok((
parse_string_key(&component.content.key)?,
component.content.value.content.to_string(),
))
})
.collect::<Result<BTreeMap<_, _>, String>>()?;
Ok((source_key, components))
})
.collect::<Result<BTreeMap<_, _>, String>>()?;
Ok((resources, entities))
}
fn as_struct<'a, 's>(
value: &'a ron_edit::Value<'s>,
label: &str,
) -> Result<&'a ron_edit::Struct<'s>, String> {
match value {
ron_edit::Value::Struct(value) => Ok(value),
_ => Err(format!("{label} must be a RON struct")),
}
}
fn as_map<'a, 's>(
value: &'a ron_edit::Value<'s>,
label: &str,
) -> Result<&'a ron_edit::Map<'s>, String> {
match value {
ron_edit::Value::Map(value) => Ok(value),
_ => Err(format!("{label} must be a RON map")),
}
}
fn struct_field<'a, 's>(
value: &'a ron_edit::Struct<'s>,
name: &str,
) -> Result<&'a ron_edit::Value<'s>, String> {
value
.fields
.values
.iter()
.find(|field| field.content.key == name)
.map(|field| &field.content.value.content)
.ok_or_else(|| format!("RON struct is missing `{name}`"))
}
fn parse_string_key(value: &ron_edit::Value<'_>) -> Result<String, String> {
ron::from_str(&value.to_string()).map_err(|error| format!("invalid string map key: {error}"))
}
fn parse_child_of_source_key(text: &str) -> Option<u64> {
let value = ron::from_str::<ron::Value>(text).ok()?;
parse_child_of_source_key_value(&value)
}
fn parse_child_of_source_key_value(value: &ron::Value) -> Option<u64> {
let ron::Value::Seq(values) = value else {
return None;
};
let ron::Value::Number(ron::value::Number::Integer(value)) = values.first()? else {
return None;
};
u64::try_from(*value).ok()
}
pub(crate) fn validate_hierarchy_references(text: &str) -> Result<(), String> {
let body = strip_schema_version(text)?;
let parsed: DynamicSceneBody = ron::from_str(&body)
.map_err(|error| format!("could not parse scene hierarchy: {error}"))?;
let mut parents = BTreeMap::new();
for (entity_key, entity) in &parsed.entities {
let Some(value) = entity.components.get(CHILD_OF_COMPONENT) else {
continue;
};
let parent_key = parse_child_of_source_key_value(value).ok_or_else(|| {
format!("scene entity `{entity_key}` has a malformed `{CHILD_OF_COMPONENT}` value")
})?;
if !parsed.entities.contains_key(&parent_key) {
return Err(format!(
"scene entity `{entity_key}` references missing hierarchy parent `{parent_key}`"
));
}
parents.insert(*entity_key, parent_key);
}
for start in parents.keys().copied() {
let mut visited = std::collections::BTreeSet::new();
let mut current = start;
while let Some(parent) = parents.get(&current).copied() {
if !visited.insert(current) {
return Err(format!(
"scene hierarchy contains a cycle involving entity `{current}`"
));
}
current = parent;
}
}
Ok(())
}
fn encode_lossless_scene_body(
resources: &BTreeMap<String, String>,
entities: &BTreeMap<u64, BTreeMap<String, String>>,
) -> Result<String, String> {
let mut body = String::from("(resources: {\n");
for (type_name, value) in resources {
ron::from_str::<ron::Value>(value)
.map_err(|error| format!("invalid resource RON `{type_name}`: {error}"))?;
body.push_str(" ");
body.push_str(
&ron::to_string(type_name)
.map_err(|error| format!("could not encode resource type: {error}"))?,
);
body.push_str(": ");
body.push_str(value);
body.push_str(",\n");
}
body.push_str(" },\n entities: {\n");
for (source_key, components) in entities {
body.push_str(&format!(" {source_key}: (components: {{\n"));
for (type_name, value) in components {
body.push_str(" ");
body.push_str(
&ron::to_string(type_name)
.map_err(|error| format!("could not encode component type: {error}"))?,
);
body.push_str(": ");
body.push_str(value);
body.push_str(",\n");
}
body.push_str(" }),\n");
}
body.push_str(" },\n)");
stamp_schema_version(&body)
}
fn extract_scene_composition(
resources: &BTreeMap<String, ron::Value>,
) -> Result<Option<SceneComposition>, String> {
let mut matches = resources
.iter()
.filter(|(type_name, _)| type_name.as_str() == SCENE_COMPOSITION_RESOURCE);
let Some((_type_name, value)) = matches.next() else {
return Ok(None);
};
if matches.next().is_some() {
return Err("scene contains multiple composition resources".to_string());
}
value
.clone()
.into_rust::<SceneComposition>()
.map(Some)
.map_err(|error| format!("could not parse scene composition: {error}"))
}
fn extract_prefab_instances(
entities: &BTreeMap<u64, DynamicSceneEntity>,
) -> Result<Vec<PrefabInstance>, String> {
entities
.values()
.filter_map(|entity| entity.components.get(PREFAB_INSTANCE_COMPONENT))
.map(|value| {
value
.clone()
.into_rust::<PrefabInstance>()
.map_err(|error| format!("could not parse prefab instance: {error}"))
})
.collect()
}
fn extract_prefab_refs(
entities: &BTreeMap<u64, DynamicSceneEntity>,
) -> Result<Vec<PrefabRef>, String> {
entities
.values()
.filter_map(|entity| entity.components.get(PREFAB_REF_COMPONENT))
.map(|value| {
value
.clone()
.into_rust::<PrefabRef>()
.map_err(|error| format!("could not parse prefab reference: {error}"))
})
.collect()
}
fn extract_name(components: &[SceneComponentBlob]) -> Option<String> {
components
.iter()
@@ -286,8 +690,10 @@ fn extract_actor_id(components: &[SceneComponentBlob]) -> Option<String> {
let component = components
.iter()
.find(|component| component.type_name == ACTOR_ID_COMPONENT)?;
ron::from_str::<String>(&component.ron)
ron::from_str::<ActorId>(&component.ron)
.ok()
.map(|id| id.0)
.or_else(|| ron::from_str::<String>(&component.ron).ok())
.or_else(|| {
ron::from_str::<Vec<String>>(&component.ron)
.ok()
@@ -300,6 +706,12 @@ fn extract_actor_id(components: &[SceneComponentBlob]) -> Option<String> {
mod tests {
use super::*;
#[test]
fn lossless_parser_accepts_anonymous_structs_and_tuples() {
let value = "(translation: (1.0, 2.0, 3.0), scale: (1.0, 1.0, 1.0))";
assert!(ron_edit::File::try_from(value).is_ok());
}
#[test]
fn parses_scene_document_without_exposing_runtime_entity_ids() {
let text = r#"(schema_version: 2,
@@ -332,7 +744,10 @@ mod tests {
let document = SceneDocument::from_ron_text(body).unwrap();
let text = document.to_ron_text().unwrap();
assert!(text.starts_with("(schema_version: 2,"));
assert!(text.contains("entities: {}"));
assert!(SceneDocument::from_ron_text(&text)
.unwrap()
.entities
.is_empty());
}
#[test]
@@ -372,5 +787,15 @@ mod tests {
.components
.iter()
.any(|component| component.type_name == TRANSFORM_COMPONENT));
let reparsed = SceneDocument::from_ron_text(&document.to_ron_text().unwrap()).unwrap();
let entity = reparsed.find_entity(&target).unwrap();
assert_eq!(entity.name.as_deref(), Some("Renamed"));
let transform = entity
.components
.iter()
.find(|component| component.type_name == TRANSFORM_COMPONENT)
.unwrap();
assert!(transform.ron.contains("1.0"));
}
}
+138 -2
View File
@@ -3,17 +3,74 @@
//! Bevy dynamic scenes are stored as RON tuples. On save the editor stamps
//! `schema_version` as the first root field; loaders strip it before deserializing.
mod composition;
pub mod document;
mod migrate;
mod prefab;
mod project_validation;
use std::path::Path;
use serde::{Deserialize, Serialize};
pub use composition::{validate_composition_graph, validate_scene_composition};
pub use migrate::{migrate_v1_to_v2, DEFAULT_SUN_ILLUMINANCE_LUX};
pub use prefab::{
prefab_graph_revision, validate_prefab_graph, validate_prefab_graph_text,
validate_prefab_references, validate_prefab_references_text,
};
pub use project_validation::{
validate_project, ProjectDependency, ProjectValidationFinding, ProjectValidationReport,
ValidationSeverity,
};
pub const CURRENT_SCENE_SCHEMA_VERSION: u32 = 2;
/// Whether an asset-relative path names a tree excluded from runtime packages.
pub fn is_runtime_package_excluded_tree(relative: &Path) -> bool {
relative
.components()
.filter_map(|component| match component {
std::path::Component::Normal(component) => component.to_str(),
_ => None,
})
.any(|component| {
component.starts_with('.')
|| matches!(
component,
"thumbnails" | "build_profiles" | "recovery" | "autosave"
)
})
}
/// Shared validator/packager policy for files that may ship under `assets/`.
pub fn is_runtime_package_asset(relative: &Path) -> bool {
if is_runtime_package_excluded_tree(relative) {
return false;
}
let filename = relative
.file_name()
.and_then(|name| name.to_str())
.unwrap_or_default()
.to_ascii_lowercase();
if filename.starts_with('.')
|| filename.ends_with(".bak")
|| filename.ends_with(".tmp")
|| filename.ends_with(".autosave")
|| filename.ends_with(".recovery")
{
return false;
}
!matches!(
relative
.extension()
.and_then(|extension| extension.to_str())
.map(str::to_ascii_lowercase)
.as_deref(),
Some("blend" | "blend1" | "psd" | "kra" | "xcf" | "fbm")
)
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SceneSchemaHeader {
pub schema_version: u32,
@@ -74,7 +131,11 @@ pub fn migrate_scene_text(text: &str) -> Result<String, String> {
let migrated_body = match version {
0 | 1 => migrate_v1_to_v2(&body),
2 => body,
_ => body,
_ => {
return Err(format!(
"scene schema version {version} is newer than supported version {CURRENT_SCENE_SCHEMA_VERSION}"
));
}
};
stamp_schema_version(&migrated_body)
@@ -110,6 +171,12 @@ pub const FORBIDDEN_SAVED_COMPONENT_MARKERS: &[&str] = &[
"bevy_world_serialization::components::WorldAssetRoot",
"bevy_world_serialization::components::DynamicWorldRoot",
"bevy_render::visibility::ComputedVisibility",
"bevy_audio::",
"game::audio::AuthoredAudioVoice",
"bevy_animation::AnimationGraphHandle",
"bevy_animation::AnimationPlayer",
"bevy_animation::AnimationTransitions",
"game::animation::AuthoredAnimationRuntime",
];
/// Ensures serialized scene text does not contain hydrated ECS component entries.
@@ -131,12 +198,18 @@ pub fn validate_level_text(text: &str) -> Result<(), String> {
let migrated = migrate_scene_text(text)?;
strip_schema_version(&migrated)?;
validate_scene_authoring_only(&migrated)?;
document::validate_hierarchy_references(&migrated)?;
Ok(())
}
pub fn validate_level_file(path: &Path) -> Result<(), String> {
let text = std::fs::read_to_string(path).map_err(|e| e.to_string())?;
validate_level_text(&text)
validate_level_text(&text)?;
if let Some(project_root) = composition::find_project_root(path) {
validate_composition_graph(path, &project_root)?;
validate_prefab_references(path, &project_root)?;
}
Ok(())
}
#[cfg(test)]
@@ -159,6 +232,37 @@ mod tests {
assert!(migrated.contains("schema_version: 2"));
}
#[test]
fn newer_scene_schema_is_rejected_instead_of_downstamped() {
let future = "(schema_version: 999, resources: {}, entities: {})";
let error = migrate_scene_text(future).unwrap_err();
assert!(error.contains("newer than supported"), "{error}");
assert!(validate_level_text(future).is_err());
}
#[test]
fn runtime_package_policy_excludes_editor_trees_and_source_formats() {
for excluded in [
".index/registry.ron",
".env/secret",
"build_profiles/release.ron",
"levels/recovery/main.scn.ron",
"textures/source.psd",
"models/source.blend",
"levels/main.scn.ron.bak",
] {
assert!(!is_runtime_package_asset(Path::new(excluded)), "{excluded}");
}
for included in [
"project.ron",
"levels/main.scn.ron",
"textures/albedo.png",
"models/mesh.glb",
] {
assert!(is_runtime_package_asset(Path::new(included)), "{included}");
}
}
#[test]
#[ignore = "run manually to rewrite assets/levels/editor_scene.scn.ron"]
fn migrate_editor_scene_on_disk() {
@@ -177,6 +281,22 @@ mod tests {
validate_scene_authoring_only(&text).expect("editor scene must be authoring-only");
}
#[test]
fn runtime_audio_components_are_rejected_from_authored_scenes() {
for marker in [
"bevy_audio::audio::AudioPlayer",
"bevy_audio::sinks::SpatialAudioSink",
"game::audio::AuthoredAudioVoice",
] {
let text =
format!("(resources: {{}}, entities: {{1:(components:{{\"{marker}\":()}})}})");
assert!(
validate_scene_authoring_only(&text).is_err(),
"{marker} must be runtime-only"
);
}
}
#[test]
fn v1_scene_gains_actor_kind_on_migrate() {
let v1 = "(schema_version: 1,(resources: {}, entities: {
@@ -194,4 +314,20 @@ mod tests {
assert!(migrated.contains("ActorKind"));
assert!(migrated.contains("StaticMesh"));
}
#[test]
fn hierarchy_validation_rejects_missing_parent_and_cycles() {
let missing_parent = r#"(schema_version: 2, resources: {}, entities: {
1: (components: { "bevy_ecs::hierarchy::ChildOf": (99) }),
})"#;
let error = validate_level_text(missing_parent).unwrap_err();
assert!(error.contains("missing hierarchy parent `99`"));
let cycle = r#"(schema_version: 2, resources: {}, entities: {
1: (components: { "bevy_ecs::hierarchy::ChildOf": (2) }),
2: (components: { "bevy_ecs::hierarchy::ChildOf": (1) }),
})"#;
let error = validate_level_text(cycle).unwrap_err();
assert!(error.contains("scene hierarchy contains a cycle"));
}
}
+35
View File
@@ -105,6 +105,12 @@ fn infer_kind_from_block(block: &str) -> &'static str {
{
return actor_kind_ron(ActorKind::PrefabAnchor);
}
if block.contains("\"shared::components::AudioSourceDesc\"") {
return actor_kind_ron(ActorKind::AudioSource);
}
if block.contains("\"shared::components::AudioListenerDesc\"") {
return actor_kind_ron(ActorKind::AudioListener);
}
actor_kind_ron(ActorKind::Empty)
}
@@ -122,6 +128,8 @@ fn actor_kind_ron(kind: ActorKind) -> &'static str {
ActorKind::PostProcessVolume => "PostProcessVolume",
ActorKind::TeamSpawn => "TeamSpawn",
ActorKind::Objective => "Objective",
ActorKind::AudioSource => "AudioSource",
ActorKind::AudioListener => "AudioListener",
}
}
@@ -233,6 +241,33 @@ mod tests {
assert!(migrated.contains("Brush"));
}
#[test]
fn backfills_actor_kind_for_audio_source_entity() {
let body = r#"(
resources: {},
entities: {
1: (
components: {
"shared::components::LevelObject": (),
"shared::components::AudioSourceDesc": (
clip: None,
gain_db: 0.0,
pitch: 1.0,
looping: false,
autoplay: true,
spatial_blend: 1.0,
attenuation: (min_distance: 1.0, max_distance: 25.0, rolloff: Inverse, rolloff_factor: 1.0),
bus: "sfx",
),
},
),
},
)"#;
let migrated = migrate_v1_to_v2(body);
assert!(migrated.contains("ActorKind"));
assert!(migrated.contains("AudioSource"));
}
#[test]
fn fixes_low_directional_lux() {
let body = r#"(
+628
View File
@@ -0,0 +1,628 @@
//! Stable prefab dependency validation for nested instances and variants.
use std::collections::{BTreeMap, HashSet};
use std::path::{Component, Path, PathBuf};
use crate::document::SceneDocument;
pub fn validate_prefab_graph(entry: &Path, project_root: &Path) -> Result<(), String> {
let requested = entry.to_path_buf();
let entry = canonical_existing(entry)
.map_err(|error| format!("missing prefab source `{}`: {error}", requested.display()))?;
let project_root = canonical_existing(project_root)?;
let text = std::fs::read_to_string(&entry)
.map_err(|error| format!("could not read {}: {error}", entry.display()))?;
validate_prefab_graph_text(&text, &entry, &project_root)
}
pub fn validate_prefab_references(entry: &Path, project_root: &Path) -> Result<(), String> {
let entry = canonical_existing(entry)?;
let project_root = canonical_existing(project_root)?;
let text = std::fs::read_to_string(&entry)
.map_err(|error| format!("could not read {}: {error}", entry.display()))?;
validate_prefab_references_text(&text, &entry, &project_root)
}
pub fn prefab_graph_revision(entry: &Path, project_root: &Path) -> Result<String, String> {
validate_prefab_graph(entry, project_root)?;
let entry = canonical_existing(entry)?;
let project_root = canonical_existing(project_root)?;
let mut files = BTreeMap::new();
collect_prefab_graph_files(&entry, &project_root, &mut files)?;
let mut hash = 0xcbf2_9ce4_8422_2325_u64;
for (path, bytes) in files {
for byte in path.as_bytes().iter().chain([0xff].iter()).chain(&bytes) {
hash ^= u64::from(*byte);
hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
}
}
Ok(format!("fnv1a64:{hash:016x}"))
}
fn collect_prefab_graph_files(
path: &Path,
project_root: &Path,
files: &mut BTreeMap<String, Vec<u8>>,
) -> Result<(), String> {
let label = project_label(path, project_root);
if files.contains_key(&label) {
return Ok(());
}
let bytes = std::fs::read(path)
.map_err(|error| format!("could not read {}: {error}", path.display()))?;
let text = std::str::from_utf8(&bytes)
.map_err(|error| format!("{} is not UTF-8: {error}", path.display()))?;
let document = SceneDocument::from_ron_text(text)
.map_err(|error| format!("{}: {error}", path.display()))?;
let mut dependencies: Vec<String> = document
.prefab_instances
.into_iter()
.map(|instance| instance.source_path)
.collect();
dependencies.sort();
dependencies.dedup();
files.insert(label, bytes);
for source_path in dependencies {
let target = resolve_source_path(project_root, &source_path)?;
collect_prefab_graph_files(&target, project_root, files)?;
}
Ok(())
}
pub fn validate_prefab_graph_text(
entry_text: &str,
entry: &Path,
project_root: &Path,
) -> Result<(), String> {
validate_prefab_graph_text_inner(entry_text, entry, project_root, true)
}
pub fn validate_prefab_references_text(
entry_text: &str,
entry: &Path,
project_root: &Path,
) -> Result<(), String> {
validate_prefab_graph_text_inner(entry_text, entry, project_root, false)
}
fn validate_prefab_graph_text_inner(
entry_text: &str,
entry: &Path,
project_root: &Path,
require_stable_ids: bool,
) -> Result<(), String> {
let project_root = canonical_existing(project_root)?;
let entry = canonical_or_nearest_existing(entry)?;
if !entry.starts_with(&project_root) {
return Err(format!(
"prefab document {} is outside project root {}",
entry.display(),
project_root.display()
));
}
let relative_entry = entry
.strip_prefix(&project_root)
.map_err(|_| "prefab document is outside the project root".to_string())?;
validate_entry_path(relative_entry, require_stable_ids)?;
let mut visiting = Vec::new();
let mut visited = HashSet::new();
visit_prefab_text(
&entry,
entry_text,
&project_root,
&mut visiting,
&mut visited,
require_stable_ids,
)
}
fn visit_prefab_text(
path: &Path,
text: &str,
project_root: &Path,
visiting: &mut Vec<PathBuf>,
visited: &mut HashSet<PathBuf>,
require_stable_ids: bool,
) -> Result<(), String> {
if let Some(cycle_start) = visiting.iter().position(|candidate| candidate == path) {
let mut cycle: Vec<String> = visiting[cycle_start..]
.iter()
.map(|candidate| project_label(candidate, project_root))
.collect();
cycle.push(project_label(path, project_root));
return Err(format!("cyclic prefab reference: {}", cycle.join(" -> ")));
}
if !visited.insert(path.to_path_buf()) {
return Ok(());
}
let document = SceneDocument::from_ron_text(text)
.map_err(|error| format!("{}: {error}", path.display()))?;
if require_stable_ids {
if !document.resource_types.is_empty() {
return Err(format!(
"{}: prefab documents may not contain resources ({})",
path.display(),
document.resource_types.join(", ")
));
}
validate_actor_ids(&document, path)?;
validate_prefab_link_anchors(&document, path)?;
}
for instance in &document.prefab_instances {
shared::decode_prefab_overrides(instance).map_err(|error| {
format!(
"{}: prefab instance `{}` has invalid overrides: {error}",
path.display(),
instance.asset_id
)
})?;
}
let instance_paths: HashSet<String> = document
.prefab_instances
.iter()
.map(|instance| instance.source_path.clone())
.collect();
let legacy_refs: Vec<_> = document
.prefab_refs
.into_iter()
.filter(|prefab_ref| !instance_paths.contains(&prefab_ref.path))
.collect();
if require_stable_ids && !legacy_refs.is_empty() {
return Err(format!(
"{} contains legacy PrefabRef links without PrefabInstance identity",
path.display()
));
}
let mut dependencies: Vec<(String, String)> = document
.prefab_instances
.into_iter()
.map(|instance| (instance.asset_id, instance.source_path))
.collect();
dependencies.extend(
legacy_refs
.into_iter()
.map(|prefab_ref| (format!("legacy:{}", prefab_ref.path), prefab_ref.path)),
);
visiting.push(path.to_path_buf());
for (asset_id, source_path) in dependencies {
if asset_id.trim().is_empty() {
return Err(format!(
"{}: prefab instance has an empty asset_id",
path.display()
));
}
validate_source_path(&source_path)?;
let lexical_target = project_root.join(&source_path);
if let Some(cycle_start) = visiting
.iter()
.position(|candidate| candidate == &lexical_target)
{
let mut cycle: Vec<String> = visiting[cycle_start..]
.iter()
.map(|candidate| project_label(candidate, project_root))
.collect();
cycle.push(project_label(&lexical_target, project_root));
return Err(format!("cyclic prefab reference: {}", cycle.join(" -> ")));
}
let target = resolve_source_path(project_root, &source_path)?;
if let Some(cycle_start) = visiting.iter().position(|candidate| candidate == &target) {
let mut cycle: Vec<String> = visiting[cycle_start..]
.iter()
.map(|candidate| project_label(candidate, project_root))
.collect();
cycle.push(project_label(&target, project_root));
return Err(format!("cyclic prefab reference: {}", cycle.join(" -> ")));
}
if visited.contains(&target) {
continue;
}
let target_text = std::fs::read_to_string(&target).map_err(|error| {
format!(
"missing prefab source `{}` referenced by {}: {error}",
source_path,
project_label(path, project_root)
)
})?;
visit_prefab_text(&target, &target_text, project_root, visiting, visited, true)?;
}
visiting.pop();
Ok(())
}
fn validate_prefab_link_anchors(document: &SceneDocument, path: &Path) -> Result<(), String> {
const LEVEL_OBJECT: &str = "shared::components::LevelObject";
const PREFAB_INSTANCE: &str = "shared::components::PrefabInstance";
const PREFAB_REF: &str = "shared::components::PrefabRef";
const ACTOR_KIND: &str = "shared::components::ActorKind";
const TRANSFORM: &str = "bevy_transform::components::transform::Transform";
for entity in &document.entities {
let has = |type_name: &str| {
entity
.components
.iter()
.any(|component| component.type_name == type_name)
};
if !has(PREFAB_INSTANCE) && !has(PREFAB_REF) {
continue;
}
let label = entity
.actor_id
.as_deref()
.unwrap_or("anonymous prefab link");
for (component, description) in [
(LEVEL_OBJECT, "LevelObject"),
(TRANSFORM, "Transform"),
(ACTOR_KIND, "ActorKind"),
] {
if !has(component) {
return Err(format!(
"{}: prefab link `{label}` is missing required {description}",
path.display()
));
}
}
}
Ok(())
}
fn validate_actor_ids(document: &SceneDocument, path: &Path) -> Result<(), String> {
let mut ids = HashSet::new();
for entity in &document.entities {
let authored_actor = entity
.components
.iter()
.any(|component| component.type_name == "shared::components::LevelObject");
if authored_actor && entity.actor_id.is_none() {
return Err(format!(
"{} contains an authored prefab actor without ActorId",
path.display()
));
}
let Some(actor_id) = entity.actor_id.as_deref() else {
continue;
};
if !ids.insert(actor_id) {
return Err(format!(
"{} contains duplicate ActorId `{actor_id}`",
path.display()
));
}
}
Ok(())
}
fn resolve_source_path(project_root: &Path, source_path: &str) -> Result<PathBuf, String> {
validate_source_path(source_path)?;
let target = project_root.join(source_path);
let target = canonical_existing(&target).map_err(|error| {
format!(
"missing prefab source `{source_path}` under {}: {error}",
project_root.display()
)
})?;
if !target.starts_with(project_root) {
return Err(format!(
"prefab source `{source_path}` escapes the project root"
));
}
Ok(target)
}
fn validate_source_path(source_path: &str) -> Result<(), String> {
let path = Path::new(source_path);
if path.as_os_str().is_empty() || path.is_absolute() {
return Err(format!(
"prefab source `{}` must be project-relative",
path.display()
));
}
if path.components().any(|component| {
matches!(
component,
Component::ParentDir | Component::RootDir | Component::Prefix(_)
)
}) {
return Err(format!(
"prefab source `{}` may not escape the project root",
path.display()
));
}
let components: Vec<_> = path.components().collect();
if components.first() != Some(&Component::Normal("assets".as_ref()))
|| components.get(1) != Some(&Component::Normal("prefabs".as_ref()))
{
return Err(format!(
"prefab source `{}` must be under assets/prefabs/",
path.display()
));
}
if !path
.file_name()
.and_then(|name| name.to_str())
.is_some_and(|name| name.ends_with(".scn.ron"))
{
return Err(format!(
"prefab source `{}` must name a .scn.ron file",
path.display()
));
}
Ok(())
}
fn validate_entry_path(path: &Path, strict_prefab: bool) -> Result<(), String> {
let text = path.to_string_lossy();
if strict_prefab {
validate_source_path(&text)
} else {
if path.components().any(|component| {
matches!(
component,
Component::ParentDir | Component::RootDir | Component::Prefix(_)
)
}) || path.components().next() != Some(Component::Normal("assets".as_ref()))
{
return Err(format!(
"scene document `{}` must remain under assets/",
path.display()
));
}
if !path
.file_name()
.and_then(|name| name.to_str())
.is_some_and(|name| name.ends_with(".scn.ron"))
{
return Err(format!(
"scene document `{}` must name a .scn.ron file",
path.display()
));
}
Ok(())
}
}
fn absolute_lexical(path: &Path) -> Result<PathBuf, String> {
if path.is_absolute() {
Ok(path.to_path_buf())
} else {
std::env::current_dir()
.map(|cwd| cwd.join(path))
.map_err(|error| format!("could not resolve {}: {error}", path.display()))
}
}
fn canonical_or_nearest_existing(path: &Path) -> Result<PathBuf, String> {
let absolute = absolute_lexical(path)?;
let mut ancestor = absolute.as_path();
let mut suffix = Vec::new();
loop {
match ancestor.canonicalize() {
Ok(mut canonical) => {
for component in suffix.iter().rev() {
canonical.push(component);
}
return Ok(canonical);
}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
let Some(name) = ancestor.file_name() else {
return Err(format!("{}: {error}", path.display()));
};
suffix.push(name.to_os_string());
let Some(parent) = ancestor.parent() else {
return Err(format!("{}: {error}", path.display()));
};
ancestor = parent;
}
Err(error) => return Err(format!("{}: {error}", path.display())),
}
}
}
fn canonical_existing(path: &Path) -> Result<PathBuf, String> {
path.canonicalize()
.map_err(|error| format!("{}: {error}", path.display()))
}
fn project_label(path: &Path, project_root: &Path) -> String {
path.strip_prefix(project_root)
.unwrap_or(path)
.display()
.to_string()
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
use std::sync::atomic::{AtomicU64, Ordering};
static NEXT_FIXTURE: AtomicU64 = AtomicU64::new(1);
fn fixture_root() -> PathBuf {
let root = std::env::temp_dir().join(format!(
"blacksite-prefab-{}-{}",
std::process::id(),
NEXT_FIXTURE.fetch_add(1, Ordering::Relaxed)
));
fs::create_dir_all(root.join("assets/prefabs")).unwrap();
fs::write(root.join("assets/project.ron"), "()").unwrap();
root
}
fn prefab(actor_id: &str, references: &[(&str, &str)]) -> String {
let actor_components = |id: &str| {
format!(
"\"shared::components::LevelObject\":(),\"shared::components::ActorId\":(\"{id}\"),\"shared::components::ActorKind\":PrefabAnchor,\"bevy_transform::components::transform::Transform\":(translation:(0.0,0.0,0.0),rotation:(0.0,0.0,0.0,1.0),scale:(1.0,1.0,1.0))"
)
};
let components = references
.iter()
.enumerate()
.map(|(index, (asset_id, path))| {
let actor_id = format!("{actor_id}-{index}");
format!(
"{}:(components:{{{},\"shared::components::PrefabInstance\":(asset_id:\"{asset_id}\",source_path:\"{path}\",overrides_ron:None)}})",
index + 1,
actor_components(&actor_id)
)
})
.collect::<Vec<_>>()
.join(",");
let root = if references.is_empty() {
format!("1:(components:{{{}}})", actor_components(actor_id))
} else {
components
};
format!("(schema_version:2,resources:{{}},entities:{{{root}}})")
}
#[test]
fn nested_prefab_graph_passes() {
let root = fixture_root();
let chair = root.join("assets/prefabs/chair.scn.ron");
let room = root.join("assets/prefabs/room.scn.ron");
fs::write(&chair, prefab("chair", &[])).unwrap();
fs::write(
&room,
prefab("room", &[("chair-asset", "assets/prefabs/chair.scn.ron")]),
)
.unwrap();
validate_prefab_graph(&room, &root).unwrap();
fs::remove_dir_all(root).unwrap();
}
#[test]
fn nested_instance_with_invalid_override_payload_is_rejected() {
let root = fixture_root();
let base = root.join("assets/prefabs/base.scn.ron");
let outer = root.join("assets/prefabs/outer.scn.ron");
fs::write(&base, prefab("base", &[])).unwrap();
let mut instance = shared::PrefabInstance::new("base", "assets/prefabs/base.scn.ron");
instance.overrides_ron = Some("not valid override ron".to_string());
let text = format!(
"(schema_version:2,resources:{{}},entities:{{1:(components:{{\"shared::components::LevelObject\":(),\"shared::components::ActorId\":(\"nested\"),\"shared::components::ActorKind\":PrefabAnchor,\"bevy_transform::components::transform::Transform\":(translation:(0.0,0.0,0.0),rotation:(0.0,0.0,0.0,1.0),scale:(1.0,1.0,1.0)),\"shared::components::PrefabInstance\":{}}})}})",
ron::to_string(&instance).unwrap()
);
fs::write(&outer, text).unwrap();
let error = validate_prefab_graph(&outer, &root).unwrap_err();
assert!(error.contains("invalid overrides"), "{error}");
fs::remove_dir_all(root).unwrap();
}
#[test]
fn graph_revision_changes_when_nested_base_changes() {
let root = fixture_root();
let base = root.join("assets/prefabs/base.scn.ron");
let variant = root.join("assets/prefabs/variant.scn.ron");
fs::write(&base, prefab("base-a", &[])).unwrap();
fs::write(
&variant,
prefab("variant", &[("base", "assets/prefabs/base.scn.ron")]),
)
.unwrap();
let before = prefab_graph_revision(&variant, &root).unwrap();
fs::write(&base, prefab("base-b", &[])).unwrap();
let after = prefab_graph_revision(&variant, &root).unwrap();
assert_ne!(before, after);
fs::remove_dir_all(root).unwrap();
}
#[test]
fn missing_and_cyclic_sources_are_rejected() {
let root = fixture_root();
let a = root.join("assets/prefabs/a.scn.ron");
let b = root.join("assets/prefabs/b.scn.ron");
fs::write(&a, prefab("a", &[("b", "assets/prefabs/b.scn.ron")])).unwrap();
let error = validate_prefab_graph(&a, &root).unwrap_err();
assert!(error.contains("missing prefab source"), "{error}");
fs::write(&b, prefab("b", &[("a", "assets/prefabs/a.scn.ron")])).unwrap();
let error = validate_prefab_graph(&a, &root).unwrap_err();
assert!(error.contains("cyclic prefab reference"), "{error}");
fs::remove_dir_all(root).unwrap();
}
#[test]
fn virtual_variant_cycle_and_unsafe_path_are_rejected() {
let root = fixture_root();
let variant_path = root.join("assets/prefabs/variant.scn.ron");
let text = prefab("variant", &[("self", "assets/prefabs/variant.scn.ron")]);
let error = validate_prefab_graph_text(&text, &variant_path, &root).unwrap_err();
assert!(error.contains("cyclic prefab reference"), "{error}");
let text = prefab("unsafe", &[("escape", "../outside.scn.ron")]);
let error = validate_prefab_graph_text(&text, &variant_path, &root).unwrap_err();
assert!(error.contains("may not escape"), "{error}");
fs::remove_dir_all(root).unwrap();
}
#[test]
fn duplicate_actor_ids_are_rejected() {
let root = fixture_root();
let prefab_path = root.join("assets/prefabs/duplicate.scn.ron");
let text = concat!(
"(schema_version:2,resources:{},entities:{",
"1:(components:{\"shared::components::LevelObject\":(),",
"\"shared::components::ActorId\":(\"same-actor\")}),",
"2:(components:{\"shared::components::LevelObject\":(),",
"\"shared::components::ActorId\":(\"same-actor\")})",
"})"
);
let error = validate_prefab_graph_text(text, &prefab_path, &root).unwrap_err();
assert!(error.contains("duplicate ActorId `same-actor`"), "{error}");
fs::remove_dir_all(root).unwrap();
}
#[cfg(unix)]
#[test]
fn symlink_alias_cycle_is_rejected() {
use std::os::unix::fs::symlink;
let root = fixture_root();
let real = root.join("assets/prefabs/real.scn.ron");
let alias = root.join("assets/prefabs/alias.scn.ron");
fs::write(
&real,
prefab("real", &[("alias", "assets/prefabs/alias.scn.ron")]),
)
.unwrap();
symlink("real.scn.ron", &alias).unwrap();
let error = validate_prefab_graph(&real, &root).unwrap_err();
assert!(error.contains("cyclic prefab reference"), "{error}");
fs::remove_dir_all(root).unwrap();
}
#[cfg(unix)]
#[test]
fn new_prefab_path_cannot_escape_through_symlink_parent() {
use std::os::unix::fs::symlink;
let root = fixture_root();
let outside = std::env::temp_dir().join(format!(
"blacksite-prefab-outside-{}-{}",
std::process::id(),
NEXT_FIXTURE.fetch_add(1, Ordering::Relaxed)
));
fs::create_dir_all(&outside).unwrap();
fs::remove_dir(root.join("assets/prefabs")).unwrap();
symlink(&outside, root.join("assets/prefabs")).unwrap();
let output = root.join("assets/prefabs/escaped.scn.ron");
let error = validate_prefab_graph_text(&prefab("safe", &[]), &output, &root).unwrap_err();
assert!(error.contains("outside project root"), "{error}");
fs::remove_dir_all(root).unwrap();
fs::remove_dir_all(outside).unwrap();
}
}
File diff suppressed because it is too large. Load diff