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

+833
View File
@@ -0,0 +1,833 @@
//! Generated animation artifacts for imported model sources.
use std::collections::BTreeSet;
use std::fs;
use std::path::Path;
use std::time::UNIX_EPOCH;
use serde::Deserialize;
use shared::{
animation_clip_sub_asset_id, animation_skeleton_sub_asset_id, AnimationClipRecord,
AnimationDiagnosticSeverity, AnimationEventDesc, AnimationImportDiagnostic, AnimationManifest,
AnimationManifestSource, AnimationSkeletonRecord, AnimationSkeletonSignature,
AnimationSourceFingerprint, ANIMATION_ARTIFACT_DIR, ANIMATION_MANIFEST_SCHEMA_VERSION,
};
use crate::asset_db::AssetRecord;
pub fn animation_manifest_path(asset_id: &str) -> String {
format!("{ANIMATION_ARTIFACT_DIR}/{asset_id}.animation.ron")
}
pub fn refresh_animation_artifact(record: &mut AssetRecord) -> Result<AnimationManifest, String> {
let mut manifest = build_animation_manifest(record)?;
manifest.source.dependencies.sort();
manifest.source.dependencies.dedup();
let path = animation_manifest_path(&record.id.as_string());
record.import_settings.animation_manifest_path = Some(path.clone());
record
.dependencies
.extend(manifest.source.dependencies.iter().cloned());
record.dependencies.sort();
record.dependencies.dedup();
let text = ron::ser::to_string_pretty(&manifest, ron::ser::PrettyConfig::default())
.map_err(|error| format!("could not serialize animation manifest: {error}"))?;
if let Some(parent) = Path::new(&path).parent() {
fs::create_dir_all(parent)
.map_err(|error| format!("could not create {}: {error}", parent.display()))?;
}
if fs::read_to_string(&path).ok().as_deref() != Some(text.as_str()) {
fs::write(&path, text)
.map_err(|error| format!("could not write animation manifest {path}: {error}"))?;
bevy::log::info!(
"Animation manifest refreshed: source={} artifact={} skeletons={} clips={} runtime_supported={}",
record.path,
path,
manifest.skeletons.len(),
manifest.clips.len(),
manifest.runtime_supported
);
}
Ok(manifest)
}
pub fn load_animation_manifest(path: &str) -> Result<AnimationManifest, String> {
let text =
fs::read_to_string(path).map_err(|error| format!("could not read {path}: {error}"))?;
ron::from_str(&text).map_err(|error| format!("could not parse {path}: {error}"))
}
pub fn build_animation_manifest(record: &AssetRecord) -> Result<AnimationManifest, String> {
let bytes = fs::read(&record.path)
.map_err(|error| format!("could not read {}: {error}", record.path))?;
let fingerprint = source_fingerprint(&record.path, &bytes)?;
let format = source_format(&record.path)?;
match format.as_str() {
"gltf" | "glb" => build_gltf_manifest(record, format, fingerprint, &bytes),
"fbx" => build_fbx_manifest(record, format, fingerprint, &bytes),
_ => Err(format!("unsupported animation source format `{format}`")),
}
}
#[derive(Debug, Clone)]
struct SkeletonCandidate {
compatible_nodes: BTreeSet<usize>,
signature: AnimationSkeletonSignature,
}
fn build_gltf_manifest(
record: &AssetRecord,
format: String,
fingerprint: AnimationSourceFingerprint,
bytes: &[u8],
) -> Result<AnimationManifest, String> {
let gltf = gltf::Gltf::from_slice(bytes)
.map_err(|error| format!("could not parse glTF {}: {error}", record.path))?;
let base = Path::new(&record.path).parent();
let buffers = gltf::import_buffers(&gltf.document, base, gltf.blob.clone())
.map_err(|error| format!("could not load glTF buffers for {}: {error}", record.path))?;
let mut dependencies = gltf
.document
.buffers()
.filter_map(|buffer| match buffer.source() {
gltf::buffer::Source::Uri(uri) if !uri.starts_with("data:") => {
Some(resolve_dependency(&record.path, uri))
}
_ => None,
})
.collect::<Vec<_>>();
dependencies.sort();
dependencies.dedup();
let node_identity_names = gltf
.document
.nodes()
.map(|node| bevy_node_segment(node.name(), node.index()))
.collect::<Vec<_>>();
let readable_node_names = gltf
.document
.nodes()
.map(|node| normalized_node_segment(node.name(), node.index()))
.collect::<Vec<_>>();
let mut parents = vec![None; node_identity_names.len()];
for node in gltf.document.nodes() {
for child in node.children() {
parents[child.index()] = Some(node.index());
}
}
let mut skeletons = Vec::new();
let mut candidates = Vec::new();
for skin in gltf.document.skins() {
let source_index = skin.index();
let label = skin
.name()
.filter(|name| !name.trim().is_empty())
.map(str::to_string)
.unwrap_or_else(|| format!("Skeleton {source_index}"));
let joint_indices = skin.joints().map(|joint| joint.index()).collect::<Vec<_>>();
let joint_identity_paths = joint_indices
.iter()
.map(|index| node_path_segments(*index, &node_identity_names, &parents))
.collect::<Vec<_>>();
let joint_paths = joint_indices
.iter()
.map(|index| node_path(*index, &readable_node_names, &parents))
.collect::<Vec<_>>();
let bind_poses = skin
.reader(|buffer| Some(buffers[buffer.index()].0.as_slice()))
.read_inverse_bind_matrices()
.map(|matrices| matrices.map(gltf_matrix_bytes).collect::<Vec<_>>())
.unwrap_or_else(|| vec![identity_matrix_bytes(); joint_paths.len()]);
let signature = skeleton_signature(&joint_identity_paths, &bind_poses);
let mut compatible_nodes = joint_indices.into_iter().collect::<BTreeSet<_>>();
if let Some(root) = skin.skeleton() {
compatible_nodes.insert(root.index());
}
candidates.push(SkeletonCandidate {
compatible_nodes,
signature: signature.clone(),
});
skeletons.push(AnimationSkeletonRecord {
id: animation_skeleton_sub_asset_id(source_index, &label),
label,
source_index,
signature,
joint_paths,
});
}
let mut diagnostics = Vec::new();
let mut clips = Vec::new();
let mut animation_roots = BTreeSet::new();
for animation in gltf.document.animations() {
let source_index = animation.index();
let label = animation
.name()
.filter(|name| !name.trim().is_empty())
.map(str::to_string)
.unwrap_or_else(|| format!("Animation {source_index}"));
let mut duration_seconds = 0.0_f32;
let mut target_nodes = BTreeSet::new();
for channel in animation.channels() {
let target_index = channel.target().node().index();
target_nodes.insert(target_index);
animation_roots.insert(top_level_node(target_index, &parents));
if let Some(inputs) = channel
.reader(|buffer| Some(buffers[buffer.index()].0.as_slice()))
.read_inputs()
{
for input in inputs {
if input.is_finite() {
duration_seconds = duration_seconds.max(input);
}
}
}
}
let target_skeleton_signature = matching_skeleton_signature(&target_nodes, &candidates);
if !candidates.is_empty() && target_skeleton_signature.is_none() {
diagnostics.push(AnimationImportDiagnostic {
severity: AnimationDiagnosticSeverity::Warning,
code: "animation.clip_skeleton_unresolved".into(),
message: format!(
"clip `{label}` does not target a uniquely identifiable imported skeleton"
),
repair: "Export the clip with channels targeting one skeleton, or split unrelated rigs into separate glTF assets.".into(),
});
}
let events = gltf_animation_events(&animation, duration_seconds, &label, &mut diagnostics);
clips.push(AnimationClipRecord {
id: animation_clip_sub_asset_id(source_index, &label),
label,
source_index,
duration_seconds,
target_skeleton_signature,
events,
});
}
let runtime_supported = animation_roots.len() <= 1;
if !runtime_supported {
let roots = animation_roots
.iter()
.map(|index| format!("`{}` (node {index})", node_identity_names[*index]))
.collect::<Vec<_>>()
.join(", ");
diagnostics.push(AnimationImportDiagnostic {
severity: AnimationDiagnosticSeverity::Error,
code: "animation.multiple_roots_unsupported".into(),
message: format!(
"animation channels target {} distinct top-level roots ({roots}); Bevy requires a separate AnimationPlayer for each root",
animation_roots.len()
),
repair: "Split the source into one animated rig per glTF asset, or export every clip under one common top-level root, then reimport.".into(),
});
}
Ok(AnimationManifest {
schema_version: ANIMATION_MANIFEST_SCHEMA_VERSION,
asset_id: record.id.as_string(),
label: record.label.clone(),
source: AnimationManifestSource {
path: record.path.clone(),
format,
fingerprint,
dependencies,
},
runtime_supported,
skeletons,
clips,
diagnostics,
})
}
fn build_fbx_manifest(
record: &AssetRecord,
format: String,
fingerprint: AnimationSourceFingerprint,
bytes: &[u8],
) -> Result<AnimationManifest, String> {
let scene = ufbx::load_memory(
bytes,
ufbx::LoadOpts {
target_unit_meters: 1.0,
target_axes: ufbx::CoordinateAxes::right_handed_y_up(),
..Default::default()
},
)
.map_err(|error| format!("could not parse FBX {}: {error:?}", record.path))?;
let mut skeletons = Vec::new();
for (source_index, skin) in scene.skin_deformers.as_ref().iter().enumerate() {
let label = if skin.element.name.is_empty() {
format!("Skeleton {source_index}")
} else {
skin.element.name.to_string()
};
let mut joint_identity_paths = Vec::new();
let mut joint_paths = Vec::new();
let mut bind_poses = Vec::new();
for cluster in skin.clusters.as_ref() {
let Some(bone) = cluster.bone_node.as_ref() else {
continue;
};
let segments = fbx_node_path_segments(bone.as_ref());
joint_paths.push(segments.join("/"));
joint_identity_paths.push(segments);
bind_poses.push(fbx_matrix_bytes(&cluster.bind_to_world));
}
let signature = skeleton_signature(&joint_identity_paths, &bind_poses);
skeletons.push(AnimationSkeletonRecord {
id: animation_skeleton_sub_asset_id(source_index, &label),
label,
source_index,
signature,
joint_paths,
});
}
let fallback_signature = (skeletons.len() == 1).then(|| skeletons[0].signature.clone());
let clips = scene
.anim_stacks
.as_ref()
.iter()
.enumerate()
.map(|(source_index, stack)| {
let label = if stack.element.name.is_empty() {
format!("Animation {source_index}")
} else {
stack.element.name.to_string()
};
AnimationClipRecord {
id: animation_clip_sub_asset_id(source_index, &label),
label,
source_index,
duration_seconds: (stack.time_end - stack.time_begin).max(0.0) as f32,
target_skeleton_signature: fallback_signature.clone(),
events: Vec::new(),
}
})
.collect::<Vec<_>>();
let (runtime_supported, diagnostics) = fbx_runtime_support(
scene.anim_stacks.as_ref().len(),
scene.skin_deformers.as_ref().len(),
);
Ok(AnimationManifest {
schema_version: ANIMATION_MANIFEST_SCHEMA_VERSION,
asset_id: record.id.as_string(),
label: record.label.clone(),
source: AnimationManifestSource {
path: record.path.clone(),
format,
fingerprint,
dependencies: Vec::new(),
},
runtime_supported,
skeletons,
clips,
diagnostics,
})
}
fn fbx_runtime_support(
animation_count: usize,
skin_count: usize,
) -> (bool, Vec<AnimationImportDiagnostic>) {
let mut diagnostics = Vec::new();
if animation_count > 0 || skin_count > 0 {
diagnostics.push(AnimationImportDiagnostic {
severity: AnimationDiagnosticSeverity::Error,
code: "animation.fbx_runtime_unsupported".into(),
message: format!(
"FBX contains {animation_count} animation stack(s) and {skin_count} skin deformer(s), but Blacksite's current FBX loader cannot build a runtime skeleton or clips"
),
repair: "Export the animated source as glTF 2.0 (.glb or .gltf). Keep FBX only for static mesh import until hierarchy, SkinnedMesh, and AnimationClip conversion are implemented.".into(),
});
}
(false, diagnostics)
}
#[derive(Debug, Default, Deserialize)]
struct GltfAnimationExtras {
#[serde(default)]
blacksite_events: Vec<GltfAnimationEvent>,
}
#[derive(Debug, Deserialize)]
struct GltfAnimationEvent {
id: String,
time_seconds: f32,
#[serde(default)]
payload: Option<String>,
}
fn gltf_animation_events(
animation: &gltf::Animation<'_>,
duration_seconds: f32,
clip_label: &str,
diagnostics: &mut Vec<AnimationImportDiagnostic>,
) -> Vec<AnimationEventDesc> {
let Some(raw) = animation.extras().as_ref() else {
return Vec::new();
};
let extras = match serde_json::from_str::<GltfAnimationExtras>(raw.get()) {
Ok(extras) => extras,
Err(error) => {
diagnostics.push(AnimationImportDiagnostic {
severity: AnimationDiagnosticSeverity::Warning,
code: "animation.events_invalid".into(),
message: format!("clip `{clip_label}` has invalid animation event metadata: {error}"),
repair: "Use an animation extras object with `blacksite_events` entries containing `id`, `time_seconds`, and optional string `payload`.".into(),
});
return Vec::new();
}
};
let mut events = Vec::new();
for event in extras.blacksite_events {
let valid_time = event.time_seconds.is_finite()
&& event.time_seconds >= 0.0
&& event.time_seconds <= duration_seconds;
if event.id.trim().is_empty() || !valid_time {
diagnostics.push(AnimationImportDiagnostic {
severity: AnimationDiagnosticSeverity::Warning,
code: "animation.event_out_of_range".into(),
message: format!(
"clip `{clip_label}` contains an event with an empty ID or time outside 0..={duration_seconds:.3}s"
),
repair: "Give every event a stable non-empty ID and place it within the imported clip duration.".into(),
});
continue;
}
events.push(AnimationEventDesc {
id: event.id,
time_seconds: event.time_seconds,
payload: event.payload,
});
}
events.sort_by(|left, right| {
left.time_seconds
.total_cmp(&right.time_seconds)
.then(left.id.cmp(&right.id))
.then(left.payload.cmp(&right.payload))
});
events
}
fn matching_skeleton_signature(
target_nodes: &BTreeSet<usize>,
candidates: &[SkeletonCandidate],
) -> Option<AnimationSkeletonSignature> {
let scored = candidates
.iter()
.map(|candidate| {
(
candidate
.compatible_nodes
.intersection(target_nodes)
.count(),
candidate,
)
})
.filter(|(score, _)| *score > 0)
.collect::<Vec<_>>();
let best_score = scored.iter().map(|(score, _)| *score).max()?;
let mut best = scored
.into_iter()
.filter(|(score, _)| *score == best_score)
.map(|(_, candidate)| candidate);
let candidate = best.next()?;
best.all(|other| other.signature == candidate.signature)
.then(|| candidate.signature.clone())
}
fn node_path(index: usize, names: &[String], parents: &[Option<usize>]) -> String {
node_path_segments(index, names, parents).join("/")
}
fn node_path_segments(index: usize, names: &[String], parents: &[Option<usize>]) -> Vec<String> {
let mut segments = Vec::new();
let mut current = Some(index);
while let Some(node_index) = current {
segments.push(names[node_index].clone());
current = parents[node_index];
}
segments.reverse();
segments
}
fn top_level_node(index: usize, parents: &[Option<usize>]) -> usize {
let mut current = index;
while let Some(parent) = parents[current] {
current = parent;
}
current
}
fn bevy_node_segment(name: Option<&str>, index: usize) -> String {
name.map(str::to_string)
.unwrap_or_else(|| format!("GltfNode{index}"))
}
fn normalized_node_segment(name: Option<&str>, index: usize) -> String {
name.map(str::trim)
.filter(|name| !name.is_empty())
.map(|name| name.replace(['/', '\\'], "_"))
.unwrap_or_else(|| format!("Node{index}"))
}
fn fbx_node_path_segments(node: &ufbx::Node) -> Vec<String> {
let mut segments = Vec::new();
let mut current = Some(node);
while let Some(node) = current {
segments.push(normalized_node_segment(
(!node.element.name.is_empty()).then(|| node.element.name.as_ref()),
node.element.element_id as usize,
));
current = node.parent.as_ref().map(|parent| parent.as_ref());
}
segments.reverse();
segments
}
fn skeleton_signature(
joint_path_segments: &[Vec<String>],
bind_pose_bytes: &[Vec<u8>],
) -> AnimationSkeletonSignature {
let mut hasher = blake3::Hasher::new();
hasher.update(b"blacksite-animation-skeleton-v2\0");
hasher.update(&(joint_path_segments.len() as u64).to_le_bytes());
for path in joint_path_segments {
hasher.update(&(path.len() as u64).to_le_bytes());
for segment in path {
let bytes = segment.as_bytes();
hasher.update(&(bytes.len() as u64).to_le_bytes());
hasher.update(bytes);
}
}
hasher.update(&(bind_pose_bytes.len() as u64).to_le_bytes());
for bytes in bind_pose_bytes {
hasher.update(&(bytes.len() as u64).to_le_bytes());
hasher.update(bytes);
}
AnimationSkeletonSignature::new(hasher.finalize().to_hex().to_string())
}
fn gltf_matrix_bytes(matrix: [[f32; 4]; 4]) -> Vec<u8> {
matrix
.into_iter()
.flatten()
.flat_map(f32::to_le_bytes)
.collect()
}
fn identity_matrix_bytes() -> Vec<u8> {
gltf_matrix_bytes([
[1.0, 0.0, 0.0, 0.0],
[0.0, 1.0, 0.0, 0.0],
[0.0, 0.0, 1.0, 0.0],
[0.0, 0.0, 0.0, 1.0],
])
}
fn fbx_matrix_bytes(matrix: &ufbx::Matrix) -> Vec<u8> {
[
matrix.m00, matrix.m10, matrix.m20, matrix.m01, matrix.m11, matrix.m21, matrix.m02,
matrix.m12, matrix.m22, matrix.m03, matrix.m13, matrix.m23,
]
.into_iter()
.flat_map(f64::to_le_bytes)
.collect()
}
fn source_fingerprint(path: &str, bytes: &[u8]) -> Result<AnimationSourceFingerprint, String> {
let metadata = fs::metadata(path).map_err(|error| format!("could not stat {path}: {error}"))?;
let modified_unix_secs = metadata
.modified()
.ok()
.and_then(|time| time.duration_since(UNIX_EPOCH).ok())
.map(|duration| duration.as_secs())
.unwrap_or_default();
Ok(AnimationSourceFingerprint {
byte_len: metadata.len(),
modified_unix_secs,
content_hash: blake3::hash(bytes).to_hex().to_string(),
})
}
fn source_format(path: &str) -> Result<String, String> {
Path::new(path)
.extension()
.and_then(|extension| extension.to_str())
.map(|extension| extension.to_ascii_lowercase())
.ok_or_else(|| format!("asset path `{path}` has no extension"))
}
fn resolve_dependency(source_path: &str, uri: &str) -> String {
Path::new(source_path)
.parent()
.unwrap_or_else(|| Path::new(""))
.join(uri)
.to_string_lossy()
.replace('\\', "/")
}
#[cfg(test)]
mod tests {
use super::*;
use crate::asset_db::{AssetId, ImportSettings};
use uuid::Uuid;
fn fixture_record(path: &Path) -> AssetRecord {
AssetRecord {
id: AssetId(Uuid::nil()),
path: path.to_string_lossy().replace('\\', "/"),
label: "Animated Hero".into(),
kind_tag: "Model".into(),
import_settings: ImportSettings::default(),
dependencies: Vec::new(),
}
}
fn write_animated_gltf(root: &Path) -> std::path::PathBuf {
fs::create_dir_all(root).unwrap();
let mut buffer = Vec::new();
for value in [0.0_f32, 1.25] {
buffer.extend_from_slice(&value.to_le_bytes());
}
for value in [0.0_f32, 0.0, 0.0, 1.0, 0.0, 0.38268343, 0.0, 0.9238795] {
buffer.extend_from_slice(&value.to_le_bytes());
}
fs::write(root.join("animated.bin"), buffer).unwrap();
let gltf = r#"{
"asset":{"version":"2.0"},
"scene":0,
"scenes":[{"nodes":[0]}],
"nodes":[{"name":"Armature","children":[1]},{"name":"Hip"}],
"skins":[{"name":"Hero Rig","skeleton":0,"joints":[1]}],
"buffers":[{"uri":"animated.bin","byteLength":40}],
"bufferViews":[
{"buffer":0,"byteOffset":0,"byteLength":8},
{"buffer":0,"byteOffset":8,"byteLength":32}
],
"accessors":[
{"bufferView":0,"componentType":5126,"count":2,"type":"SCALAR","min":[0.0],"max":[1.25]},
{"bufferView":1,"componentType":5126,"count":2,"type":"VEC4"}
],
"animations":[{
"name":"Idle Loop",
"samplers":[{"input":0,"output":1,"interpolation":"LINEAR"}],
"channels":[{"sampler":0,"target":{"node":1,"path":"rotation"}}],
"extras":{"blacksite_events":[{"id":"footstep.left","time_seconds":0.5,"payload":"stone"}]}
}]
}"#;
let path = root.join("animated.gltf");
fs::write(&path, gltf).unwrap();
path
}
fn write_multi_root_animated_gltf(root: &Path) -> std::path::PathBuf {
fs::create_dir_all(root).unwrap();
let mut buffer = Vec::new();
for value in [0.0_f32, 1.0] {
buffer.extend_from_slice(&value.to_le_bytes());
}
for value in [0.0_f32, 0.0, 0.0, 1.0, 0.0, 0.38268343, 0.0, 0.9238795] {
buffer.extend_from_slice(&value.to_le_bytes());
}
fs::write(root.join("multi-root.bin"), buffer).unwrap();
let gltf = r#"{
"asset":{"version":"2.0"},
"scene":0,
"scenes":[{"nodes":[0,2]}],
"nodes":[
{"name":"Character A","children":[1]},
{"name":"Joint A"},
{"name":"Character B","children":[3]},
{"name":"Joint B"}
],
"buffers":[{"uri":"multi-root.bin","byteLength":40}],
"bufferViews":[
{"buffer":0,"byteOffset":0,"byteLength":8},
{"buffer":0,"byteOffset":8,"byteLength":32}
],
"accessors":[
{"bufferView":0,"componentType":5126,"count":2,"type":"SCALAR","min":[0.0],"max":[1.0]},
{"bufferView":1,"componentType":5126,"count":2,"type":"VEC4"}
],
"animations":[{
"name":"Two Players Required",
"samplers":[
{"input":0,"output":1,"interpolation":"LINEAR"},
{"input":0,"output":1,"interpolation":"LINEAR"}
],
"channels":[
{"sampler":0,"target":{"node":1,"path":"rotation"}},
{"sampler":1,"target":{"node":3,"path":"rotation"}}
]
}]
}"#;
let path = root.join("multi-root.gltf");
fs::write(&path, gltf).unwrap();
path
}
#[test]
fn animation_manifest_path_uses_registry_uuid() {
assert_eq!(
animation_manifest_path("abc"),
"assets/animations/generated/abc.animation.ron"
);
}
#[test]
fn gltf_extraction_is_deterministic_and_preserves_duration_events_and_signature() {
let root = std::env::temp_dir().join(format!("blacksite-animation-{}", Uuid::new_v4()));
let path = write_animated_gltf(&root);
let record = fixture_record(&path);
let first = build_animation_manifest(&record).unwrap();
let second = build_animation_manifest(&record).unwrap();
assert_eq!(first, second);
assert_eq!(first.schema_version, 2);
assert!(first.runtime_supported);
assert_eq!(first.source.dependencies.len(), 1);
assert_eq!(first.skeletons.len(), 1);
assert_eq!(first.clips.len(), 1);
assert_eq!(first.skeletons[0].id, "animation:skeleton:0:hero_rig");
assert!(!first.skeletons[0].signature.is_empty());
assert_eq!(first.clips[0].id, "animation:clip:0:idle_loop");
assert_eq!(first.clips[0].duration_seconds, 1.25);
assert_eq!(
first.clips[0].target_skeleton_signature,
Some(first.skeletons[0].signature.clone())
);
assert_eq!(first.clips[0].events.len(), 1);
assert_eq!(first.clips[0].events[0].id, "footstep.left");
assert_eq!(first.clips[0].events[0].time_seconds, 0.5);
assert_eq!(first.diagnostics, Vec::new());
fs::remove_dir_all(root).unwrap();
}
#[test]
fn exact_signature_changes_with_joint_path_or_bind_pose() {
let identity = identity_matrix_bytes();
let first = skeleton_signature(
&[vec!["Armature".into(), "Hip".into()]],
std::slice::from_ref(&identity),
);
let renamed = skeleton_signature(
&[vec!["Armature".into(), "Pelvis".into()]],
std::slice::from_ref(&identity),
);
let mut changed_pose = identity;
changed_pose[0] ^= 1;
let rebound = skeleton_signature(&[vec!["Armature".into(), "Hip".into()]], &[changed_pose]);
assert_ne!(first, renamed);
assert_ne!(first, rebound);
}
#[test]
fn exact_signature_preserves_bevy_node_bytes_and_segment_boundaries() {
let identity = identity_matrix_bytes();
let slash_in_name = vec![vec!["Armature".into(), "Hip/Joint".into()]];
let slash_as_boundary = vec![vec!["Armature/Hip".into(), "Joint".into()]];
assert_eq!(slash_in_name[0].join("/"), slash_as_boundary[0].join("/"));
assert_ne!(
skeleton_signature(&slash_in_name, std::slice::from_ref(&identity)),
skeleton_signature(&slash_as_boundary, std::slice::from_ref(&identity))
);
let backslash = vec![vec!["Armature".into(), "Hip\\Joint".into()]];
assert_eq!(
normalized_node_segment(Some("Hip/Joint"), 1),
normalized_node_segment(Some("Hip\\Joint"), 1)
);
assert_ne!(
skeleton_signature(&slash_in_name, std::slice::from_ref(&identity)),
skeleton_signature(&backslash, std::slice::from_ref(&identity))
);
assert_eq!(bevy_node_segment(Some(" /Joint "), 7), " /Joint ");
assert_eq!(bevy_node_segment(None, 7), "GltfNode7");
}
#[test]
fn gltf_with_multiple_animation_roots_is_runtime_unsupported() {
let root =
std::env::temp_dir().join(format!("blacksite-animation-multi-root-{}", Uuid::new_v4()));
let path = write_multi_root_animated_gltf(&root);
let manifest = build_animation_manifest(&fixture_record(&path)).unwrap();
assert!(!manifest.runtime_supported);
let diagnostic = manifest
.diagnostics
.iter()
.find(|diagnostic| diagnostic.code == "animation.multiple_roots_unsupported")
.expect("multi-root glTF should include an actionable blocking diagnostic");
assert_eq!(diagnostic.severity, AnimationDiagnosticSeverity::Error);
assert!(diagnostic.message.contains("2 distinct top-level roots"));
assert!(diagnostic.repair.contains("one common top-level root"));
fs::remove_dir_all(root).unwrap();
}
#[test]
fn animated_or_skinned_fbx_is_runtime_unsupported_with_repair_guidance() {
let (supported, diagnostics) = fbx_runtime_support(2, 1);
assert!(!supported);
assert_eq!(diagnostics.len(), 1);
assert_eq!(diagnostics[0].severity, AnimationDiagnosticSeverity::Error);
assert_eq!(diagnostics[0].code, "animation.fbx_runtime_unsupported");
assert!(diagnostics[0].repair.contains("glTF 2.0"));
let (supported, diagnostics) = fbx_runtime_support(0, 0);
assert!(!supported);
assert!(diagnostics.is_empty());
}
#[test]
fn committed_robot_fixture_exposes_a_skin_and_multiple_named_states() {
let path =
Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/models/robot_expressive.glb");
let manifest = build_animation_manifest(&fixture_record(&path)).unwrap();
assert!(manifest.runtime_supported);
assert_eq!(manifest.skeletons.len(), 2);
assert_eq!(manifest.skeletons[0].id, "animation:skeleton:0:skeleton_0");
assert_eq!(manifest.skeletons[1].id, "animation:skeleton:1:skeleton_1");
assert!(manifest
.skeletons
.iter()
.all(|skeleton| skeleton.joint_paths.len() == 43));
let signature = &manifest.skeletons[0].signature;
assert!(manifest
.skeletons
.iter()
.all(|skeleton| &skeleton.signature == signature));
assert_eq!(manifest.clips.len(), 14);
for expected in ["Idle", "Walking", "Running", "Jump", "Wave"] {
assert!(
manifest.clips.iter().any(|clip| clip.label == expected),
"missing expected fixture clip {expected}"
);
}
assert!(manifest
.clips
.iter()
.all(|clip| clip.duration_seconds.is_finite() && clip.duration_seconds > 0.0));
assert!(manifest
.clips
.iter()
.all(|clip| { clip.target_skeleton_signature.as_ref() == Some(signature) }));
assert!(manifest.diagnostics.is_empty());
}
}
+174 -4
View File
@@ -2,7 +2,7 @@
use bevy::prelude::*;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::collections::{HashMap, HashSet};
use uuid::Uuid;
/// Stable asset identity for dependency tracking and prefab references.
@@ -59,6 +59,8 @@ pub struct ImportSettings {
pub material_policy: MaterialImportPolicy,
#[serde(default)]
pub static_mesh_manifest_path: Option<String>,
#[serde(default)]
pub animation_manifest_path: Option<String>,
}
impl Default for ImportSettings {
@@ -71,6 +73,7 @@ impl Default for ImportSettings {
hierarchy_mode: ModelHierarchyMode::default(),
material_policy: MaterialImportPolicy::default(),
static_mesh_manifest_path: None,
animation_manifest_path: None,
}
}
}
@@ -115,6 +118,11 @@ fn sync_registry_from_browser(
.drain(..)
.map(|record| (record.path.clone(), record))
.collect();
let current_paths = assets
.assets
.iter()
.filter_map(|asset| asset.path.clone())
.collect::<HashSet<_>>();
let mut next_records = Vec::new();
let mut seen_paths = HashMap::new();
@@ -129,7 +137,18 @@ fn sync_registry_from_browser(
seen_paths.insert(path.clone(), ());
let kind_tag = format!("{:?}", asset.kind);
let mut record = if let Some(mut prior) = existing.remove(&path) {
let mut record = if let Some(mut prior) = existing.remove(&path).or_else(|| {
take_uniquely_moved_model_record(&mut existing, &current_paths, &path, &kind_tag)
}) {
if prior.path != path {
info!(
"Asset registry preserved model identity {} across move {} -> {}",
prior.id.as_string(),
prior.path,
path
);
prior.path = path.clone();
}
prior.label = asset.label.clone();
prior.kind_tag = kind_tag;
prior
@@ -144,9 +163,9 @@ fn sync_registry_from_browser(
}
};
if record.kind_tag == "Model" {
if let Err(error) = super::static_mesh::refresh_static_mesh_artifact(&mut record) {
if let Err(error) = super::refresh_model_artifacts(&mut record) {
warn!(
"Static mesh processor failed for {} (asset id {}): {error}",
"Model artifact refresh failed for {} (asset id {}): {error}",
record.path,
record.id.as_string()
);
@@ -170,6 +189,34 @@ fn sync_registry_from_browser(
}
}
fn take_uniquely_moved_model_record(
existing: &mut HashMap<String, AssetRecord>,
current_paths: &HashSet<String>,
new_path: &str,
kind_tag: &str,
) -> Option<AssetRecord> {
if kind_tag != "Model" {
return None;
}
let bytes = std::fs::read(new_path).ok()?;
let content_hash = blake3::hash(&bytes).to_hex().to_string();
let candidates = existing
.iter()
.filter_map(|(old_path, record)| {
if current_paths.contains(old_path) || record.kind_tag != "Model" {
return None;
}
let manifest_path = record.import_settings.animation_manifest_path.as_deref()?;
let manifest = super::animation::load_animation_manifest(manifest_path).ok()?;
(manifest.source.fingerprint.content_hash == content_hash).then(|| old_path.clone())
})
.collect::<Vec<_>>();
if candidates.len() != 1 {
return None;
}
existing.remove(&candidates[0])
}
pub fn find_asset_by_path(registry: &AssetRegistry, path: &str) -> Option<AssetRecord> {
registry
.records
@@ -196,6 +243,34 @@ pub fn find_asset_mut_by_path<'a>(
.find(|record| record.path == path)
}
pub fn ensure_asset_record(
registry: &mut AssetRegistry,
path: impl Into<String>,
label: impl Into<String>,
kind_tag: impl Into<String>,
) -> Result<AssetRecord, String> {
let path = path.into();
if let Some(record) = find_asset_by_path(registry, &path) {
return Ok(record);
}
let record = AssetRecord {
id: AssetId::new(),
path,
label: label.into(),
kind_tag: kind_tag.into(),
import_settings: ImportSettings::default(),
dependencies: Vec::new(),
};
registry.records.push(record.clone());
registry.index_dirty = true;
if let Err(error) = save_registry(registry) {
registry.records.pop();
return Err(error);
}
registry.index_dirty = false;
Ok(record)
}
pub fn update_import_settings(
registry: &mut AssetRegistry,
path: &str,
@@ -240,3 +315,98 @@ pub fn load_registry() -> AssetRegistry {
Err(_) => AssetRegistry::default(),
}
}
#[cfg(test)]
mod tests {
use super::*;
use shared::{
AnimationManifest, AnimationManifestSource, AnimationSourceFingerprint,
ANIMATION_MANIFEST_SCHEMA_VERSION,
};
fn moved_model_fixture(bytes: &[u8]) -> (std::path::PathBuf, std::path::PathBuf, AssetRecord) {
let key = Uuid::new_v4();
let source_path = std::env::temp_dir().join(format!("blacksite-moved-model-{key}.glb"));
let manifest_path =
std::env::temp_dir().join(format!("blacksite-moved-model-{key}.animation.ron"));
std::fs::write(&source_path, bytes).unwrap();
let id = AssetId::new();
let old_path = format!("assets/models/old-{key}.glb");
let manifest = AnimationManifest {
schema_version: ANIMATION_MANIFEST_SCHEMA_VERSION,
asset_id: id.as_string(),
label: "Moved Model".into(),
source: AnimationManifestSource {
path: old_path.clone(),
format: "glb".into(),
fingerprint: AnimationSourceFingerprint {
byte_len: bytes.len() as u64,
modified_unix_secs: 0,
content_hash: blake3::hash(bytes).to_hex().to_string(),
},
dependencies: Vec::new(),
},
runtime_supported: true,
skeletons: Vec::new(),
clips: Vec::new(),
diagnostics: Vec::new(),
};
std::fs::write(
&manifest_path,
ron::ser::to_string_pretty(&manifest, ron::ser::PrettyConfig::default()).unwrap(),
)
.unwrap();
let record = AssetRecord {
id,
path: old_path,
label: "Moved Model".into(),
kind_tag: "Model".into(),
import_settings: ImportSettings {
animation_manifest_path: Some(manifest_path.to_string_lossy().into_owned()),
..Default::default()
},
dependencies: Vec::new(),
};
(source_path, manifest_path, record)
}
#[test]
fn unique_content_match_preserves_model_record_across_move() {
let (source_path, manifest_path, record) = moved_model_fixture(b"stable model bytes");
let expected_id = record.id.clone();
let mut existing = HashMap::from([(record.path.clone(), record)]);
let moved = take_uniquely_moved_model_record(
&mut existing,
&HashSet::new(),
&source_path.to_string_lossy(),
"Model",
)
.expect("unique moved model should retain its registry record");
assert_eq!(moved.id, expected_id);
assert!(existing.is_empty());
let _ = std::fs::remove_file(source_path);
let _ = std::fs::remove_file(manifest_path);
}
#[test]
fn existing_source_path_is_not_reconciled_as_a_copy_move() {
let (source_path, manifest_path, record) = moved_model_fixture(b"copied model bytes");
let old_path = record.path.clone();
let mut existing = HashMap::from([(old_path.clone(), record)]);
let current_paths = HashSet::from([old_path]);
let moved = take_uniquely_moved_model_record(
&mut existing,
&current_paths,
&source_path.to_string_lossy(),
"Model",
);
assert!(moved.is_none());
assert_eq!(existing.len(), 1);
let _ = std::fs::remove_file(source_path);
let _ = std::fs::remove_file(manifest_path);
}
}
+526 -47
View File
@@ -5,28 +5,34 @@ use bevy::prelude::*;
use settings::ProjectSettings;
use shared::{
ActorKind, AuthoringLightKind, ColliderDesc, ColorDesc, EditorVisibility, LightDesc,
MaterialDesc, ModelRef, PostProcessVolumeDesc, PrefabInstance, PrefabRef, Primitive,
PrimitiveShape, RigidBodyDesc,
MaterialDesc, ModelRef, PostProcessVolumeDesc, PrefabRef, Primitive, PrimitiveShape,
RigidBodyDesc, AUDIO_CLIP_SUB_ASSET_ID,
};
use walkdir::WalkDir;
use crate::asset_db::{
find_asset_by_path, find_asset_mut_by_path, AssetRegistry, MaterialImportPolicy,
ModelPlacementMode,
};
use crate::assets::static_mesh::{
load_static_mesh_manifest, refresh_static_mesh_artifact, renderer_from_manifest,
ensure_asset_record, find_asset_by_id, find_asset_by_path, find_asset_mut_by_path,
AssetRegistry, MaterialImportPolicy, ModelPlacementMode,
};
use crate::assets::animation::load_animation_manifest;
use crate::assets::static_mesh::{load_static_mesh_manifest, renderer_from_manifest};
use crate::history::{spawn_with_history, EditorEntitySnapshot};
pub const BUILTINS_FOLDER: &str = "__builtins__";
pub const ASSETS_ROOT: &str = "assets";
pub const AUDIO_ASSET_EXTENSIONS: &[&str] = &["ogg", "oga", "spx", "wav", "mp3", "flac"];
pub const IMPORTABLE_ASSET_EXTENSIONS: &[&str] = &[
"gltf", "glb", "fbx", "png", "jpg", "jpeg", "webp", "ktx2", "ogg", "oga", "spx", "wav", "mp3",
"flac",
];
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum AssetSubAssetKind {
Mesh,
Material,
Texture,
Skeleton,
AnimationClip,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
@@ -73,6 +79,7 @@ pub enum EditorAssetKind {
Model,
Texture,
Material,
AudioClip,
Level,
Prefab,
PostProcessVolume,
@@ -219,7 +226,15 @@ pub struct EditorAssetsPlugin;
impl Plugin for EditorAssetsPlugin {
fn build(&self, app: &mut App) {
app.init_resource::<EditorAssets>()
.add_systems(Update, refresh_assets_on_settings_change);
.init_resource::<super::prefab_overrides::PrefabHealthCache>()
.add_observer(super::prefab_overrides::invalidate_prefab_health_on_ready)
.add_systems(
Update,
(
refresh_assets_on_settings_change,
super::prefab_overrides::guard_prefab_reimports,
),
);
}
}
@@ -352,50 +367,56 @@ fn should_skip_asset_path(path: &Path) -> bool {
fn asset_from_file_path(path: &Path) -> Option<EditorAsset> {
let extension = path.extension()?.to_str()?.to_ascii_lowercase();
let (kinds, extensions) = match extension.as_str() {
"gltf" | "glb" | "fbx" => (vec![EditorAssetKind::Model], vec!["gltf", "glb", "fbx"]),
"png" | "jpg" | "jpeg" | "webp" | "ktx2" => (
vec![EditorAssetKind::Texture],
vec!["png", "jpg", "jpeg", "webp", "ktx2"],
),
"ron" | "mat" | "material" => {
if path.to_string_lossy().contains("/materials/") {
(
vec![EditorAssetKind::Material],
vec!["ron", "mat", "material"],
)
} else if path.to_string_lossy().contains("/post_fx/") {
(vec![EditorAssetKind::PostProcessEffect], vec!["ron"])
} else if path.to_string_lossy().contains("/rendering_profiles/") {
(vec![EditorAssetKind::RenderingProfile], vec!["ron"])
} else if path.to_string_lossy().contains("/shaders/") {
(vec![EditorAssetKind::ShaderSchema], vec!["ron"])
} else {
(
vec![EditorAssetKind::Level, EditorAssetKind::Prefab],
vec!["ron"],
)
let normalized_path = normalize_asset_path(path);
let (kinds, extensions) = if is_audio_asset_extension(&extension) {
(
vec![EditorAssetKind::AudioClip],
AUDIO_ASSET_EXTENSIONS.to_vec(),
)
} else {
match extension.as_str() {
"gltf" | "glb" | "fbx" => (vec![EditorAssetKind::Model], vec!["gltf", "glb", "fbx"]),
"png" | "jpg" | "jpeg" | "webp" | "ktx2" => (
vec![EditorAssetKind::Texture],
vec!["png", "jpg", "jpeg", "webp", "ktx2"],
),
"ron" | "mat" | "material" => {
if normalized_path.contains("/materials/") {
(
vec![EditorAssetKind::Material],
vec!["ron", "mat", "material"],
)
} else if normalized_path.contains("/post_fx/") {
(vec![EditorAssetKind::PostProcessEffect], vec!["ron"])
} else if normalized_path.contains("/rendering_profiles/") {
(vec![EditorAssetKind::RenderingProfile], vec!["ron"])
} else if normalized_path.contains("/shaders/") {
(vec![EditorAssetKind::ShaderSchema], vec!["ron"])
} else if normalized_path.ends_with(".scn.ron")
&& (normalized_path.starts_with("assets/prefabs/")
|| normalized_path.contains("/assets/prefabs/"))
{
(vec![EditorAssetKind::Prefab], vec!["ron"])
} else {
(vec![EditorAssetKind::Level], vec!["ron"])
}
}
_ => return None,
}
_ => return None,
};
if !has_extension(path, &extensions) {
return None;
}
let path_string = normalize_asset_path(path);
let path_string = normalized_path;
let folder_path = parent_folder_path(&path_string).unwrap_or_else(|| ASSETS_ROOT.to_string());
let label = path
.file_stem()
.and_then(|stem| stem.to_str())
.unwrap_or(&path_string)
.to_string();
let kind = if kinds.len() == 2 && path_string.ends_with(".scn.ron") {
kinds[1].clone()
} else {
kinds[0].clone()
};
let kind = kinds[0].clone();
Some(EditorAsset {
label,
@@ -447,8 +468,54 @@ fn has_extension(path: &Path, extensions: &[&str]) -> bool {
})
}
pub fn snapshot_for_asset(asset: &EditorAsset, translation: Vec3) -> Option<EditorEntitySnapshot> {
let mut snapshot = EditorEntitySnapshot {
fn is_audio_asset_extension(extension: &str) -> bool {
AUDIO_ASSET_EXTENSIONS
.iter()
.any(|candidate| extension.eq_ignore_ascii_case(candidate))
}
pub fn audio_clip_ref_for_asset(
world: &mut World,
asset: &EditorAsset,
) -> Result<shared::EditorAssetRef, String> {
if !matches!(asset.kind, EditorAssetKind::AudioClip) {
return Err(format!("{} is not an audio clip", asset.label));
}
let path = asset
.path
.as_deref()
.ok_or_else(|| format!("audio clip {} has no source path", asset.label))?;
let record = world
.get_resource_mut::<AssetRegistry>()
.ok_or_else(|| "asset registry is unavailable".to_string())
.and_then(|mut registry| {
ensure_asset_record(
&mut registry,
path.to_string(),
asset.label.clone(),
"AudioClip",
)
})?;
Ok(shared::EditorAssetRef::new(
record.id.as_string(),
AUDIO_CLIP_SUB_ASSET_ID,
asset.label.clone(),
)
.with_source_path(path))
}
pub fn audio_source_desc_for_asset(
world: &mut World,
asset: &EditorAsset,
) -> Result<shared::AudioSourceDesc, String> {
Ok(shared::AudioSourceDesc {
clip: Some(audio_clip_ref_for_asset(world, asset)?),
..Default::default()
})
}
fn empty_snapshot_for_asset(asset: &EditorAsset, translation: Vec3) -> EditorEntitySnapshot {
EditorEntitySnapshot {
actor_id: None,
actor_kind: ActorKind::Empty,
actor_name: None,
@@ -463,6 +530,9 @@ pub fn snapshot_for_asset(asset: &EditorAsset, translation: Vec3) -> Option<Edit
collider: None,
physics: None,
light: None,
animation_controller: None,
audio_source: None,
audio_listener: None,
player_spawn: false,
model: None,
prefab: None,
@@ -475,7 +545,11 @@ pub fn snapshot_for_asset(asset: &EditorAsset, translation: Vec3) -> Option<Edit
hierarchy_sibling_index: 0,
editor_visibility: EditorVisibility::default(),
children: Vec::new(),
};
}
}
pub fn snapshot_for_asset(asset: &EditorAsset, translation: Vec3) -> Option<EditorEntitySnapshot> {
let mut snapshot = empty_snapshot_for_asset(asset, translation);
match &asset.kind {
EditorAssetKind::Primitive(shape) => {
@@ -522,13 +596,15 @@ pub fn snapshot_for_asset(asset: &EditorAsset, translation: Vec3) -> Option<Edit
snapshot.model = Some(ModelRef::new(path.clone()));
snapshot.transform.translation.y += 0.1;
}
EditorAssetKind::Prefab | EditorAssetKind::Level => {
EditorAssetKind::Prefab => {
snapshot.actor_kind = ActorKind::PrefabAnchor;
let path = asset.path.as_ref()?;
snapshot.prefab = Some(PrefabRef::new(path.clone()));
}
EditorAssetKind::Level => return None,
EditorAssetKind::Texture
| EditorAssetKind::Material
| EditorAssetKind::AudioClip
| EditorAssetKind::PostProcessEffect
| EditorAssetKind::RenderingProfile
| EditorAssetKind::ShaderSchema => return None,
@@ -538,7 +614,24 @@ pub fn snapshot_for_asset(asset: &EditorAsset, translation: Vec3) -> Option<Edit
}
pub fn spawn_asset_at(world: &mut World, asset: &EditorAsset, translation: Vec3) -> Option<Entity> {
let mut snapshot = snapshot_for_asset(asset, translation)?;
let mut snapshot = if matches!(asset.kind, EditorAssetKind::AudioClip) {
let descriptor = match audio_source_desc_for_asset(world, asset) {
Ok(descriptor) => descriptor,
Err(error) => {
warn!("Audio clip placement failed for {}: {error}", asset.label);
if let Some(mut scene_io) = world.get_resource_mut::<crate::scene_io::SceneIo>() {
scene_io.status = format!("Audio placement failed: {error}");
}
return None;
}
};
let mut snapshot = empty_snapshot_for_asset(asset, translation);
snapshot.actor_kind = ActorKind::AudioSource;
snapshot.audio_source = Some(descriptor);
snapshot
} else {
snapshot_for_asset(asset, translation)?
};
if let Some(light) = snapshot.light.as_mut() {
if matches!(light.kind, AuthoringLightKind::Directional) {
light.intensity = world
@@ -548,12 +641,32 @@ pub fn spawn_asset_at(world: &mut World, asset: &EditorAsset, translation: Vec3)
}
}
if let Some(path) = asset.path.as_ref() {
let record = world
let mut record = world
.get_resource::<AssetRegistry>()
.and_then(|registry| find_asset_by_path(registry, path));
if matches!(asset.kind, EditorAssetKind::Prefab) && record.is_none() {
record = world
.get_resource_mut::<AssetRegistry>()
.and_then(|mut registry| {
ensure_asset_record(&mut registry, path.clone(), asset.label.clone(), "Prefab")
.map_err(|error| {
error!("Could not register prefab asset {path}: {error}");
})
.ok()
});
}
if matches!(asset.kind, EditorAssetKind::Prefab) && record.is_none() {
if let Some(mut scene_io) = world.get_resource_mut::<crate::scene_io::SceneIo>() {
scene_io.status = format!("Prefab placement failed: could not register {path}");
}
return None;
}
if let Some(record) = record {
match asset.kind {
EditorAssetKind::Model => {
if let Some(model) = snapshot.model.as_mut() {
model.asset_id = record.id.as_string();
}
snapshot.transform.scale *= record.import_settings.scale;
if matches!(
record.import_settings.placement_mode,
@@ -580,7 +693,11 @@ pub fn spawn_asset_at(world: &mut World, asset: &EditorAsset, translation: Vec3)
}
EditorAssetKind::Prefab => {
snapshot.prefab_instance =
Some(PrefabInstance::new(record.id.as_string(), path.clone()));
Some(super::prefab_overrides::new_tracked_prefab_instance(
world,
record.id.as_string(),
path.clone(),
));
}
_ => {}
}
@@ -589,11 +706,37 @@ pub fn spawn_asset_at(world: &mut World, asset: &EditorAsset, translation: Vec3)
Some(spawn_with_history(world, snapshot))
}
pub fn validate_prefab_asset(world: &World, asset: &EditorAsset) -> Result<(), String> {
if !matches!(asset.kind, EditorAssetKind::Prefab) {
return Ok(());
}
let source_path = asset
.path
.as_deref()
.ok_or_else(|| "Prefab asset has no source path".to_string())?;
let project_root = world
.get_resource::<crate::project_io::ProjectWorkspace>()
.map(|workspace| PathBuf::from(&workspace.root))
.ok_or_else(|| "Project workspace is unavailable".to_string())?;
scene::validate_prefab_graph(&project_root.join(source_path), &project_root)
.map_err(|error| format!("Prefab dependency validation failed: {error}"))
}
pub fn spawn_subasset_at(
world: &mut World,
selection: &AssetSelection,
translation: Vec3,
) -> Option<Entity> {
if matches!(
selection,
AssetSelection::SubAsset {
kind: AssetSubAssetKind::AnimationClip,
..
}
) {
return spawn_animation_clip_at(world, selection, translation);
}
let AssetSelection::SubAsset {
parent_path,
sub_asset_id,
@@ -663,6 +806,9 @@ pub fn spawn_subasset_at(
collider: None,
physics: None,
light: None,
animation_controller: None,
audio_source: None,
audio_listener: None,
player_spawn: false,
model: None,
prefab: None,
@@ -685,6 +831,251 @@ pub fn spawn_subasset_at(
Some(spawn_with_history(world, snapshot))
}
#[derive(Debug, Clone)]
pub struct AnimationClipAuthoringData {
pub model_asset_id: String,
pub model_path: String,
pub model_label: String,
pub model_scale: f32,
pub skeleton: shared::EditorAssetRef,
pub skeleton_signature: shared::AnimationSkeletonSignature,
pub state: shared::AnimationStateDesc,
}
pub fn animation_clip_authoring_data(
world: &World,
selection: &AssetSelection,
) -> Result<AnimationClipAuthoringData, String> {
let AssetSelection::SubAsset {
parent_path,
sub_asset_id,
kind: AssetSubAssetKind::AnimationClip,
..
} = selection
else {
return Err("the selected sub-asset is not an animation clip".into());
};
let record = world
.get_resource::<AssetRegistry>()
.and_then(|registry| find_asset_by_path(registry, parent_path))
.ok_or_else(|| format!("model `{parent_path}` is missing from the asset registry"))?;
let manifest_path = record
.import_settings
.animation_manifest_path
.as_deref()
.ok_or_else(|| format!("model `{parent_path}` has no generated animation manifest"))?;
let manifest = load_animation_manifest(manifest_path)?;
if !manifest.runtime_supported {
return Err(format!(
"model `{parent_path}` is not supported by the animation runtime; animation v1 requires glTF/GLB"
));
}
let clip = manifest
.clips
.iter()
.find(|clip| clip.id == *sub_asset_id)
.ok_or_else(|| {
format!(
"animation clip `{sub_asset_id}` is missing from `{manifest_path}`; reimport the model"
)
})?;
let target_signature = clip.target_skeleton_signature.as_ref().ok_or_else(|| {
format!(
"animation clip `{}` has no uniquely resolved target skeleton",
clip.label
)
})?;
let skeleton = manifest
.skeletons
.iter()
.find(|skeleton| &skeleton.signature == target_signature)
.ok_or_else(|| {
format!(
"animation clip `{}` targets skeleton `{}` but no exact match exists in `{parent_path}`",
clip.label, target_signature.0
)
})?;
let asset_id = record.id.as_string();
let skeleton_ref = shared::EditorAssetRef::new(
asset_id.clone(),
skeleton.id.clone(),
skeleton.label.clone(),
)
.with_source_path(parent_path);
let clip_ref = shared::EditorAssetRef::new(asset_id, clip.id.clone(), clip.label.clone())
.with_source_path(parent_path);
let state_id = animation_state_id(&clip.label, clip.source_index);
Ok(AnimationClipAuthoringData {
model_asset_id: record.id.as_string(),
model_path: parent_path.clone(),
model_label: record.label,
model_scale: record.import_settings.scale,
skeleton: skeleton_ref,
skeleton_signature: skeleton.signature.clone(),
state: shared::AnimationStateDesc {
id: state_id,
label: clip.label.clone(),
clip: clip_ref,
looping: true,
speed: 1.0,
range: shared::AnimationPlaybackRange::default(),
},
})
}
pub fn animation_skeleton_signature_for_ref(
world: &World,
reference: &shared::EditorAssetRef,
) -> Result<shared::AnimationSkeletonSignature, String> {
let record = world
.get_resource::<AssetRegistry>()
.and_then(|registry| find_asset_by_id(registry, &reference.asset_id))
.ok_or_else(|| {
format!(
"skeleton asset `{}` is missing from the asset registry",
reference.asset_id
)
})?;
let manifest_path = record
.import_settings
.animation_manifest_path
.as_deref()
.ok_or_else(|| format!("model `{}` has no animation manifest", record.path))?;
let manifest = load_animation_manifest(manifest_path)?;
manifest
.skeletons
.iter()
.find(|skeleton| skeleton.id == reference.sub_asset_id)
.map(|skeleton| skeleton.signature.clone())
.ok_or_else(|| {
format!(
"skeleton `{}` is missing from `{manifest_path}`; reimport the model",
reference.sub_asset_id
)
})
}
pub fn compatible_animation_skeleton_for_model(
world: &World,
model: &ModelRef,
signature: &shared::AnimationSkeletonSignature,
) -> Result<shared::EditorAssetRef, String> {
let record = world
.get_resource::<AssetRegistry>()
.and_then(|registry| {
if model.asset_id.trim().is_empty() {
find_asset_by_path(registry, &model.path)
} else {
find_asset_by_id(registry, &model.asset_id)
}
})
.ok_or_else(|| {
format!(
"model `{}` ({}) is missing from the asset registry",
model.path, model.asset_id
)
})?;
let model_path = record.path.as_str();
let manifest_path = record
.import_settings
.animation_manifest_path
.as_deref()
.ok_or_else(|| format!("model `{model_path}` has no animation manifest"))?;
let manifest = load_animation_manifest(manifest_path)?;
let skeleton = manifest
.skeletons
.iter()
.find(|skeleton| &skeleton.signature == signature)
.ok_or_else(|| {
format!(
"model `{model_path}` has no skeleton matching animation rig `{}`",
signature.0
)
})?;
Ok(shared::EditorAssetRef::new(
record.id.as_string(),
skeleton.id.clone(),
skeleton.label.clone(),
)
.with_source_path(model_path))
}
fn animation_state_id(label: &str, source_index: usize) -> String {
let mut id = String::new();
for character in label.chars() {
if character.is_ascii_alphanumeric() {
id.push(character.to_ascii_lowercase());
} else if !id.ends_with('_') {
id.push('_');
}
}
let id = id.trim_matches('_');
if id.is_empty() {
format!("clip_{source_index}")
} else {
id.to_string()
}
}
fn spawn_animation_clip_at(
world: &mut World,
selection: &AssetSelection,
translation: Vec3,
) -> Option<Entity> {
let authored = match animation_clip_authoring_data(world, selection) {
Ok(authored) => authored,
Err(error) => {
warn!("Animation clip placement failed: {error}");
if let Some(mut scene_io) = world.get_resource_mut::<crate::scene_io::SceneIo>() {
scene_io.status = format!("Animation placement failed: {error}");
}
return None;
}
};
let default_state = authored.state.id.clone();
let snapshot = EditorEntitySnapshot {
actor_id: None,
actor_kind: ActorKind::ImportedModel,
actor_name: None,
name: Some(authored.model_label),
transform: Transform {
translation: translation + Vec3::Y * 0.1,
scale: Vec3::splat(authored.model_scale),
..default()
},
primitive: None,
brush: None,
static_mesh_renderer: None,
material: None,
material_override: None,
rigid_body: None,
collider: None,
physics: None,
light: None,
animation_controller: Some(shared::AnimationControllerDesc {
skeleton: Some(authored.skeleton),
states: vec![authored.state],
default_state,
..default()
}),
audio_source: None,
audio_listener: None,
player_spawn: false,
model: Some(ModelRef::new(authored.model_path).with_asset_id(authored.model_asset_id)),
prefab: None,
prefab_instance: None,
weapon_spawn: None,
trigger_volume: None,
post_process_volume: None,
team_spawn: None,
objective: None,
hierarchy_sibling_index: 0,
editor_visibility: EditorVisibility::default(),
children: Vec::new(),
};
Some(spawn_with_history(world, snapshot))
}
fn apply_static_mesh_placement_mode(
snapshot: &mut EditorEntitySnapshot,
renderer: shared::StaticMeshRenderer,
@@ -733,6 +1124,9 @@ fn apply_static_mesh_placement_mode(
collider,
physics: None,
light: None,
animation_controller: None,
audio_source: None,
audio_listener: None,
player_spawn: false,
model: None,
prefab: None,
@@ -788,13 +1182,13 @@ fn static_mesh_renderer_for_asset(
if let Some(mut registry) = world.get_resource_mut::<AssetRegistry>() {
let mut renderer = None;
if let Some(record) = find_asset_mut_by_path(&mut registry, path) {
match refresh_static_mesh_artifact(record) {
match super::refresh_model_artifacts(record) {
Ok(manifest) => {
renderer = Some(renderer_from_manifest(&manifest, &record.import_settings));
registry.index_dirty = true;
}
Err(error) => {
warn!("Static mesh manifest refresh failed for {path}: {error}");
warn!("Model artifact refresh failed for {path}: {error}");
manifest_path = record.import_settings.static_mesh_manifest_path.clone();
}
}
@@ -847,6 +1241,9 @@ pub fn import_external_assets(paths: &[PathBuf]) -> Result<usize, String> {
}
fn import_dir_for_extension(extension: &str) -> &'static str {
if is_audio_asset_extension(extension) {
return "assets/audio";
}
match extension.to_ascii_lowercase().as_str() {
"gltf" | "glb" | "fbx" => "assets/models",
"png" | "jpg" | "jpeg" | "webp" | "ktx2" => "assets/textures",
@@ -870,3 +1267,85 @@ pub fn asset_cache_key(asset: &EditorAsset) -> String {
None => format!("builtin:{}", asset.label),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::asset_db::{AssetId, AssetRecord};
use uuid::Uuid;
#[test]
fn scene_assets_are_classified_by_authoring_folder() {
let level = asset_from_file_path(Path::new("assets/levels/arena.scn.ron")).unwrap();
let prefab = asset_from_file_path(Path::new("assets/prefabs/crate.scn.ron")).unwrap();
assert_eq!(level.kind, EditorAssetKind::Level);
assert_eq!(prefab.kind, EditorAssetKind::Prefab);
}
#[test]
fn bevy_audio_extensions_are_classified_and_imported_to_audio() {
for extension in AUDIO_ASSET_EXTENSIONS {
let path = format!("assets/audio/impact.{extension}");
let asset = asset_from_file_path(Path::new(&path)).unwrap();
assert_eq!(asset.kind, EditorAssetKind::AudioClip);
assert_eq!(asset.folder_path, "assets/audio");
assert_eq!(import_dir_for_extension(extension), "assets/audio");
assert!(IMPORTABLE_ASSET_EXTENSIONS.contains(extension));
}
assert!(asset_from_file_path(Path::new("assets/audio/impact.m4a")).is_none());
assert_eq!(import_dir_for_extension("WAV"), "assets/audio");
}
#[test]
fn audio_clip_reference_keeps_stable_registry_identity_and_runtime_path() {
let asset = EditorAsset {
label: "Impact".into(),
path: Some("assets/audio/impact.ogg".into()),
folder_path: "assets/audio".into(),
kind: EditorAssetKind::AudioClip,
};
let stable_id = AssetId(Uuid::nil());
let mut world = World::new();
world.insert_resource(AssetRegistry {
records: vec![AssetRecord {
id: stable_id.clone(),
path: asset.path.clone().unwrap(),
label: asset.label.clone(),
kind_tag: "AudioClip".into(),
import_settings: Default::default(),
dependencies: Vec::new(),
}],
index_dirty: false,
});
world.init_resource::<crate::history::EditorHistory>();
world.init_resource::<crate::selection::SelectedEntity>();
let descriptor = audio_source_desc_for_asset(&mut world, &asset).unwrap();
let reference = descriptor.clip.unwrap();
assert_eq!(reference.asset_id, stable_id.as_string());
assert_eq!(reference.sub_asset_id, AUDIO_CLIP_SUB_ASSET_ID);
assert_eq!(reference.label, "Impact");
assert_eq!(reference.source_path.as_deref(), asset.path.as_deref());
assert_eq!(
audio_clip_ref_for_asset(&mut world, &asset)
.unwrap()
.asset_id,
reference.asset_id
);
let entity = spawn_asset_at(&mut world, &asset, Vec3::new(1.0, 2.0, 3.0)).unwrap();
assert_eq!(
world.get::<ActorKind>(entity),
Some(&ActorKind::AudioSource)
);
let placed = world.get::<shared::AudioSourceDesc>(entity).unwrap();
assert_eq!(placed.clip.as_ref(), Some(&reference));
assert_eq!(
world.get::<Transform>(entity).unwrap().translation,
Vec3::new(1.0, 2.0, 3.0)
);
assert!(world.resource::<crate::history::EditorHistory>().can_undo());
}
}
+14 -21
View File
@@ -5,7 +5,7 @@ use bevy_egui::egui;
use shared::{LevelObject, MaterialAsset, MaterialDesc};
use crate::assets::{EditorAsset, EditorAssetKind, EditorAssets};
use crate::history::set_material_with_history;
use crate::history::set_material_group_with_history;
use crate::ui::inspector::property_row;
pub fn load_material_asset(catalog_path: &str) -> Result<MaterialAsset, String> {
@@ -23,28 +23,21 @@ pub fn apply_material_asset_to_selection(
world: &mut World,
asset: &EditorAsset,
selected: &bevy_inspector_egui::bevy_inspector::hierarchy::SelectedEntities,
) {
let Some(path) = asset.path.clone() else {
return;
};
let desc = match material_desc_from_asset(&path) {
Ok(desc) => desc,
Err(err) => {
world.resource_mut::<crate::scene_io::SceneIo>().status = err;
return;
}
};
for entity in crate::ui::helpers::selected_level_entities(world, selected) {
if world.get::<LevelObject>(entity).is_none() {
continue;
}
if world.get::<MaterialDesc>(entity).is_none() {
world.entity_mut(entity).insert(desc.clone());
}
set_material_with_history(world, entity, desc.clone());
}
) -> Result<(), String> {
let path = asset
.path
.clone()
.ok_or_else(|| format!("Material has no source path: {}", asset.label))?;
let desc = material_desc_from_asset(&path)?;
let changes = crate::ui::helpers::selected_level_entities(world, selected)
.into_iter()
.filter(|entity| world.get::<LevelObject>(*entity).is_some())
.map(|entity| (entity, desc.clone()))
.collect::<Vec<_>>();
set_material_group_with_history(world, changes);
world.resource_mut::<crate::scene_io::SceneIo>().status =
format!("Applied material {}", asset.label);
Ok(())
}
pub fn material_asset_picker_ui(
+22 -2
View File
@@ -1,5 +1,6 @@
//! Asset catalog, database, thumbnails, materials, and prefab overrides.
pub mod animation;
pub mod asset_db;
mod catalog;
mod import;
@@ -11,6 +12,25 @@ pub mod thumbnails;
pub use catalog::*;
pub use thumbnails::{
draw_asset_cell_with, invalidate_on_catalog_refresh, kind_icon, prefetch_folder_thumbnails,
AssetThumbnailCache, ThumbnailCacheSnapshot, ThumbnailState, ThumbnailStudio, ThumbnailsPlugin,
draw_asset_cell_with, gltf_skinned_primitive_labels, invalidate_on_catalog_refresh, kind_icon,
prefetch_folder_thumbnails, AssetThumbnailCache, ThumbnailCacheSnapshot, ThumbnailState,
ThumbnailStudio, ThumbnailsPlugin,
};
/// Refreshes both generated contracts derived from one imported model source.
pub fn refresh_model_artifacts(
record: &mut asset_db::AssetRecord,
) -> Result<static_mesh::StaticMeshManifest, String> {
let static_mesh = static_mesh::refresh_static_mesh_artifact(record);
let animation = animation::refresh_animation_artifact(record);
match (static_mesh, animation) {
(Ok(static_mesh), Ok(_)) => Ok(static_mesh),
(Err(static_error), Ok(_)) => Err(format!("static mesh processor failed: {static_error}")),
(Ok(_), Err(animation_error)) => {
Err(format!("animation processor failed: {animation_error}"))
}
(Err(static_error), Err(animation_error)) => Err(format!(
"static mesh processor failed: {static_error}; animation processor failed: {animation_error}"
)),
}
}
+413 -6
View File
@@ -8,7 +8,11 @@ use crate::ui::helpers::{
apply_material_asset_to_selection, apply_texture_to_selection, selected_level_entities,
};
use super::{spawn_asset_at, spawn_subasset_at, AssetSelection, EditorAsset};
use super::{
animation_clip_authoring_data, animation_skeleton_signature_for_ref, audio_clip_ref_for_asset,
compatible_animation_skeleton_for_model, spawn_asset_at, spawn_subasset_at,
validate_prefab_asset, AssetSelection, EditorAsset,
};
fn selection_availability(world: &World, selected: &SelectedEntities) -> OperatorAvailability {
if selected_level_entities(world, selected).is_empty() {
@@ -26,6 +30,7 @@ pub fn place_asset_operator(world: &mut World, asset: EditorAsset, translation:
&label,
OperatorAvailability::Ready,
move |world| {
validate_prefab_asset(world, &asset)?;
spawn_asset_at(world, &asset, translation)
.map(|_| ())
.ok_or_else(|| format!("Asset cannot be placed: {}", asset.label))
@@ -64,10 +69,7 @@ pub fn apply_texture_operator(
"assets.apply_texture",
&label,
availability,
move |world| {
apply_texture_to_selection(world, &asset, selected);
Ok(())
},
move |world| apply_texture_to_selection(world, &asset, selected),
)
}
@@ -83,9 +85,414 @@ pub fn apply_material_operator(
"assets.apply_material",
&label,
availability,
move |world| apply_material_asset_to_selection(world, &asset, selected),
)
}
pub fn assign_audio_clip_operator(world: &mut World, asset: EditorAsset, entity: Entity) -> bool {
let availability = if world.get::<shared::AudioSourceDesc>(entity).is_some() {
OperatorAvailability::Ready
} else {
OperatorAvailability::Disabled("Select an authored audio source".to_string())
};
let label = format!("Assign Audio Clip {}", asset.label);
run_immediate_operator(
world,
"assets.assign_audio_clip",
&label,
availability,
move |world| {
apply_material_asset_to_selection(world, &asset, selected);
let clip = audio_clip_ref_for_asset(world, &asset)?;
let mut source = world
.get::<shared::AudioSourceDesc>(entity)
.cloned()
.ok_or_else(|| "Selected actor is not an audio source".to_string())?;
source.clip = Some(clip);
crate::history::set_audio_source_with_history(world, entity, source);
Ok(())
},
)
}
pub fn assign_animation_clip_operator(
world: &mut World,
selection: AssetSelection,
entity: Entity,
) -> bool {
let availability = if world.get::<shared::ModelRef>(entity).is_some() {
OperatorAvailability::Ready
} else {
OperatorAvailability::Disabled("Select an authored imported-model actor".to_string())
};
let label = format!("Assign Animation Clip {}", selection.display_label());
run_immediate_operator(
world,
"assets.assign_animation_clip",
&label,
availability,
move |world| {
let authored = animation_clip_authoring_data(world, &selection)?;
let model = world
.get::<shared::ModelRef>(entity)
.cloned()
.ok_or_else(|| "Selected actor has no ModelRef".to_string())?;
let mut controller = world
.get::<shared::AnimationControllerDesc>(entity)
.cloned()
.unwrap_or_default();
let skeleton = match controller.skeleton.as_ref() {
Some(reference) => {
let existing_signature =
animation_skeleton_signature_for_ref(world, reference)?;
if existing_signature != authored.skeleton_signature {
return Err(format!(
"Clip `{}` targets rig `{}` but the actor uses `{}`. Animation v1 requires an exact skeleton match.",
authored.state.label,
authored.skeleton_signature.0,
existing_signature.0
));
}
reference.clone()
}
None => compatible_animation_skeleton_for_model(
world,
&model,
&authored.skeleton_signature,
)?,
};
if controller.states.iter().any(|state| {
state.clip.asset_id == authored.state.clip.asset_id
&& state.clip.sub_asset_id == authored.state.clip.sub_asset_id
}) {
return Err(format!(
"Animation controller already contains clip `{}`.",
authored.state.label
));
}
let mut state = authored.state;
let base_id = state.id.clone();
let mut suffix = 2;
while controller.states.iter().any(|entry| entry.id == state.id) {
state.id = format!("{base_id}_{suffix}");
suffix += 1;
}
controller.skeleton = Some(skeleton);
if controller.default_state.trim().is_empty() {
controller.default_state = state.id.clone();
}
controller.states.push(state);
crate::history::set_animation_controller_with_history(world, entity, controller);
Ok(())
},
)
}
#[cfg(test)]
mod tests {
use super::*;
use shared::{
animation_clip_sub_asset_id, animation_skeleton_sub_asset_id, ActorKind,
AnimationClipRecord, AnimationControllerDesc, AnimationManifest, AnimationManifestSource,
AnimationSkeletonRecord, AnimationSkeletonSignature, AnimationSourceFingerprint,
AudioSourceDesc, LevelObject, MaterialDesc, ModelRef, PrimitiveShape,
ANIMATION_MANIFEST_SCHEMA_VERSION,
};
use crate::asset_db::{AssetId, AssetRecord, AssetRegistry, ImportSettings};
use crate::history::EditorHistory;
use crate::operators::test_harness::{assert_undo_redo_round_trip, OperatorInvariantHarness};
use crate::operators::ActiveOperator;
use crate::scene_io::SceneIo;
use crate::selection::SelectedEntity;
fn authored_count(world: &mut World) -> usize {
let mut query = world.query_filtered::<Entity, With<LevelObject>>();
query.iter(world).count()
}
fn animation_fixture() -> (std::path::PathBuf, AssetRecord, AssetSelection) {
let model_path = "assets/models/operator_fixture.glb".to_string();
let asset_id = AssetId::new();
let skeleton_id = animation_skeleton_sub_asset_id(0, "Rig");
let clip_id = animation_clip_sub_asset_id(0, "Idle");
let manifest = AnimationManifest {
schema_version: ANIMATION_MANIFEST_SCHEMA_VERSION,
asset_id: asset_id.as_string(),
label: "Operator Fixture".into(),
source: AnimationManifestSource {
path: model_path.clone(),
format: "glb".into(),
fingerprint: AnimationSourceFingerprint {
byte_len: 1,
modified_unix_secs: 0,
content_hash: "fixture".into(),
},
dependencies: Vec::new(),
},
runtime_supported: true,
skeletons: vec![AnimationSkeletonRecord {
id: skeleton_id,
label: "Rig".into(),
source_index: 0,
signature: AnimationSkeletonSignature::new("exact-rig"),
joint_paths: vec!["Root".into()],
}],
clips: vec![AnimationClipRecord {
id: clip_id.clone(),
label: "Idle".into(),
source_index: 0,
duration_seconds: 1.0,
target_skeleton_signature: Some(AnimationSkeletonSignature::new("exact-rig")),
events: Vec::new(),
}],
diagnostics: Vec::new(),
};
let path = std::env::temp_dir().join(format!(
"blacksite-animation-operator-{}.animation.ron",
uuid::Uuid::new_v4()
));
std::fs::write(
&path,
ron::ser::to_string_pretty(&manifest, ron::ser::PrettyConfig::default()).unwrap(),
)
.unwrap();
let record = AssetRecord {
id: asset_id,
path: model_path.clone(),
label: "Operator Fixture".into(),
kind_tag: "Model".into(),
import_settings: ImportSettings {
animation_manifest_path: Some(path.to_string_lossy().into_owned()),
..Default::default()
},
dependencies: Vec::new(),
};
let selection = AssetSelection::SubAsset {
parent_path: model_path.clone(),
sub_asset_id: clip_id,
label: "Idle".into(),
kind: super::super::AssetSubAssetKind::AnimationClip,
source_path: Some(model_path),
};
(path, record, selection)
}
#[test]
fn asset_placement_commits_one_undo_group_and_round_trips() {
let mut world = World::new();
world.init_resource::<ActiveOperator>();
world.init_resource::<EditorHistory>();
world.init_resource::<SceneIo>();
world.init_resource::<SelectedEntity>();
let harness = OperatorInvariantHarness::capture(&mut world);
let asset = EditorAsset {
label: "Cube".to_string(),
path: None,
folder_path: "Built-ins".to_string(),
kind: super::super::EditorAssetKind::Primitive(PrimitiveShape::Box),
};
assert!(place_asset_operator(&mut world, asset, Vec3::ZERO));
harness.assert_committed(&mut world, 1, 1);
assert_undo_redo_round_trip(&mut world, 0, 1, authored_count);
}
#[test]
fn audio_clip_assignment_is_one_undoable_operator() {
let mut world = World::new();
world.init_resource::<ActiveOperator>();
world.init_resource::<EditorHistory>();
world.init_resource::<SceneIo>();
let path = "assets/audio/impact.ogg".to_string();
world.insert_resource(AssetRegistry {
records: vec![AssetRecord {
id: AssetId::new(),
path: path.clone(),
label: "Impact".into(),
kind_tag: "AudioClip".into(),
import_settings: Default::default(),
dependencies: Vec::new(),
}],
index_dirty: false,
});
let entity = world
.spawn((
LevelObject,
ActorKind::AudioSource,
Transform::IDENTITY,
AudioSourceDesc::default(),
))
.id();
let asset = EditorAsset {
label: "Impact".into(),
path: Some(path.clone()),
folder_path: "assets/audio".into(),
kind: super::super::EditorAssetKind::AudioClip,
};
let harness = OperatorInvariantHarness::capture(&mut world);
let read_clip = move |world: &mut World| {
world
.get::<AudioSourceDesc>(entity)
.and_then(|source| source.clip.clone())
};
assert!(assign_audio_clip_operator(&mut world, asset, entity));
let assigned = read_clip(&mut world).expect("clip assigned");
assert_eq!(assigned.source_path.as_deref(), Some(path.as_str()));
harness.assert_committed(&mut world, 1, 0);
assert_undo_redo_round_trip(&mut world, None, Some(assigned), read_clip);
}
#[test]
fn animation_clip_assignment_is_one_undoable_operator() {
let mut world = World::new();
world.init_resource::<ActiveOperator>();
world.init_resource::<EditorHistory>();
world.init_resource::<SceneIo>();
let (manifest_path, record, selection) = animation_fixture();
let model_path = record.path.clone();
world.insert_resource(AssetRegistry {
records: vec![record],
index_dirty: false,
});
let entity = world
.spawn((
LevelObject,
ActorKind::ImportedModel,
ModelRef::new(model_path),
))
.id();
let harness = OperatorInvariantHarness::capture(&mut world);
let read_controller =
move |world: &mut World| world.get::<AnimationControllerDesc>(entity).cloned();
assert!(assign_animation_clip_operator(
&mut world, selection, entity
));
let assigned = read_controller(&mut world).expect("controller assigned");
assert_eq!(assigned.default_state, "idle");
assert_eq!(assigned.states.len(), 1);
assert_eq!(assigned.states[0].id, "idle");
assert_eq!(
assigned.skeleton.as_ref().unwrap().sub_asset_id,
animation_skeleton_sub_asset_id(0, "Rig")
);
harness.assert_committed(&mut world, 1, 0);
assert_undo_redo_round_trip(&mut world, None, Some(assigned), read_controller);
let _ = std::fs::remove_file(manifest_path);
}
#[test]
fn multi_actor_texture_assignment_is_one_undo_group() {
let mut world = World::new();
world.init_resource::<ActiveOperator>();
world.init_resource::<EditorHistory>();
world.init_resource::<SceneIo>();
let first = world.spawn((LevelObject, MaterialDesc::default())).id();
let second = world.spawn((LevelObject, MaterialDesc::default())).id();
let mut selected = SelectedEntities::default();
selected.select_replace(first);
selected.select_maybe_add(second, true);
let asset = EditorAsset {
label: "Grid".to_string(),
path: Some("assets/textures/grid.png".to_string()),
folder_path: "assets/textures".to_string(),
kind: super::super::EditorAssetKind::Texture,
};
let harness = OperatorInvariantHarness::capture(&mut world);
let read_textures = move |world: &mut World| {
[first, second]
.into_iter()
.map(|entity| {
world
.get::<MaterialDesc>(entity)
.and_then(|material| material.base_color_texture.clone())
})
.collect::<Vec<_>>()
};
assert!(apply_texture_operator(&mut world, asset, &selected));
harness.assert_committed(&mut world, 1, 0);
assert_undo_redo_round_trip(
&mut world,
vec![None, None],
vec![
Some("assets/textures/grid.png".to_string()),
Some("assets/textures/grid.png".to_string()),
],
read_textures,
);
}
#[test]
fn missing_subasset_commit_cancels_without_side_effects() {
let mut world = World::new();
world.init_resource::<ActiveOperator>();
world.init_resource::<EditorHistory>();
world.init_resource::<SceneIo>();
let harness = OperatorInvariantHarness::capture(&mut world);
let selection = AssetSelection::SubAsset {
parent_path: "assets/models/missing.glb".to_string(),
sub_asset_id: "mesh:missing".to_string(),
label: "Missing Mesh".to_string(),
kind: super::super::AssetSubAssetKind::Mesh,
source_path: None,
};
assert!(!place_subasset_operator(&mut world, selection, Vec3::ZERO));
harness.assert_canceled(&mut world);
}
#[test]
fn missing_material_source_cancels_without_side_effects() {
let mut world = World::new();
world.init_resource::<ActiveOperator>();
world.init_resource::<EditorHistory>();
world.init_resource::<SceneIo>();
let entity = world.spawn(LevelObject).id();
let mut selected = SelectedEntities::default();
selected.select_replace(entity);
let harness = OperatorInvariantHarness::capture(&mut world);
let asset = EditorAsset {
label: "Missing Material".to_string(),
path: Some("assets/materials/does-not-exist.material.ron".to_string()),
folder_path: "assets/materials".to_string(),
kind: super::super::EditorAssetKind::Material,
};
assert!(!apply_material_operator(&mut world, asset, &selected));
harness.assert_canceled(&mut world);
}
#[test]
fn texture_assignment_without_authored_selection_is_blocked() {
let mut world = World::new();
world.init_resource::<ActiveOperator>();
world.init_resource::<EditorHistory>();
world.init_resource::<SceneIo>();
let harness = OperatorInvariantHarness::capture(&mut world);
let asset = EditorAsset {
label: "Grid".to_string(),
path: Some("assets/textures/grid.png".to_string()),
folder_path: "assets/textures".to_string(),
kind: super::super::EditorAssetKind::Texture,
};
assert!(!apply_texture_operator(
&mut world,
asset,
&SelectedEntities::default()
));
harness.assert_blocked(&mut world);
}
}
File diff suppressed because it is too large. Load diff
+8 -4
View File
@@ -120,6 +120,7 @@ impl AssetThumbnailCache {
model_path: String,
mesh_label: String,
material_label: Option<String>,
requires_scene_instance: bool,
studio: &mut ThumbnailStudio,
) {
if matches!(
@@ -132,14 +133,16 @@ impl AssetThumbnailCache {
if !self.model_source_ready(&key, &model_path) {
return;
}
if studio.enqueue_source(
key.clone(),
let source = if requires_scene_instance {
ThumbnailJobSource::Model { model_path }
} else {
ThumbnailJobSource::MeshSubAsset {
model_path,
mesh_label,
material_label,
},
) {
}
};
if studio.enqueue_source(key.clone(), source) {
self.studio_pending.insert(key);
}
}
@@ -292,6 +295,7 @@ pub fn kind_icon(kind: &EditorAssetKind) -> egui_phosphor_icons::Icon {
EditorAssetKind::Model => icons::CUBE_TRANSPARENT,
EditorAssetKind::Texture => icons::IMAGE,
EditorAssetKind::Material => icons::PAINT_BRUSH,
EditorAssetKind::AudioClip => icons::WAVEFORM,
EditorAssetKind::Level => icons::MAP_TRIFOLD,
EditorAssetKind::Prefab => icons::PACKAGE,
EditorAssetKind::PostProcessVolume => icons::CAMERA,
+3 -1
View File
@@ -12,7 +12,9 @@ pub use cache::{
AssetThumbnailCache, AssetThumbnailsPlugin, ThumbnailCacheSnapshot, ThumbnailState,
};
pub use job::{ThumbnailJob, ThumbnailJobSource};
pub use sources::{FbxThumbnailSource, GltfThumbnailSource, ThumbnailModelSource};
pub use sources::{
gltf_skinned_primitive_labels, FbxThumbnailSource, GltfThumbnailSource, ThumbnailModelSource,
};
pub use studio::{
model_file_exists, model_scene_asset_path, ThumbnailStudio, ThumbnailStudioPlugin,
};
@@ -1,5 +1,6 @@
//! glTF/GLB fast-path texture extraction for asset browser thumbnails.
use std::collections::HashSet;
use std::path::Path;
/// Returns an asset-server path for the first base-color texture referenced by a glTF/GLB file.
@@ -64,6 +65,32 @@ pub fn validate_gltf_dependencies(model_asset_path: &str) -> Result<(), String>
Ok(())
}
/// Returns primitive labels that cannot be rendered without their source skin hierarchy.
pub fn gltf_skinned_primitive_labels(model_asset_path: &str) -> HashSet<String> {
let model_path = Path::new(model_asset_path);
if !is_gltf_path(model_path) {
return HashSet::new();
}
let Ok(gltf) = gltf::Gltf::open(model_path) else {
return HashSet::new();
};
gltf.meshes()
.flat_map(|mesh| {
let mesh_index = mesh.index();
mesh.primitives()
.filter(|primitive| {
primitive.attributes().any(|(semantic, _)| {
matches!(
semantic,
gltf::Semantic::Joints(_) | gltf::Semantic::Weights(_)
)
})
})
.map(move |primitive| format!("Mesh{mesh_index}/Primitive{}", primitive.index()))
})
.collect()
}
pub struct GltfThumbnailSource;
fn is_gltf_path(path: &Path) -> bool {
@@ -137,4 +164,16 @@ mod tests {
fs::remove_dir_all(directory).unwrap();
}
#[test]
fn committed_robot_fixture_identifies_skinned_primitives() {
let path =
Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/models/robot_expressive.glb");
let labels = gltf_skinned_primitive_labels(path.to_str().unwrap());
assert!(labels.contains("Mesh12/Primitive0"));
assert!(labels.contains("Mesh13/Primitive0"));
assert!(!labels.contains("Mesh0/Primitive0"));
assert!(!labels.contains("Mesh999/Primitive0"));
}
}
@@ -4,7 +4,7 @@ mod fbx;
pub(crate) mod gltf;
pub use fbx::FbxThumbnailSource;
pub use gltf::GltfThumbnailSource;
pub use gltf::{gltf_skinned_primitive_labels, GltfThumbnailSource};
use bevy::prelude::*;
@@ -11,7 +11,7 @@ use bevy::mesh::VertexAttributeValues;
use bevy::prelude::*;
use bevy::render::render_resource::TextureFormat;
use bevy_egui::EguiUserTextures;
use shared::{material_from_desc, ModelRef};
use shared::{material_from_desc, standard_material_asset_path, ModelRef};
use super::cache::AssetThumbnailCache;
use super::job::{ThumbnailJob, ThumbnailJobSource};
@@ -413,7 +413,7 @@ fn spawn_thumbnail_job_content(
commands,
mesh_storage,
root,
asset_server.load(labeled_asset_path(
asset_server.load(standard_material_asset_path(
&asset_server_path(model_path),
material_label,
)),
@@ -437,7 +437,7 @@ fn spawn_mesh_subasset_preview(
let source_path = asset_server_path(model_path);
let mesh: Handle<Mesh> = asset_server.load(labeled_asset_path(&source_path, mesh_label));
let material = if let Some(material_label) = material_label {
asset_server.load(labeled_asset_path(&source_path, material_label))
asset_server.load(standard_material_asset_path(&source_path, material_label))
} else {
materials.add(StandardMaterial {
base_color: Color::srgb(0.72, 0.72, 0.75),