Initial project import
CI / Format, lint, test, build (push) Waiting to run

This commit is contained in:
Rbanh committed 2026-06-05 21:44:45 -04:00
commit f29712d158
259 files changed
+52069

No files matched your search

+257
View File
@@ -0,0 +1,257 @@
//! Project asset registry (stable IDs + import metadata). Phase 5 foundation.
use bevy::prelude::*;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use uuid::Uuid;
/// Stable asset identity for dependency tracking and prefab references.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub struct AssetId(pub Uuid);
impl AssetId {
pub fn new() -> Self {
Self(Uuid::new_v4())
}
pub fn as_string(&self) -> String {
self.0.to_string()
}
}
impl Default for AssetId {
fn default() -> Self {
Self::new()
}
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub enum ModelPlacementMode {
StaticAsset,
SceneInstance,
}
impl Default for ModelPlacementMode {
fn default() -> Self {
Self::StaticAsset
}
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub enum ModelHierarchyMode {
SingleActor,
SourceHierarchy,
}
impl Default for ModelHierarchyMode {
fn default() -> Self {
Self::SingleActor
}
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub enum MaterialImportPolicy {
SourceMaterials,
AuthoringOverride,
}
impl Default for MaterialImportPolicy {
fn default() -> Self {
Self::SourceMaterials
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ImportSettings {
pub scale: f32,
pub generate_collider: bool,
pub lod0_only: bool,
#[serde(default)]
pub placement_mode: ModelPlacementMode,
#[serde(default)]
pub hierarchy_mode: ModelHierarchyMode,
#[serde(default)]
pub material_policy: MaterialImportPolicy,
#[serde(default)]
pub static_mesh_manifest_path: Option<String>,
}
impl Default for ImportSettings {
fn default() -> Self {
Self {
scale: 1.0,
generate_collider: true,
lod0_only: true,
placement_mode: ModelPlacementMode::default(),
hierarchy_mode: ModelHierarchyMode::default(),
material_policy: MaterialImportPolicy::default(),
static_mesh_manifest_path: None,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct AssetRecord {
pub id: AssetId,
pub path: String,
pub label: String,
pub kind_tag: String,
#[serde(default)]
pub import_settings: ImportSettings,
#[serde(default)]
pub dependencies: Vec<String>,
}
#[derive(Resource, Debug, Default)]
pub struct AssetRegistry {
pub records: Vec<AssetRecord>,
pub index_dirty: bool,
}
pub struct AssetDbPlugin;
impl Plugin for AssetDbPlugin {
fn build(&self, app: &mut App) {
app.insert_resource(load_registry())
.add_systems(Update, sync_registry_from_browser);
}
}
fn sync_registry_from_browser(
assets: Res<crate::assets::EditorAssets>,
mut registry: ResMut<AssetRegistry>,
) {
if !assets.is_changed() {
return;
}
let mut existing: HashMap<String, AssetRecord> = registry
.records
.drain(..)
.map(|record| (record.path.clone(), record))
.collect();
let mut next_records = Vec::new();
let mut seen_paths = HashMap::new();
for asset in &assets.assets {
let Some(path) = asset.path.clone() else {
continue;
};
if path.is_empty() || seen_paths.contains_key(&path) {
continue;
}
seen_paths.insert(path.clone(), ());
let kind_tag = format!("{:?}", asset.kind);
let mut record = if let Some(mut prior) = existing.remove(&path) {
prior.label = asset.label.clone();
prior.kind_tag = kind_tag;
prior
} else {
AssetRecord {
id: AssetId::new(),
path: path.clone(),
label: asset.label.clone(),
kind_tag,
import_settings: ImportSettings::default(),
dependencies: Vec::new(),
}
};
if record.kind_tag == "Model" {
if let Err(error) = super::static_mesh::refresh_static_mesh_artifact(&mut record) {
warn!(
"Static mesh processor failed for {} (asset id {}): {error}",
record.path,
record.id.as_string()
);
}
}
next_records.push(record);
}
let changed = registry.records != next_records;
registry.records = next_records;
if changed {
registry.index_dirty = true;
}
if registry.index_dirty {
if let Err(error) = save_registry(&registry) {
warn!("Asset registry save failed: {error}");
} else {
registry.index_dirty = false;
}
}
}
pub fn find_asset_by_path(registry: &AssetRegistry, path: &str) -> Option<AssetRecord> {
registry
.records
.iter()
.find(|record| record.path == path)
.cloned()
}
pub fn find_asset_by_id(registry: &AssetRegistry, id: &str) -> Option<AssetRecord> {
registry
.records
.iter()
.find(|record| record.id.as_string() == id)
.cloned()
}
pub fn find_asset_mut_by_path<'a>(
registry: &'a mut AssetRegistry,
path: &str,
) -> Option<&'a mut AssetRecord> {
registry
.records
.iter_mut()
.find(|record| record.path == path)
}
pub fn update_import_settings(
registry: &mut AssetRegistry,
path: &str,
settings: ImportSettings,
) -> bool {
let Some(record) = registry
.records
.iter_mut()
.find(|record| record.path == path)
else {
return false;
};
record.import_settings = settings;
registry.index_dirty = true;
true
}
pub fn registry_index_path() -> &'static str {
"assets/.index/registry.ron"
}
pub fn save_registry(registry: &AssetRegistry) -> Result<(), String> {
let path = registry_index_path();
if let Some(parent) = std::path::Path::new(path).parent() {
std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
}
let text = ron::ser::to_string_pretty(&registry.records, ron::ser::PrettyConfig::default())
.map_err(|e| e.to_string())?;
std::fs::write(path, text).map_err(|e| e.to_string())
}
pub fn load_registry() -> AssetRegistry {
let path = registry_index_path();
match std::fs::read_to_string(path) {
Ok(text) => {
let records: Vec<AssetRecord> = ron::from_str(&text).unwrap_or_default();
AssetRegistry {
records,
index_dirty: false,
}
}
Err(_) => AssetRegistry::default(),
}
}
+711
View File
@@ -0,0 +1,711 @@
use std::fs;
use std::path::{Path, PathBuf};
use bevy::prelude::*;
use settings::ProjectSettings;
use shared::{
ActorKind, AuthoringLightKind, ColliderDesc, ColorDesc, EditorVisibility, LightDesc,
MaterialDesc, ModelRef, PostProcessVolumeDesc, PrefabInstance, PrefabRef, Primitive,
PrimitiveShape, RigidBodyDesc,
};
use walkdir::WalkDir;
use crate::asset_db::{
find_asset_by_path, find_asset_mut_by_path, AssetRegistry, ModelPlacementMode,
};
use crate::assets::static_mesh::{
load_static_mesh_manifest, refresh_static_mesh_artifact, renderer_from_manifest,
};
use crate::history::{spawn_with_history, EditorEntitySnapshot};
pub const BUILTINS_FOLDER: &str = "__builtins__";
pub const ASSETS_ROOT: &str = "assets";
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum AssetSelection {
Builtin(String),
File(String),
}
impl AssetSelection {
pub fn from_asset(asset: &EditorAsset) -> Self {
match &asset.path {
Some(path) => AssetSelection::File(path.clone()),
None => AssetSelection::Builtin(asset.label.clone()),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EditorAssetKind {
Primitive(PrimitiveShape),
Light(AuthoringLightKind),
Model,
Texture,
Material,
Level,
Prefab,
PostProcessVolume,
PostProcessEffect,
RenderingProfile,
ShaderSchema,
}
#[derive(Debug, Clone)]
pub struct EditorAsset {
pub label: String,
pub path: Option<String>,
pub folder_path: String,
pub kind: EditorAssetKind,
}
#[derive(Debug, Clone)]
pub struct AssetFolder {
pub path: String,
pub name: String,
pub parent: Option<String>,
}
#[derive(Resource, Debug)]
pub struct EditorAssets {
pub folders: Vec<AssetFolder>,
pub assets: Vec<EditorAsset>,
pub current_folder: String,
pub selected: Option<AssetSelection>,
pub dragging: Option<AssetSelection>,
pub status: String,
}
impl Default for EditorAssets {
fn default() -> Self {
let mut assets = Self {
folders: Vec::new(),
assets: Vec::new(),
current_folder: ASSETS_ROOT.to_string(),
selected: None,
dragging: None,
status: "Assets not scanned yet".to_string(),
};
assets.refresh();
assets
}
}
impl EditorAssets {
pub fn refresh(&mut self) {
self.folders.clear();
self.assets.clear();
self.folders.push(AssetFolder {
path: BUILTINS_FOLDER.to_string(),
name: "Built-ins".to_string(),
parent: None,
});
register_folder_tree(&mut self.folders, ASSETS_ROOT);
self.assets.extend(builtin_assets());
scan_assets_directory(&mut self.assets);
if !self.folder_exists(&self.current_folder) {
self.current_folder = ASSETS_ROOT.to_string();
}
self.selected = self
.selected
.take()
.filter(|selection| self.asset_for_selection(selection).is_some());
let folder_count = self.folders.len();
self.status = format!(
"Scanned {} assets in {} folders",
self.assets.len(),
folder_count
);
}
fn folder_exists(&self, path: &str) -> bool {
self.folders.iter().any(|folder| folder.path == path)
}
pub fn asset_for_selection(&self, selection: &AssetSelection) -> Option<&EditorAsset> {
match selection {
AssetSelection::Builtin(label) => self
.assets
.iter()
.find(|asset| asset.path.is_none() && asset.label == *label),
AssetSelection::File(path) => self
.assets
.iter()
.find(|asset| asset.path.as_deref() == Some(path.as_str())),
}
}
pub fn selected_asset(&self) -> Option<&EditorAsset> {
self.selected
.as_ref()
.and_then(|selection| self.asset_for_selection(selection))
}
pub fn dragging_asset(&self) -> Option<&EditorAsset> {
self.dragging
.as_ref()
.and_then(|selection| self.asset_for_selection(selection))
}
pub fn select(&mut self, selection: AssetSelection) {
if let Some(asset) = self.asset_for_selection(&selection).cloned() {
self.selected = Some(selection);
self.status = format!("Selected {}", asset.label);
}
}
pub fn start_drag(&mut self, selection: AssetSelection) {
if self.asset_for_selection(&selection).is_some() {
self.dragging = Some(selection);
}
}
pub fn clear_drag(&mut self) {
self.dragging = None;
}
}
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);
}
}
fn refresh_assets_on_settings_change(
settings: Res<settings::ProjectSettings>,
mut assets: ResMut<EditorAssets>,
) {
if settings.is_changed() {
assets.refresh();
}
}
fn builtin_assets() -> Vec<EditorAsset> {
vec![
EditorAsset {
label: "Cube".to_string(),
path: None,
folder_path: BUILTINS_FOLDER.to_string(),
kind: EditorAssetKind::Primitive(PrimitiveShape::Box),
},
EditorAsset {
label: "Sphere".to_string(),
path: None,
folder_path: BUILTINS_FOLDER.to_string(),
kind: EditorAssetKind::Primitive(PrimitiveShape::Sphere),
},
EditorAsset {
label: "Ramp".to_string(),
path: None,
folder_path: BUILTINS_FOLDER.to_string(),
kind: EditorAssetKind::Primitive(PrimitiveShape::Ramp),
},
EditorAsset {
label: "Point Light".to_string(),
path: None,
folder_path: BUILTINS_FOLDER.to_string(),
kind: EditorAssetKind::Light(AuthoringLightKind::Point),
},
EditorAsset {
label: "Spot Light".to_string(),
path: None,
folder_path: BUILTINS_FOLDER.to_string(),
kind: EditorAssetKind::Light(AuthoringLightKind::Spot),
},
EditorAsset {
label: "Directional Light".to_string(),
path: None,
folder_path: BUILTINS_FOLDER.to_string(),
kind: EditorAssetKind::Light(AuthoringLightKind::Directional),
},
EditorAsset {
label: "Post Process Volume".to_string(),
path: None,
folder_path: BUILTINS_FOLDER.to_string(),
kind: EditorAssetKind::PostProcessVolume,
},
]
}
fn register_folder_tree(folders: &mut Vec<AssetFolder>, root: &str) {
let normalized = normalize_path(root);
if folders.iter().any(|folder| folder.path == normalized) {
return;
}
let parent = parent_folder_path(&normalized);
if let Some(ref parent_path) = parent {
if !folders.iter().any(|folder| folder.path == *parent_path) {
register_folder_tree(folders, parent_path);
}
}
folders.push(AssetFolder {
name: folder_name(&normalized),
path: normalized.clone(),
parent,
});
if Path::new(&normalized).is_dir() {
let Ok(read_dir) = fs::read_dir(&normalized) else {
return;
};
for entry in read_dir.flatten() {
if entry.path().is_dir() {
register_folder_tree(folders, &entry.path().to_string_lossy());
}
}
}
}
fn scan_assets_directory(assets: &mut Vec<EditorAsset>) {
let root_path = Path::new(ASSETS_ROOT);
if !root_path.exists() {
return;
}
for entry in WalkDir::new(root_path)
.follow_links(false)
.into_iter()
.filter_map(Result::ok)
{
if !entry.file_type().is_file() {
continue;
}
let path = entry.path();
if should_skip_asset_path(path) {
continue;
}
if let Some(asset) = asset_from_file_path(path) {
assets.push(asset);
}
}
}
fn should_skip_asset_path(path: &Path) -> bool {
if path
.file_name()
.and_then(|name| name.to_str())
.is_some_and(|name| name.starts_with('.'))
{
return true;
}
let normalized = normalize_asset_path(path);
normalized == "assets/project.ron"
|| normalized.starts_with("assets/.index/")
|| normalized.starts_with(crate::assets::static_mesh::STATIC_MESH_ARTIFACT_DIR)
}
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"],
)
}
}
_ => return None,
};
if !has_extension(path, &extensions) {
return None;
}
let path_string = normalize_asset_path(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()
};
Some(EditorAsset {
label,
path: Some(path_string),
folder_path,
kind,
})
}
fn normalize_path(path: &str) -> String {
path.replace('\\', "/").trim_end_matches('/').to_string()
}
fn normalize_asset_path(path: &Path) -> String {
let raw = path.to_string_lossy().replace('\\', "/");
raw.strip_prefix("assets/")
.or_else(|| raw.strip_prefix("./assets/"))
.map(|rest| format!("assets/{rest}"))
.unwrap_or(raw)
}
/// Path relative to Bevy's `assets/` folder for [`AssetServer::load`].
pub fn asset_server_path(catalog_path: &str) -> String {
shared::asset_server_path(catalog_path)
}
fn parent_folder_path(path: &str) -> Option<String> {
let normalized = normalize_path(path);
normalized
.rfind('/')
.map(|index| normalized[..index].to_string())
}
fn folder_name(path: &str) -> String {
Path::new(path)
.file_name()
.and_then(|name| name.to_str())
.unwrap_or(path)
.to_string()
}
fn has_extension(path: &Path, extensions: &[&str]) -> bool {
path.extension()
.and_then(|ext| ext.to_str())
.is_some_and(|ext| {
extensions
.iter()
.any(|candidate| ext.eq_ignore_ascii_case(candidate))
})
}
pub fn snapshot_for_asset(asset: &EditorAsset, translation: Vec3) -> Option<EditorEntitySnapshot> {
let mut snapshot = EditorEntitySnapshot {
actor_id: None,
actor_kind: ActorKind::Empty,
actor_name: None,
name: Some(asset.label.clone()),
transform: Transform::from_translation(translation),
primitive: None,
static_mesh_renderer: None,
material: None,
material_override: None,
rigid_body: None,
collider: None,
physics: None,
light: None,
player_spawn: false,
model: None,
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(),
};
match &asset.kind {
EditorAssetKind::Primitive(shape) => {
snapshot.actor_kind = ActorKind::StaticMesh;
let size = match shape {
PrimitiveShape::Box => Vec3::ONE,
PrimitiveShape::Sphere => Vec3::splat(1.5),
PrimitiveShape::Ramp => Vec3::new(4.0, 0.4, 5.0),
};
snapshot.primitive = Some(match shape {
PrimitiveShape::Box => Primitive::cuboid(size),
PrimitiveShape::Sphere => Primitive::sphere(size.x * 0.5),
PrimitiveShape::Ramp => Primitive::ramp(size),
});
snapshot.material = Some(default_material_for(shape));
snapshot.rigid_body = Some(RigidBodyDesc::default());
snapshot.collider = Some(match shape {
PrimitiveShape::Sphere => ColliderDesc::static_sphere(size.x * 0.5),
_ => ColliderDesc::static_cuboid(size),
});
if matches!(shape, PrimitiveShape::Ramp) {
snapshot.transform.rotation = Quat::from_rotation_x(-std::f32::consts::PI / 9.0);
snapshot.transform.translation.y += 1.0;
} else {
snapshot.transform.translation.y += size.y * 0.5;
}
}
EditorAssetKind::Light(kind) => {
snapshot.actor_kind = ActorKind::Light;
snapshot.light = Some(LightDesc::for_kind(*kind));
snapshot.transform.translation.y += 3.0;
}
EditorAssetKind::PostProcessVolume => {
snapshot.actor_kind = ActorKind::PostProcessVolume;
snapshot.post_process_volume = Some(PostProcessVolumeDesc {
half_extents: Vec3::new(4.0, 2.0, 4.0),
..Default::default()
});
snapshot.transform.translation.y += 2.0;
}
EditorAssetKind::Model => {
snapshot.actor_kind = ActorKind::ImportedModel;
let path = asset.path.as_ref()?;
snapshot.model = Some(ModelRef::new(path.clone()));
snapshot.transform.translation.y += 0.1;
}
EditorAssetKind::Prefab | EditorAssetKind::Level => {
snapshot.actor_kind = ActorKind::PrefabAnchor;
let path = asset.path.as_ref()?;
snapshot.prefab = Some(PrefabRef::new(path.clone()));
}
EditorAssetKind::Texture
| EditorAssetKind::Material
| EditorAssetKind::PostProcessEffect
| EditorAssetKind::RenderingProfile
| EditorAssetKind::ShaderSchema => return None,
}
Some(snapshot)
}
pub fn spawn_asset_at(world: &mut World, asset: &EditorAsset, translation: Vec3) -> Option<Entity> {
let mut snapshot = snapshot_for_asset(asset, translation)?;
if let Some(light) = snapshot.light.as_mut() {
if matches!(light.kind, AuthoringLightKind::Directional) {
light.intensity = world
.resource::<ProjectSettings>()
.rendering
.sun_illuminance;
}
}
if let Some(path) = asset.path.as_ref() {
let record = world
.get_resource::<AssetRegistry>()
.and_then(|registry| find_asset_by_path(registry, path));
if let Some(record) = record {
match asset.kind {
EditorAssetKind::Model => {
snapshot.transform.scale *= record.import_settings.scale;
if matches!(
record.import_settings.placement_mode,
ModelPlacementMode::StaticAsset
) {
if let Some(renderer) = static_mesh_renderer_for_asset(world, path) {
let collider = record
.import_settings
.generate_collider
.then(|| static_mesh_collider_for_renderer(&renderer));
apply_static_mesh_placement_mode(
&mut snapshot,
renderer,
collider,
record.import_settings.hierarchy_mode,
);
} else {
warn!(
"Static mesh placement fell back to SceneRoot for {} because no renderer manifest was available",
path
);
}
}
}
EditorAssetKind::Prefab => {
snapshot.prefab_instance =
Some(PrefabInstance::new(record.id.as_string(), path.clone()));
}
_ => {}
}
}
}
Some(spawn_with_history(world, snapshot))
}
fn apply_static_mesh_placement_mode(
snapshot: &mut EditorEntitySnapshot,
renderer: shared::StaticMeshRenderer,
collider: Option<ColliderDesc>,
hierarchy_mode: crate::asset_db::ModelHierarchyMode,
) {
snapshot.model = None;
match hierarchy_mode {
crate::asset_db::ModelHierarchyMode::SingleActor => {
snapshot.actor_kind = ActorKind::StaticMesh;
snapshot.static_mesh_renderer = Some(renderer);
if let Some(collider) = collider {
snapshot.rigid_body = Some(RigidBodyDesc::default());
snapshot.collider = Some(collider);
}
}
crate::asset_db::ModelHierarchyMode::SourceHierarchy => {
snapshot.actor_kind = ActorKind::Empty;
snapshot.static_mesh_renderer = None;
snapshot.children = renderer
.slots
.into_iter()
.enumerate()
.map(|(index, mut entry)| {
let transform = entry.local_transform;
let collider = collider
.as_ref()
.map(|_| ColliderDesc::static_mesh(vec![entry.mesh.clone()]));
entry.local_transform = Transform::default();
EditorEntitySnapshot {
actor_id: None,
actor_kind: ActorKind::StaticMesh,
actor_name: None,
name: Some(if entry.name.trim().is_empty() {
format!("Mesh Part {index}")
} else {
entry.name.clone()
}),
transform,
primitive: None,
static_mesh_renderer: Some(shared::StaticMeshRenderer::single(entry)),
material: None,
material_override: None,
rigid_body: collider.as_ref().map(|_| RigidBodyDesc::default()),
collider,
physics: None,
light: None,
player_spawn: false,
model: None,
prefab: None,
prefab_instance: None,
weapon_spawn: None,
trigger_volume: None,
post_process_volume: None,
team_spawn: None,
objective: None,
hierarchy_sibling_index: index as i32,
editor_visibility: EditorVisibility::default(),
children: Vec::new(),
}
})
.collect();
}
}
}
fn static_mesh_collider_for_renderer(renderer: &shared::StaticMeshRenderer) -> ColliderDesc {
ColliderDesc::static_mesh(
renderer
.slots
.iter()
.map(|slot| slot.mesh.clone())
.collect(),
)
}
fn static_mesh_renderer_for_asset(
world: &mut World,
path: &str,
) -> Option<shared::StaticMeshRenderer> {
let mut manifest_path = None;
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) {
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}");
manifest_path = record.import_settings.static_mesh_manifest_path.clone();
}
}
}
if renderer.is_some() {
if let Err(error) = crate::asset_db::save_registry(&registry) {
warn!("Asset registry save failed after static mesh refresh: {error}");
} else {
registry.index_dirty = false;
}
return renderer;
}
}
let manifest_path = manifest_path?;
let registry = world.get_resource::<AssetRegistry>()?;
let record = find_asset_by_path(registry, path)?;
let manifest = load_static_mesh_manifest(&manifest_path).ok()?;
Some(renderer_from_manifest(&manifest, &record.import_settings))
}
pub fn import_external_assets(paths: &[PathBuf]) -> Result<usize, String> {
let mut copied = 0;
for source in paths {
let Some(file_name) = source.file_name() else {
continue;
};
let Some(extension) = source.extension().and_then(|ext| ext.to_str()) else {
continue;
};
let dest_dir = import_dir_for_extension(extension);
if extension.eq_ignore_ascii_case("fbx") {
super::import::copy_fbx_with_sidecar(source, Path::new(dest_dir))?;
copied += 1;
continue;
}
fs::create_dir_all(dest_dir)
.map_err(|err| format!("could not create {dest_dir}: {err}"))?;
let dest = Path::new(dest_dir).join(file_name);
fs::copy(source, &dest).map_err(|err| {
format!(
"could not copy {} to {}: {err}",
source.display(),
dest.display()
)
})?;
copied += 1;
}
Ok(copied)
}
fn import_dir_for_extension(extension: &str) -> &'static str {
match extension.to_ascii_lowercase().as_str() {
"gltf" | "glb" | "fbx" => "assets/models",
"png" | "jpg" | "jpeg" | "webp" | "ktx2" => "assets/textures",
"ron" => "assets/levels",
"mat" | "material" => "assets/materials",
_ => "assets",
}
}
fn default_material_for(shape: &PrimitiveShape) -> MaterialDesc {
match shape {
PrimitiveShape::Box => MaterialDesc::default(),
PrimitiveShape::Sphere => MaterialDesc::new(ColorDesc::srgb(0.9, 0.9, 0.92), 1.0, 0.25),
PrimitiveShape::Ramp => MaterialDesc::new(ColorDesc::srgb(0.30, 0.45, 0.70), 0.05, 0.55),
}
}
pub fn asset_cache_key(asset: &EditorAsset) -> String {
match &asset.path {
Some(path) => path.clone(),
None => format!("builtin:{}", asset.label),
}
}
+71
View File
@@ -0,0 +1,71 @@
//! External asset import helpers (FBX sidecar folders, etc.).
use std::fs;
use std::path::{Path, PathBuf};
/// Copies an FBX file and its sibling `.fbm` embedded-texture folder when present.
pub fn copy_fbx_with_sidecar(source: &Path, dest_dir: &Path) -> Result<(), String> {
let Some(file_name) = source.file_name() else {
return Err("FBX import path has no file name".into());
};
fs::create_dir_all(dest_dir)
.map_err(|err| format!("could not create {}: {err}", dest_dir.display()))?;
let dest = dest_dir.join(file_name);
fs::copy(source, &dest).map_err(|err| {
format!(
"could not copy {} to {}: {err}",
source.display(),
dest.display()
)
})?;
if let Some(fbm_dir) = fbm_sidecar_dir(source) {
if fbm_dir.is_dir() {
let dest_fbm = dest_dir.join(fbm_dir.file_name().unwrap_or_default());
copy_dir_recursive(&fbm_dir, &dest_fbm)?;
}
}
Ok(())
}
fn fbm_sidecar_dir(source: &Path) -> Option<PathBuf> {
let stem = source.file_stem()?.to_str()?;
let parent = source.parent()?;
Some(parent.join(format!("{stem}.fbm")))
}
fn copy_dir_recursive(source: &Path, dest: &Path) -> Result<(), String> {
fs::create_dir_all(dest)
.map_err(|err| format!("could not create {}: {err}", dest.display()))?;
for entry in fs::read_dir(source).map_err(|err| err.to_string())? {
let entry = entry.map_err(|err| err.to_string())?;
let src_path = entry.path();
let dest_path = dest.join(entry.file_name());
if src_path.is_dir() {
copy_dir_recursive(&src_path, &dest_path)?;
} else {
fs::copy(&src_path, &dest_path).map_err(|err| {
format!(
"could not copy {} to {}: {err}",
src_path.display(),
dest_path.display()
)
})?;
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::fbm_sidecar_dir;
use std::path::Path;
#[test]
fn fbm_sidecar_path() {
assert_eq!(
fbm_sidecar_dir(Path::new("/tmp/Character.fbx")),
Some(Path::new("/tmp/Character.fbm").to_path_buf())
);
}
}
+101
View File
@@ -0,0 +1,101 @@
//! Material asset loading and inspector/browser integration.
use bevy::prelude::*;
use bevy_egui::egui;
use shared::{LevelObject, MaterialAsset, MaterialDesc};
use crate::assets::{EditorAsset, EditorAssetKind, EditorAssets};
use crate::history::set_material_with_history;
use crate::ui::inspector::property_row;
pub fn load_material_asset(catalog_path: &str) -> Result<MaterialAsset, String> {
MaterialAsset::load_from_path(catalog_path)
}
pub fn material_desc_from_asset(catalog_path: &str) -> Result<MaterialDesc, String> {
let asset = load_material_asset(catalog_path)?;
let mut desc = asset.material;
desc.material_asset_path = Some(catalog_path.to_string());
Ok(desc)
}
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());
}
world.resource_mut::<crate::scene_io::SceneIo>().status =
format!("Applied material {}", asset.label);
}
pub fn material_asset_picker_ui(
world: &mut World,
ui: &mut egui::Ui,
_entity: Entity,
material: &mut MaterialDesc,
_original: &MaterialDesc,
) -> bool {
let assets: Vec<(String, String)> = world
.resource::<EditorAssets>()
.assets
.iter()
.filter(|a| matches!(a.kind, EditorAssetKind::Material))
.filter_map(|a| Some((a.label.clone(), a.path.clone()?)))
.collect();
let current = material.material_asset_path.clone().unwrap_or_default();
let mut selected_label = assets
.iter()
.find(|(_, path)| path == &current)
.map(|(label, _)| label.clone())
.unwrap_or_else(|| "(none)".to_string());
let mut changed = false;
property_row(ui, "Material asset", |ui| {
egui::ComboBox::from_id_salt("material_asset_picker")
.selected_text(&selected_label)
.show_ui(ui, |ui| {
if ui.selectable_label(current.is_empty(), "(none)").clicked() {
material.material_asset_path = None;
selected_label = "(none)".into();
changed = true;
}
for (label, path) in &assets {
if ui
.selectable_label(&selected_label == label, label)
.clicked()
{
if let Ok(desc) = material_desc_from_asset(path) {
*material = desc;
selected_label = label.clone();
changed = true;
} else {
world.resource_mut::<crate::scene_io::SceneIo>().status =
format!("Could not load material {path}");
}
}
}
});
});
changed
}
+15
View File
@@ -0,0 +1,15 @@
//! Asset catalog, database, thumbnails, materials, and prefab overrides.
pub mod asset_db;
mod catalog;
mod import;
pub mod materials;
pub mod prefab_overrides;
pub mod static_mesh;
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, ThumbnailsPlugin,
};
@@ -0,0 +1,390 @@
//! Prefab instance overrides — apply/revert per field group (v2).
use std::collections::HashMap;
use std::path::Path;
use bevy::prelude::*;
use bevy_egui::egui;
use egui_phosphor_icons::icons;
use scene::{migrate_scene_text, strip_schema_version, validate_level_text};
use serde::{Deserialize, Serialize};
use shared::{EditorVisibility, MaterialDesc, PrefabInstance};
use crate::history::{set_material_with_history, set_transform_with_history};
use crate::ui::inspector::{
apply_component_card_response, component_card, component_card_context, property_row,
ComponentCardOptions,
};
#[derive(Resource, Default)]
pub struct PrefabOverrideClipboard {
pub property_path: String,
pub value_ron: String,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
pub struct PrefabOverrides {
#[serde(default)]
pub transform: Option<Transform>,
#[serde(default)]
pub material: Option<MaterialDesc>,
#[serde(default)]
pub child_visibility: HashMap<String, bool>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PrefabOverrideField {
Transform,
Material,
ChildVisibility,
}
pub fn read_overrides(instance: &PrefabInstance) -> PrefabOverrides {
instance
.overrides_ron
.as_ref()
.and_then(|ron| ron::from_str(ron).ok())
.unwrap_or_default()
}
pub fn write_overrides(world: &mut World, entity: Entity, overrides: &PrefabOverrides) {
let Some(mut instance) = world.get::<PrefabInstance>(entity).cloned() else {
return;
};
instance.overrides_ron = if overrides == &PrefabOverrides::default() {
None
} else {
Some(ron::to_string(overrides).unwrap_or_default())
};
if let Ok(mut entity_mut) = world.get_entity_mut(entity) {
entity_mut.insert(instance);
}
}
pub fn has_override(overrides: &PrefabOverrides, field: PrefabOverrideField) -> bool {
match field {
PrefabOverrideField::Transform => overrides.transform.is_some(),
PrefabOverrideField::Material => overrides.material.is_some(),
PrefabOverrideField::ChildVisibility => !overrides.child_visibility.is_empty(),
}
}
pub fn capture_transform_override(world: &mut World, entity: Entity) {
let Some(transform) = world.get::<Transform>(entity).copied() else {
return;
};
let Some(instance) = world.get::<PrefabInstance>(entity) else {
return;
};
let mut overrides = read_overrides(instance);
overrides.transform = Some(transform);
write_overrides(world, entity, &overrides);
}
pub fn revert_transform_override(world: &mut World, entity: Entity) {
let Some(instance) = world.get::<PrefabInstance>(entity).cloned() else {
return;
};
let Some(old) = world.get::<Transform>(entity).copied() else {
return;
};
let Some(source_transform) = prefab_root_transform(&instance.source_path) else {
world.resource_mut::<crate::scene_io::SceneIo>().status =
"Could not read prefab source for revert".into();
return;
};
set_transform_with_history(world, entity, old, source_transform);
let mut overrides = read_overrides(&instance);
overrides.transform = None;
write_overrides(world, entity, &overrides);
}
pub fn apply_material_override(world: &mut World, entity: Entity) {
let Some(instance) = world.get::<PrefabInstance>(entity).cloned() else {
return;
};
let Some(material) = world.get::<MaterialDesc>(entity).cloned() else {
world.resource_mut::<crate::scene_io::SceneIo>().status =
"Prefab instance has no MaterialDesc to capture".into();
return;
};
let mut overrides = read_overrides(&instance);
overrides.material = Some(material);
write_overrides(world, entity, &overrides);
world.resource_mut::<crate::scene_io::SceneIo>().status = "Material override applied".into();
}
pub fn revert_material_override(world: &mut World, entity: Entity) {
let Some(instance) = world.get::<PrefabInstance>(entity).cloned() else {
return;
};
let Some(source_material) = prefab_root_material(&instance.source_path) else {
world.resource_mut::<crate::scene_io::SceneIo>().status =
"Could not read prefab source material".into();
return;
};
let old = world.get::<MaterialDesc>(entity).cloned();
if old.is_some() {
set_material_with_history(world, entity, source_material.clone());
} else {
world.entity_mut(entity).insert(source_material.clone());
}
let mut overrides = read_overrides(&instance);
overrides.material = None;
write_overrides(world, entity, &overrides);
}
pub fn apply_child_visibility_override(world: &mut World, entity: Entity, child: Entity) {
let Some(instance) = world.get::<PrefabInstance>(entity).cloned() else {
return;
};
let Some(name) = world.get::<Name>(child).map(|n| n.to_string()) else {
return;
};
let visible = world
.get::<EditorVisibility>(child)
.map(|v| v.visible)
.unwrap_or(true);
let mut overrides = read_overrides(&instance);
overrides.child_visibility.insert(name, visible);
write_overrides(world, entity, &overrides);
}
pub fn revert_child_visibility_overrides(world: &mut World, entity: Entity) {
let Some(instance) = world.get::<PrefabInstance>(entity).cloned() else {
return;
};
for child in prefab_instance_children(world, entity) {
if let Ok(mut entity_mut) = world.get_entity_mut(child) {
entity_mut.remove::<EditorVisibility>();
}
}
let mut overrides = read_overrides(&instance);
overrides.child_visibility.clear();
write_overrides(world, entity, &overrides);
}
pub fn apply_stored_overrides(world: &mut World, entity: Entity) {
let Some(instance) = world.get::<PrefabInstance>(entity).cloned() else {
return;
};
let overrides = read_overrides(&instance);
if let Some(transform) = overrides.transform {
if let Ok(mut entity_mut) = world.get_entity_mut(entity) {
entity_mut.insert(transform);
}
}
if let Some(material) = overrides.material {
if let Ok(mut entity_mut) = world.get_entity_mut(entity) {
entity_mut.insert(material);
}
}
for child in prefab_instance_children(world, entity) {
let Some(name) = world.get::<Name>(child).map(|n| n.to_string()) else {
continue;
};
if let Some(&visible) = overrides.child_visibility.get(&name) {
if let Ok(mut entity_mut) = world.get_entity_mut(child) {
entity_mut.insert(EditorVisibility { visible });
}
}
}
}
pub fn prefab_instance_inspector_ui(world: &mut World, ui: &mut egui::Ui, entity: Entity) {
let Some(instance) = world.get::<PrefabInstance>(entity).cloned() else {
return;
};
let overrides = read_overrides(&instance);
let card = component_card_context(
world,
entity,
ComponentCardOptions::removable(
shared::COMPONENT_PREFAB_INSTANCE,
"Prefab Instance",
icons::PACKAGE,
),
);
let card_response = component_card(ui, &card, |ui| {
property_row(ui, "Asset ID", |ui| {
ui.add(egui::Label::new(instance.asset_id.as_str()).truncate());
});
property_row(ui, "Source", |ui| {
ui.add(egui::Label::new(instance.source_path.as_str()).truncate());
});
ui.collapsing("Transform override", |ui| {
let active = has_override(&overrides, PrefabOverrideField::Transform);
if active {
ui.label(egui::RichText::new("Override active").weak());
}
ui.horizontal_wrapped(|ui| {
if ui.button("Apply").clicked() {
capture_transform_override(world, entity);
world.resource_mut::<crate::scene_io::SceneIo>().status =
"Transform override saved".into();
}
if ui
.add_enabled(active, egui::Button::new("Revert"))
.clicked()
{
revert_transform_override(world, entity);
}
});
});
ui.collapsing("Material override", |ui| {
let active = has_override(&overrides, PrefabOverrideField::Material);
if active {
ui.label(egui::RichText::new("Override active").weak());
}
ui.horizontal_wrapped(|ui| {
if ui.button("Apply").clicked() {
apply_material_override(world, entity);
}
if ui
.add_enabled(active, egui::Button::new("Revert"))
.clicked()
{
revert_material_override(world, entity);
}
});
});
ui.collapsing("Child visibility overrides", |ui| {
let active = has_override(&overrides, PrefabOverrideField::ChildVisibility);
if active {
ui.label(egui::RichText::new("Overrides stored by child name").weak());
}
for child in prefab_instance_children(world, entity) {
let name = world
.get::<Name>(child)
.map(|n| n.to_string())
.unwrap_or_else(|| format!("{child:?}"));
ui.horizontal_wrapped(|ui| {
ui.add(egui::Label::new(name).truncate());
if ui.small_button("Apply").clicked() {
apply_child_visibility_override(world, entity, child);
}
});
}
ui.horizontal_wrapped(|ui| {
if ui
.add_enabled(active, egui::Button::new("Revert all"))
.clicked()
{
revert_child_visibility_overrides(world, entity);
}
});
});
ui.horizontal_wrapped(|ui| {
if ui.button("Unpack Instance").clicked() {
crate::history::unpack_prefab_instance(world, entity);
}
});
});
apply_component_card_response(world, entity, card_response);
}
fn prefab_instance_children(world: &World, root: Entity) -> Vec<Entity> {
let mut children = Vec::new();
let mut stack = Vec::new();
if let Some(kids) = world.get::<Children>(root) {
stack.extend(kids.iter());
}
while let Some(entity) = stack.pop() {
children.push(entity);
if let Some(kids) = world.get::<Children>(entity) {
stack.extend(kids.iter());
}
}
children
}
fn prefab_root_transform(source_path: &str) -> Option<Transform> {
parse_prefab_root_component::<Transform>(source_path, "Transform")
}
fn prefab_root_material(source_path: &str) -> Option<MaterialDesc> {
parse_prefab_root_component::<MaterialDesc>(source_path, "MaterialDesc")
}
fn parse_prefab_root_component<T: serde::de::DeserializeOwned>(
source_path: &str,
type_name: &str,
) -> Option<T> {
let path = Path::new(source_path);
let text = std::fs::read_to_string(path).ok()?;
validate_level_text(&text).ok()?;
let body = strip_schema_version(&migrate_scene_text(&text).ok()?).ok()?;
let root_tuple = body.trim().trim_start_matches('(').trim_end_matches(')');
for segment in split_top_level_fields(root_tuple) {
let segment = segment.trim();
if segment.starts_with("entities:") {
let entities_body = segment.trim_start_matches("entities:").trim();
return parse_first_entity_component(entities_body, type_name);
}
}
None
}
fn split_top_level_fields(input: &str) -> Vec<String> {
let mut fields = Vec::new();
let mut depth: i32 = 0;
let mut start = 0;
for (index, ch) in input.char_indices() {
match ch {
'(' | '{' => depth += 1,
')' | '}' => depth = depth.saturating_sub(1),
',' if depth == 0 => {
fields.push(input[start..index].to_string());
start = index + 1;
}
_ => {}
}
}
if start < input.len() {
fields.push(input[start..].to_string());
}
fields
}
fn parse_first_entity_component<T: serde::de::DeserializeOwned>(
entities_body: &str,
type_name: &str,
) -> Option<T> {
let trimmed = entities_body.trim();
let inner = trimmed.strip_prefix('{')?.strip_suffix('}')?.trim();
let first_entity = inner.split(',').next()?.trim();
let components = first_entity
.split(':')
.nth(1)?
.trim()
.strip_prefix('(')?
.strip_suffix(')')?;
for component in split_top_level_fields(components) {
if component.contains(type_name) {
return ron::from_str::<T>(&format!("({component})")).ok();
}
}
None
}
pub fn list_prefab_dependencies(path: &str) -> Vec<String> {
vec![path.to_string()]
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn empty_overrides_roundtrip() {
let instance = PrefabInstance::new("id", "assets/prefabs/test.scn.ron");
assert_eq!(read_overrides(&instance), PrefabOverrides::default());
}
}
+648
View File
@@ -0,0 +1,648 @@
//! Normalized static mesh artifacts generated from model source files.
use std::fs;
use std::path::Path;
use std::time::UNIX_EPOCH;
use bevy::gltf::GltfAssetLabel;
use bevy::prelude::*;
use bevy_ufbx::label::FbxAssetLabel;
use bevy_ufbx::mesh::group_faces_by_material;
use bevy_ufbx::utils::convert_matrix;
use serde::{Deserialize, Serialize};
use crate::asset_db::{
AssetRecord, ImportSettings, MaterialImportPolicy, ModelHierarchyMode, ModelPlacementMode,
};
use shared::{ComponentInstanceId, EditorAssetRef, StaticMeshRenderer, StaticMeshRendererEntry};
pub const STATIC_MESH_MANIFEST_SCHEMA: u32 = 1;
pub const STATIC_MESH_ARTIFACT_DIR: &str = "assets/meshes/generated";
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct StaticMeshManifest {
pub schema_version: u32,
pub asset_id: String,
pub label: String,
pub source: StaticMeshSource,
pub import: StaticMeshImportSnapshot,
pub metadata: StaticMeshMetadata,
pub parts: Vec<StaticMeshPart>,
pub warnings: Vec<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct StaticMeshSource {
pub path: String,
pub format: String,
pub fingerprint: StaticMeshSourceFingerprint,
pub dependencies: Vec<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct StaticMeshSourceFingerprint {
pub byte_len: u64,
pub modified_unix_secs: u64,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct StaticMeshImportSnapshot {
pub scale: f32,
pub generate_collider: bool,
pub lod0_only: bool,
pub placement_mode: ModelPlacementMode,
pub hierarchy_mode: ModelHierarchyMode,
pub material_policy: MaterialImportPolicy,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct StaticMeshMetadata {
pub mesh_count: usize,
pub material_count: usize,
pub node_count: usize,
pub animation_count: usize,
pub skin_count: usize,
pub light_count: usize,
pub camera_count: usize,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct StaticMeshPart {
#[serde(default)]
pub id: String,
pub name: String,
pub mesh_label: String,
#[serde(default)]
pub material_id: Option<String>,
pub material_slot_name: String,
pub material_label: Option<String>,
pub local_transform: Transform,
pub source_node: Option<String>,
pub source_mesh: Option<String>,
pub source_material: Option<String>,
}
pub fn static_mesh_manifest_path(asset_id: &str) -> String {
format!("{STATIC_MESH_ARTIFACT_DIR}/{asset_id}.static_mesh.ron")
}
pub fn part_id_from_label(label: &str) -> String {
format!("mesh:{}", stable_sub_asset_slug(label))
}
pub fn material_id_from_label(label: &str) -> String {
format!("material:{}", stable_sub_asset_slug(label))
}
fn stable_sub_asset_slug(label: &str) -> String {
let mut slug = String::new();
for ch in label.chars() {
if ch.is_ascii_alphanumeric() {
slug.push(ch.to_ascii_lowercase());
} else if !slug.ends_with('_') {
slug.push('_');
}
}
slug.trim_matches('_').to_string()
}
pub fn refresh_static_mesh_artifact(
record: &mut AssetRecord,
) -> Result<StaticMeshManifest, String> {
let mut manifest = build_static_mesh_manifest(record)?;
let path = static_mesh_manifest_path(&record.id.as_string());
record.import_settings.static_mesh_manifest_path = Some(path.clone());
manifest.source.dependencies.sort();
manifest.source.dependencies.dedup();
record.dependencies = manifest.source.dependencies.clone();
let text = ron::ser::to_string_pretty(&manifest, ron::ser::PrettyConfig::default())
.map_err(|err| format!("could not serialize static mesh manifest: {err}"))?;
if let Some(parent) = Path::new(&path).parent() {
fs::create_dir_all(parent)
.map_err(|err| format!("could not create {}: {err}", parent.display()))?;
}
let should_write = fs::read_to_string(&path).ok().as_deref() != Some(text.as_str());
if should_write {
fs::write(&path, text)
.map_err(|err| format!("could not write static mesh manifest {path}: {err}"))?;
info!(
"Static mesh manifest refreshed: source={} artifact={} parts={}",
record.path,
path,
manifest.parts.len()
);
}
Ok(manifest)
}
pub fn load_static_mesh_manifest(path: &str) -> Result<StaticMeshManifest, String> {
let text = fs::read_to_string(path).map_err(|err| format!("could not read {path}: {err}"))?;
ron::from_str(&text).map_err(|err| format!("could not parse {path}: {err}"))
}
pub fn renderer_from_manifest(
manifest: &StaticMeshManifest,
settings: &ImportSettings,
) -> StaticMeshRenderer {
let use_source_materials = matches!(
settings.material_policy,
MaterialImportPolicy::SourceMaterials
);
StaticMeshRenderer {
slots: manifest
.parts
.iter()
.map(|part| StaticMeshRendererEntry {
id: ComponentInstanceId::new(part_effective_id(part)),
name: part.name.clone(),
mesh: EditorAssetRef::new(
manifest.asset_id.clone(),
part_effective_id(part),
part.name.clone(),
),
material: use_source_materials
.then(|| {
part_effective_material_id(part).map(|id| {
EditorAssetRef::new(
manifest.asset_id.clone(),
id,
part.material_slot_name.clone(),
)
})
})
.flatten(),
local_transform: part.local_transform,
visible: true,
cast_shadows: true,
receive_shadows: true,
})
.collect(),
}
}
fn part_effective_id(part: &StaticMeshPart) -> String {
if part.id.trim().is_empty() {
part_id_from_label(&part.mesh_label)
} else {
part.id.clone()
}
}
fn part_effective_material_id(part: &StaticMeshPart) -> Option<String> {
part.material_id.clone().or_else(|| {
part.material_label
.as_ref()
.map(|label| material_id_from_label(label))
})
}
fn build_static_mesh_manifest(record: &AssetRecord) -> Result<StaticMeshManifest, String> {
let format = source_format(&record.path)?;
let fingerprint = source_fingerprint(&record.path)?;
let import = StaticMeshImportSnapshot {
scale: record.import_settings.scale,
generate_collider: record.import_settings.generate_collider,
lod0_only: record.import_settings.lod0_only,
placement_mode: record.import_settings.placement_mode.clone(),
hierarchy_mode: record.import_settings.hierarchy_mode.clone(),
material_policy: record.import_settings.material_policy.clone(),
};
let mut manifest = match format.as_str() {
"gltf" | "glb" => build_gltf_manifest(record, format, fingerprint, import)?,
"fbx" => build_fbx_manifest(record, format, fingerprint, import)?,
_ => return Err(format!("unsupported static mesh source format `{format}`")),
};
if manifest.parts.is_empty() {
manifest
.warnings
.push("No renderable static mesh parts were found.".into());
}
Ok(manifest)
}
fn build_gltf_manifest(
record: &AssetRecord,
format: String,
fingerprint: StaticMeshSourceFingerprint,
import: StaticMeshImportSnapshot,
) -> Result<StaticMeshManifest, String> {
let gltf = gltf::Gltf::open(&record.path)
.map_err(|err| format!("could not parse glTF {}: {err}", record.path))?;
let mut parts = Vec::new();
let mut dependencies = Vec::new();
let mut warnings = Vec::new();
for buffer in gltf.document.buffers() {
if let gltf::buffer::Source::Uri(uri) = buffer.source() {
dependencies.push(resolve_dependency(&record.path, uri));
}
}
for image in gltf.document.images() {
if let gltf::image::Source::Uri { uri, .. } = image.source() {
dependencies.push(resolve_dependency(&record.path, uri));
}
}
if let Some(scene) = gltf
.document
.default_scene()
.or_else(|| gltf.document.scenes().next())
{
for node in scene.nodes() {
collect_gltf_node_parts(node, Mat4::IDENTITY, &mut parts);
}
} else {
for mesh in gltf.document.meshes() {
collect_gltf_mesh_parts(None, None, mesh, Mat4::IDENTITY, &mut parts);
}
}
if gltf.document.animations().count() > 0 {
warnings.push(
"Animations are recorded as metadata; use Scene Instance placement for playback."
.into(),
);
}
if gltf.document.skins().count() > 0 {
warnings.push(
"Skins are recorded as metadata; skinned playback stays on the Scene Instance path."
.into(),
);
}
parts.sort_by(|a, b| a.mesh_label.cmp(&b.mesh_label).then(a.name.cmp(&b.name)));
Ok(StaticMeshManifest {
schema_version: STATIC_MESH_MANIFEST_SCHEMA,
asset_id: record.id.as_string(),
label: record.label.clone(),
source: StaticMeshSource {
path: record.path.clone(),
format,
fingerprint,
dependencies,
},
import,
metadata: StaticMeshMetadata {
mesh_count: gltf.document.meshes().count(),
material_count: gltf.document.materials().count(),
node_count: gltf.document.nodes().count(),
animation_count: gltf.document.animations().count(),
skin_count: gltf.document.skins().count(),
light_count: 0,
camera_count: gltf.document.cameras().count(),
},
parts,
warnings,
})
}
fn collect_gltf_node_parts(
node: gltf::Node<'_>,
parent_transform: Mat4,
parts: &mut Vec<StaticMeshPart>,
) {
let local = Mat4::from_cols_array_2d(&node.transform().matrix());
let world_transform = parent_transform * local;
if let Some(mesh) = node.mesh() {
collect_gltf_mesh_parts(
node.name().map(str::to_string),
Some(node.index()),
mesh,
world_transform,
parts,
);
}
for child in node.children() {
collect_gltf_node_parts(child, world_transform, parts);
}
}
fn collect_gltf_mesh_parts(
node_name: Option<String>,
node_index: Option<usize>,
mesh: gltf::Mesh<'_>,
transform: Mat4,
parts: &mut Vec<StaticMeshPart>,
) {
let mesh_index = mesh.index();
let mesh_name = mesh.name().map(str::to_string);
for primitive in mesh.primitives() {
let primitive_index = primitive.index();
let mesh_label = GltfAssetLabel::Primitive {
mesh: mesh_index,
primitive: primitive_index,
}
.to_string();
let material = primitive.material();
let material_label = material
.index()
.map(|index| {
GltfAssetLabel::Material {
index,
is_scale_inverted: false,
}
.to_string()
})
.or_else(|| Some(GltfAssetLabel::DefaultMaterial.to_string()));
let material_name = material
.name()
.map(str::to_string)
.unwrap_or_else(|| "Default Material".into());
let name = node_name
.clone()
.or_else(|| mesh_name.clone())
.unwrap_or_else(|| format!("Mesh {mesh_index}"));
let source_node = node_index.map(|index| format!("Node{index}"));
parts.push(StaticMeshPart {
id: part_id_from_label(&mesh_label),
name: format!("{name} / Primitive {primitive_index}"),
material_id: material_label
.as_ref()
.map(|label| material_id_from_label(label)),
mesh_label,
material_slot_name: material_name.clone(),
material_label,
local_transform: Transform::from_matrix(transform),
source_node,
source_mesh: Some(format!("Mesh{mesh_index}")),
source_material: Some(material_name),
});
}
}
fn build_fbx_manifest(
record: &AssetRecord,
format: String,
fingerprint: StaticMeshSourceFingerprint,
import: StaticMeshImportSnapshot,
) -> Result<StaticMeshManifest, String> {
let bytes =
fs::read(&record.path).map_err(|err| format!("could not read {}: {err}", record.path))?;
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(|err| format!("could not parse FBX {}: {err:?}", record.path))?;
let mut parts = Vec::new();
let mut warnings = Vec::new();
for (node_index, node) in scene.nodes.as_ref().iter().enumerate() {
let Some(mesh_ref) = node.mesh.as_ref() else {
continue;
};
let mesh = mesh_ref.as_ref();
if mesh.num_vertices == 0 || mesh.faces.as_ref().is_empty() {
continue;
}
let mut groups: Vec<(usize, Vec<u32>)> =
group_faces_by_material(mesh).into_iter().collect();
groups.sort_by_key(|(material_index, _)| *material_index);
for (material_index, indices) in groups {
if indices.is_empty() {
continue;
}
let material = mesh.materials.get(material_index).map(|mat| mat.as_ref());
let material_label = material
.and_then(|mat| fbx_material_label(&scene, mat.element.element_id))
.or_else(|| Some(FbxAssetLabel::DefaultMaterial.to_string()));
let material_name = material
.map(|mat| mat.element.name.to_string())
.filter(|name| !name.is_empty())
.unwrap_or_else(|| "Default Material".into());
let node_name = if node.element.name.is_empty() {
format!("Node {node_index}")
} else {
node.element.name.to_string()
};
let mesh_label = FbxAssetLabel::Mesh(node_index * 1000 + material_index).to_string();
parts.push(StaticMeshPart {
id: part_id_from_label(&mesh_label),
name: format!("{node_name} / Material {material_index}"),
material_id: material_label
.as_ref()
.map(|label| material_id_from_label(label)),
mesh_label,
material_slot_name: material_name.clone(),
material_label,
local_transform: Transform::from_matrix(convert_matrix(&node.geometry_to_world)),
source_node: Some(format!("Node{node_index}")),
source_mesh: Some(format!("Mesh{node_index}")),
source_material: Some(material_name),
});
}
}
if !scene.anim_stacks.as_ref().is_empty() {
warnings.push(
"Animations are recorded as metadata; use Scene Instance placement for playback."
.into(),
);
}
if !scene.skin_deformers.as_ref().is_empty() {
warnings.push(
"Skins are recorded as metadata; skinned playback stays on the Scene Instance path."
.into(),
);
}
parts.sort_by(|a, b| a.mesh_label.cmp(&b.mesh_label).then(a.name.cmp(&b.name)));
Ok(StaticMeshManifest {
schema_version: STATIC_MESH_MANIFEST_SCHEMA,
asset_id: record.id.as_string(),
label: record.label.clone(),
source: StaticMeshSource {
path: record.path.clone(),
format,
fingerprint,
dependencies: fbx_dependencies(&record.path),
},
import,
metadata: StaticMeshMetadata {
mesh_count: scene.meshes.as_ref().len(),
material_count: scene.materials.as_ref().len(),
node_count: scene.nodes.as_ref().len(),
animation_count: scene.anim_stacks.as_ref().len(),
skin_count: scene.skin_deformers.as_ref().len(),
light_count: scene.lights.as_ref().len(),
camera_count: scene.cameras.as_ref().len(),
},
parts,
warnings,
})
}
fn fbx_material_label(scene: &ufbx::Scene, element_id: u32) -> Option<String> {
if element_id == 0 {
return None;
}
scene
.materials
.as_ref()
.iter()
.position(|material| material.element.element_id == element_id)
.map(|index| FbxAssetLabel::Material(index).to_string())
}
fn fbx_dependencies(source_path: &str) -> Vec<String> {
let path = Path::new(source_path);
let Some(stem) = path.file_stem().and_then(|stem| stem.to_str()) else {
return Vec::new();
};
let Some(parent) = path.parent() else {
return Vec::new();
};
let sidecar = parent.join(format!("{stem}.fbm"));
if !sidecar.is_dir() {
return Vec::new();
}
walkdir::WalkDir::new(sidecar)
.follow_links(false)
.into_iter()
.filter_map(Result::ok)
.filter(|entry| entry.file_type().is_file())
.map(|entry| entry.path().to_string_lossy().replace('\\', "/"))
.collect()
}
fn source_format(path: &str) -> Result<String, String> {
Path::new(path)
.extension()
.and_then(|ext| ext.to_str())
.map(|ext| ext.to_ascii_lowercase())
.ok_or_else(|| format!("asset path `{path}` has no extension"))
}
fn source_fingerprint(path: &str) -> Result<StaticMeshSourceFingerprint, String> {
let metadata = fs::metadata(path).map_err(|err| format!("could not stat {path}: {err}"))?;
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(StaticMeshSourceFingerprint {
byte_len: metadata.len(),
modified_unix_secs,
})
}
fn resolve_dependency(source_path: &str, uri: &str) -> String {
if uri.starts_with("data:") || uri.contains("://") {
return uri.to_string();
}
Path::new(source_path)
.parent()
.unwrap_or_else(|| Path::new(""))
.join(uri)
.to_string_lossy()
.replace('\\', "/")
}
#[cfg(test)]
mod tests {
use super::*;
fn test_manifest() -> StaticMeshManifest {
StaticMeshManifest {
schema_version: STATIC_MESH_MANIFEST_SCHEMA,
asset_id: "asset-1".into(),
label: "Crate".into(),
source: StaticMeshSource {
path: "assets/models/crate.glb".into(),
format: "glb".into(),
fingerprint: StaticMeshSourceFingerprint {
byte_len: 42,
modified_unix_secs: 10,
},
dependencies: Vec::new(),
},
import: StaticMeshImportSnapshot {
scale: 1.0,
generate_collider: true,
lod0_only: true,
placement_mode: ModelPlacementMode::StaticAsset,
hierarchy_mode: ModelHierarchyMode::SingleActor,
material_policy: MaterialImportPolicy::SourceMaterials,
},
metadata: StaticMeshMetadata {
mesh_count: 1,
material_count: 1,
node_count: 1,
animation_count: 0,
skin_count: 0,
light_count: 0,
camera_count: 0,
},
parts: vec![StaticMeshPart {
id: "mesh:mesh0_primitive0".into(),
name: "Crate / Primitive 0".into(),
mesh_label: "Mesh0/Primitive0".into(),
material_id: Some("material:material0".into()),
material_slot_name: "Wood".into(),
material_label: Some("Material0".into()),
local_transform: Transform::from_xyz(1.0, 2.0, 3.0),
source_node: Some("Node0".into()),
source_mesh: Some("Mesh0".into()),
source_material: Some("Wood".into()),
}],
warnings: Vec::new(),
}
}
#[test]
fn static_mesh_manifest_path_uses_asset_id() {
assert_eq!(
static_mesh_manifest_path("abc"),
"assets/meshes/generated/abc.static_mesh.ron"
);
}
#[test]
fn renderer_from_manifest_preserves_labels_and_collider_policy() {
let manifest = test_manifest();
let settings = ImportSettings {
generate_collider: true,
..Default::default()
};
let renderer = renderer_from_manifest(&manifest, &settings);
assert_eq!(renderer.slots.len(), 1);
let entry = &renderer.slots[0];
assert_eq!(entry.mesh.asset_id, manifest.asset_id);
assert_eq!(entry.mesh.sub_asset_id, "mesh:mesh0_primitive0");
assert_eq!(
entry
.material
.as_ref()
.map(|material| material.sub_asset_id.as_str()),
Some("material:material0")
);
}
#[test]
fn renderer_from_manifest_can_ignore_source_materials() {
let manifest = test_manifest();
let settings = ImportSettings {
material_policy: MaterialImportPolicy::AuthoringOverride,
..Default::default()
};
let renderer = renderer_from_manifest(&manifest, &settings);
assert!(renderer.slots[0].material.is_none());
}
}
@@ -0,0 +1,379 @@
//! Thumbnail cache for asset browser grid cells.
use std::collections::{HashMap, HashSet};
use bevy::prelude::*;
use bevy_egui::{egui, EguiPrimaryContextPass, EguiTextureHandle, EguiUserTextures};
use egui_phosphor_icons::icons;
use super::sources::gltf::gltf_base_color_texture_path;
use super::studio::{model_file_exists, ThumbnailStudio};
use crate::assets::{
asset_cache_key, asset_server_path, EditorAsset, EditorAssetKind, EditorAssets,
};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ThumbnailState {
Pending,
Ready,
Failed { reason: String, retryable: bool },
}
#[derive(Debug, Clone)]
struct ThumbnailFailure {
reason: String,
retryable: bool,
}
#[derive(Resource, Default)]
pub struct AssetThumbnailCache {
pub texture_ids: HashMap<String, egui::TextureId>,
pending: HashMap<String, Handle<Image>>,
pub(crate) studio_pending: HashSet<String>,
failed: HashMap<String, ThumbnailFailure>,
prefetched_folder: Option<String>,
}
pub struct AssetThumbnailsPlugin;
impl Plugin for AssetThumbnailsPlugin {
fn build(&self, app: &mut App) {
app.init_resource::<AssetThumbnailCache>()
.add_systems(EguiPrimaryContextPass, register_loaded_thumbnails);
}
}
impl AssetThumbnailCache {
pub fn state(&self, key: &str) -> Option<ThumbnailState> {
if self.texture_ids.contains_key(key) {
return Some(ThumbnailState::Ready);
}
if self.failed.contains_key(key) {
let failure = self.failed.get(key)?;
return Some(ThumbnailState::Failed {
reason: failure.reason.clone(),
retryable: failure.retryable,
});
}
if self.pending.contains_key(key) || self.studio_pending.contains(key) {
return Some(ThumbnailState::Pending);
}
None
}
pub fn retry(&mut self, key: &str) {
self.failed.remove(key);
self.pending.remove(key);
self.studio_pending.remove(key);
self.texture_ids.remove(key);
}
pub fn request_texture(&mut self, key: String, path: String, asset_server: &AssetServer) {
if matches!(
self.state(&key),
Some(ThumbnailState::Ready | ThumbnailState::Pending)
) {
return;
}
if self.failed.contains_key(&key) {
return;
}
let handle: Handle<Image> = asset_server.load(asset_server_path(&path));
self.pending.insert(key, handle);
}
pub fn request_model(
&mut self,
key: String,
model_path: String,
asset_server: &AssetServer,
studio: &mut ThumbnailStudio,
) {
if matches!(
self.state(&key),
Some(ThumbnailState::Ready | ThumbnailState::Pending)
) {
return;
}
if self.failed.contains_key(&key) {
return;
}
if let Some(texture_path) = gltf_base_color_texture_path(&model_path) {
self.request_texture(key, texture_path, asset_server);
return;
}
if !model_file_exists(&model_path) {
self.mark_studio_failed(&key, "file not found", false);
return;
}
if studio.enqueue(key.clone(), model_path) {
self.studio_pending.insert(key);
}
}
pub(crate) fn complete_studio_thumbnail(
&mut self,
key: &str,
image: Handle<Image>,
textures: &mut EguiUserTextures,
) {
self.studio_pending.remove(key);
self.failed.remove(key);
let texture_id = textures
.image_id(&image)
.unwrap_or_else(|| textures.add_image(EguiTextureHandle::Strong(image)));
self.texture_ids.insert(key.to_string(), texture_id);
}
pub(crate) fn mark_studio_failed(&mut self, key: &str, reason: &str, retryable: bool) {
self.studio_pending.remove(key);
self.pending.remove(key);
self.failed.insert(
key.to_string(),
ThumbnailFailure {
reason: reason.to_string(),
retryable,
},
);
}
pub fn invalidate_all(&mut self) {
self.texture_ids.clear();
self.pending.clear();
self.studio_pending.clear();
self.failed.clear();
self.prefetched_folder = None;
}
pub fn snapshot(&self) -> ThumbnailCacheSnapshot {
ThumbnailCacheSnapshot {
texture_ids: self.texture_ids.clone(),
pending_keys: self
.pending
.keys()
.chain(self.studio_pending.iter())
.cloned()
.collect(),
failed_keys: self.failed.keys().cloned().collect(),
}
}
}
fn register_loaded_thumbnails(
asset_server: Res<AssetServer>,
mut cache: ResMut<AssetThumbnailCache>,
mut textures: ResMut<EguiUserTextures>,
) {
let ready: Vec<(String, Handle<Image>)> = cache
.pending
.iter()
.filter(|(_, handle)| asset_server.is_loaded_with_dependencies(*handle))
.map(|(key, handle)| (key.clone(), handle.clone()))
.collect();
for (key, handle) in ready {
cache.pending.remove(&key);
cache.failed.remove(&key);
let texture_id = textures
.image_id(&handle)
.unwrap_or_else(|| textures.add_image(EguiTextureHandle::Strong(handle)));
cache.texture_ids.insert(key, texture_id);
}
}
pub fn kind_icon(kind: &EditorAssetKind) -> egui_phosphor_icons::Icon {
match kind {
EditorAssetKind::Primitive(_) => icons::CUBE,
EditorAssetKind::Light(_) => icons::LIGHTBULB,
EditorAssetKind::Model => icons::CUBE_TRANSPARENT,
EditorAssetKind::Texture => icons::IMAGE,
EditorAssetKind::Material => icons::PAINT_BRUSH,
EditorAssetKind::Level => icons::MAP_TRIFOLD,
EditorAssetKind::Prefab => icons::PACKAGE,
EditorAssetKind::PostProcessVolume => icons::CAMERA,
EditorAssetKind::PostProcessEffect => icons::SPARKLE,
EditorAssetKind::RenderingProfile => icons::SLIDERS,
EditorAssetKind::ShaderSchema => icons::CODE,
}
}
pub fn draw_asset_cell_with(
ui: &mut egui::Ui,
asset: &EditorAsset,
texture_id: Option<egui::TextureId>,
pending: bool,
failed: Option<&str>,
selected: bool,
thumbnail_size: f32,
) -> egui::Response {
let thumb_size = thumbnail_size.clamp(48.0, 112.0);
let cell_size = egui::vec2(thumb_size + 20.0, thumb_size + 30.0);
let (rect, response) = ui.allocate_exact_size(cell_size, egui::Sense::click_and_drag());
let fill = if selected {
crate::ui::theme::SELECTION_BG_MUTED
} else if response.hovered() {
crate::ui::theme::ELEVATED_BG
} else {
crate::ui::theme::WIDGET_BG
};
ui.painter().rect(
rect,
4.0,
fill,
egui::Stroke::new(
1.0,
if selected {
crate::ui::theme::ACCENT_HOVER
} else {
crate::ui::theme::BORDER
},
),
egui::StrokeKind::Inside,
);
let thumb_rect = egui::Rect::from_min_size(
rect.min + egui::vec2(10.0, 8.0),
egui::vec2(thumb_size, thumb_size),
);
if let Some(texture_id) = texture_id {
ui.painter().image(
texture_id,
thumb_rect,
egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)),
egui::Color32::WHITE,
);
} else if pending {
ui.painter().text(
thumb_rect.center(),
egui::Align2::CENTER_CENTER,
icons::CIRCLE_NOTCH.as_str(),
egui::FontId::new(24.0, egui::FontFamily::Name("phosphor-regular".into())),
crate::ui::theme::TEXT_DIM,
);
} else if failed.is_some() {
ui.painter().text(
thumb_rect.center(),
egui::Align2::CENTER_CENTER,
icons::WARNING_CIRCLE.as_str(),
egui::FontId::new(24.0, egui::FontFamily::Name("phosphor-regular".into())),
crate::ui::theme::TEXT_DIM,
);
} else {
let icon = kind_icon(&asset.kind);
ui.painter().text(
thumb_rect.center(),
egui::Align2::CENTER_CENTER,
icon.as_str(),
egui::FontId::new(28.0, egui::FontFamily::Name("phosphor-regular".into())),
crate::ui::theme::TEXT,
);
}
ui.painter().text(
egui::pos2(rect.center().x, rect.max.y - 6.0),
egui::Align2::CENTER_BOTTOM,
asset.label.as_str(),
egui::FontId::new(11.0, egui::FontFamily::Proportional),
if selected {
crate::ui::theme::TEXT_SELECTED
} else {
crate::ui::theme::TEXT
},
);
response
}
#[derive(Clone)]
pub struct ThumbnailCacheSnapshot {
pub texture_ids: HashMap<String, egui::TextureId>,
pub pending_keys: Vec<String>,
pub failed_keys: Vec<String>,
}
impl ThumbnailCacheSnapshot {
pub fn texture_for(&self, asset: &EditorAsset) -> Option<egui::TextureId> {
self.texture_ids.get(&asset_cache_key(asset)).copied()
}
pub fn is_pending(&self, asset: &EditorAsset) -> bool {
self.pending_keys
.iter()
.any(|key| key == &asset_cache_key(asset))
}
pub fn is_failed(&self, asset: &EditorAsset) -> bool {
self.failed_keys
.iter()
.any(|key| key == &asset_cache_key(asset))
}
}
pub fn prefetch_folder_thumbnails(world: &mut World, folder: &str) {
{
let cache = world.resource::<AssetThumbnailCache>();
if cache.prefetched_folder.as_deref() == Some(folder) {
return;
}
}
let requests: Vec<(String, String, EditorAssetKind)> = {
let assets = world.resource::<EditorAssets>();
assets
.assets
.iter()
.filter(|asset| asset.folder_path == folder)
.filter(|asset| {
matches!(
asset.kind,
EditorAssetKind::Texture | EditorAssetKind::Model
)
})
.filter_map(|asset| {
Some((
asset_cache_key(asset),
asset.path.clone()?,
asset.kind.clone(),
))
})
.collect()
};
let asset_server = world.resource::<AssetServer>().clone();
world.resource_scope(|world, mut cache: Mut<AssetThumbnailCache>| {
world.resource_scope(|_world, mut studio: Mut<ThumbnailStudio>| {
for (key, path, kind) in requests {
match kind {
EditorAssetKind::Texture => cache.request_texture(key, path, &asset_server),
EditorAssetKind::Model => {
cache.request_model(key, path, &asset_server, &mut studio)
}
_ => {}
}
}
});
});
world
.resource_mut::<AssetThumbnailCache>()
.prefetched_folder = Some(folder.to_string());
}
pub fn invalidate_on_catalog_refresh(world: &mut World) {
world.resource_mut::<AssetThumbnailCache>().invalidate_all();
if !world.contains_resource::<ThumbnailStudio>() {
return;
}
let cleanup = {
let mut studio = world.resource_mut::<ThumbnailStudio>();
studio.clear_queue();
studio.clear_jobs()
};
if let Some(root) = cleanup.active_root {
world.commands().entity(root).despawn_children();
world.commands().entity(root).despawn();
}
}
@@ -0,0 +1,7 @@
//! Thumbnail generation job descriptor.
#[derive(Debug, Clone)]
pub struct ThumbnailJob {
pub cache_key: String,
pub model_path: String,
}
@@ -0,0 +1,26 @@
//! Unified asset thumbnail pipeline (texture fast-path + model studio).
use bevy::prelude::*;
mod cache;
mod job;
mod sources;
mod studio;
pub use cache::{
draw_asset_cell_with, invalidate_on_catalog_refresh, kind_icon, prefetch_folder_thumbnails,
AssetThumbnailCache, AssetThumbnailsPlugin, ThumbnailCacheSnapshot, ThumbnailState,
};
pub use job::ThumbnailJob;
pub use sources::{FbxThumbnailSource, GltfThumbnailSource, ThumbnailModelSource};
pub use studio::{
model_file_exists, model_scene_asset_path, ThumbnailStudio, ThumbnailStudioPlugin,
};
pub struct ThumbnailsPlugin;
impl Plugin for ThumbnailsPlugin {
fn build(&self, app: &mut App) {
app.add_plugins((AssetThumbnailsPlugin, ThumbnailStudioPlugin));
}
}
@@ -0,0 +1,123 @@
//! Direct FBX mesh extraction for thumbnail studio (no texture deps).
use bevy::asset::RenderAssetUsages;
use bevy::camera::visibility::RenderLayers;
use bevy::mesh::{Indices, PrimitiveTopology};
use bevy::prelude::*;
use bevy_ufbx::mesh::group_faces_by_material;
use bevy_ufbx::utils::convert_matrix;
use super::ThumbnailModelSource;
use crate::assets::thumbnails::studio::THUMBNAIL_LAYER;
pub struct FbxThumbnailSource;
impl ThumbnailModelSource for FbxThumbnailSource {
fn spawn_preview(
&self,
commands: &mut Commands,
meshes: &mut Assets<Mesh>,
materials: &mut Assets<StandardMaterial>,
root: Entity,
catalog_path: &str,
) -> bool {
let Ok(bytes) = std::fs::read(catalog_path) else {
warn!("FBX thumbnail: could not read {catalog_path}");
return false;
};
let scene = match ufbx::load_memory(
&bytes,
ufbx::LoadOpts {
target_unit_meters: 1.0,
target_axes: ufbx::CoordinateAxes::right_handed_y_up(),
..Default::default()
},
) {
Ok(scene) => scene,
Err(err) => {
warn!("FBX thumbnail: failed to parse {catalog_path}: {err:?}");
return false;
}
};
let material = materials.add(StandardMaterial {
base_color: Color::srgb(0.72, 0.72, 0.75),
..default()
});
let mut spawned = false;
for node in scene.nodes.as_ref().iter() {
let Some(mesh_ref) = node.mesh.as_ref() else {
continue;
};
let ufbx_mesh = mesh_ref.as_ref();
if ufbx_mesh.num_vertices == 0 || ufbx_mesh.faces.as_ref().is_empty() {
continue;
}
for (_material_idx, indices) in group_faces_by_material(ufbx_mesh) {
if indices.is_empty() {
continue;
}
let mesh_handle = meshes.add(build_mesh(ufbx_mesh, &indices));
let transform = Transform::from_matrix(convert_matrix(&node.geometry_to_world));
commands.entity(root).with_children(|parent| {
parent.spawn((
RenderLayers::layer(THUMBNAIL_LAYER),
Mesh3d(mesh_handle),
MeshMaterial3d(material.clone()),
transform,
));
});
spawned = true;
}
}
if !spawned {
warn!("FBX thumbnail: no renderable meshes in {catalog_path}");
}
spawned
}
}
fn build_mesh(ufbx_mesh: &ufbx::Mesh, indices: &[u32]) -> Mesh {
let mut mesh = Mesh::new(
PrimitiveTopology::TriangleList,
RenderAssetUsages::default(),
);
let positions: Vec<[f32; 3]> = ufbx_mesh
.vertex_position
.values
.as_ref()
.iter()
.map(|v| [v.x as f32, v.y as f32, v.z as f32])
.collect();
mesh.insert_attribute(Mesh::ATTRIBUTE_POSITION, positions);
if ufbx_mesh.vertex_normal.exists {
let normals: Vec<[f32; 3]> = (0..ufbx_mesh.num_vertices)
.map(|i| {
let n = ufbx_mesh.vertex_normal[i];
[n.x as f32, n.y as f32, n.z as f32]
})
.collect();
mesh.insert_attribute(Mesh::ATTRIBUTE_NORMAL, normals);
}
if ufbx_mesh.vertex_uv.exists {
let uvs: Vec<[f32; 2]> = (0..ufbx_mesh.num_vertices)
.map(|i| {
let uv = ufbx_mesh.vertex_uv[i];
[uv.x as f32, uv.y as f32]
})
.collect();
mesh.insert_attribute(Mesh::ATTRIBUTE_UV_0, uvs);
}
mesh.insert_indices(Indices::U32(indices.to_vec()));
mesh
}
@@ -0,0 +1,82 @@
//! glTF/GLB fast-path texture extraction for asset browser thumbnails.
use std::path::Path;
/// Returns an asset-server path for the first base-color texture referenced by a glTF/GLB file.
///
/// Embedded GLB buffers are skipped so callers can fall back to the render studio.
pub fn gltf_base_color_texture_path(model_asset_path: &str) -> Option<String> {
let model_path = Path::new(model_asset_path);
if !is_gltf_path(model_path) {
return None;
}
let (document, ..) = gltf::import(model_path).ok()?;
for material in document.materials() {
let Some(tex_info) = material.pbr_metallic_roughness().base_color_texture() else {
continue;
};
let texture = document.textures().nth(tex_info.texture().index())?;
let image = document.images().nth(texture.source().index())?;
let uri = match image.source() {
gltf::image::Source::Uri { uri, .. } => uri,
gltf::image::Source::View { .. } => continue,
};
if let Some(path) = resolve_texture_uri(model_path, uri) {
return Some(path);
}
}
None
}
pub struct GltfThumbnailSource;
fn is_gltf_path(path: &Path) -> bool {
path.extension()
.and_then(|ext| ext.to_str())
.is_some_and(|ext| matches!(ext.to_ascii_lowercase().as_str(), "gltf" | "glb"))
}
fn resolve_texture_uri(model_path: &Path, uri: &str) -> Option<String> {
if uri.starts_with("data:") {
return None;
}
let model_dir = model_path.parent()?;
let texture_path = model_dir.join(uri);
normalize_asset_path(&texture_path)
}
fn normalize_asset_path(path: &Path) -> Option<String> {
let raw = path.to_string_lossy().replace('\\', "/");
if raw.starts_with("assets/") {
return Some(raw);
}
let file_name = path.file_name()?.to_str()?;
if file_name.is_empty() {
return None;
}
Some(format!("assets/{file_name}"))
}
#[cfg(test)]
mod tests {
use super::*;
use std::path::PathBuf;
#[test]
fn normalize_asset_path_keeps_assets_prefix() {
assert_eq!(
normalize_asset_path(Path::new("assets/textures/albedo.png")),
Some("assets/textures/albedo.png".into())
);
}
#[test]
fn resolve_texture_uri_relative_to_model() {
let model = PathBuf::from("assets/models/chair.gltf");
assert_eq!(
resolve_texture_uri(&model, "textures/chair_albedo.png"),
Some("assets/models/textures/chair_albedo.png".into())
);
}
}
@@ -0,0 +1,33 @@
//! Model file sources for the thumbnail render studio.
mod fbx;
pub(crate) mod gltf;
pub use fbx::FbxThumbnailSource;
pub use gltf::GltfThumbnailSource;
use bevy::prelude::*;
/// Spawns untextured or scene-root preview content under `root` for the thumbnail studio.
pub trait ThumbnailModelSource: Send + Sync {
fn spawn_preview(
&self,
commands: &mut Commands,
meshes: &mut Assets<Mesh>,
materials: &mut Assets<StandardMaterial>,
root: Entity,
catalog_path: &str,
) -> bool;
}
pub fn source_for_extension(path: &str) -> Option<&'static dyn ThumbnailModelSource> {
if path.ends_with(".fbx") {
Some(&FbxThumbnailSource)
} else {
None
}
}
pub fn uses_scene_root(path: &str) -> bool {
!path.ends_with(".fbx")
}
@@ -0,0 +1,544 @@
//! Offscreen model thumbnail studio for FBX and untextured glTF assets.
use std::collections::VecDeque;
use std::path::Path;
use bevy::camera::visibility::RenderLayers;
use bevy::camera::RenderTarget;
use bevy::gltf::GltfAssetLabel;
use bevy::math::bounding::Aabb3d;
use bevy::mesh::VertexAttributeValues;
use bevy::prelude::*;
use bevy::render::render_resource::TextureFormat;
use bevy::scene::SceneRoot;
use bevy_egui::EguiUserTextures;
use shared::ModelRef;
use super::cache::AssetThumbnailCache;
use super::job::ThumbnailJob;
use super::sources::{source_for_extension, uses_scene_root};
use crate::assets::asset_server_path;
use crate::infra::EditorOnly;
pub(crate) const THUMB_SIZE: u32 = 128;
pub(crate) const THUMBNAIL_LAYER: usize = 31;
const MESH_WARMUP_FRAMES: u8 = 12;
const POST_ATTACH_FRAMES: u8 = 8;
const RENDER_FRAMES: u8 = 3;
const COOLDOWN_FRAMES: u8 = 2;
const LOAD_TIMEOUT_FRAMES: u32 = 240;
#[derive(Component)]
struct ThumbnailStudioCamera;
#[derive(Component)]
struct ThumbnailStudioLight;
#[derive(Component)]
struct ThumbnailStudioLayer;
#[derive(Component)]
struct ThumbnailSceneRoot;
#[derive(Resource)]
pub struct ThumbnailStudio {
camera: Entity,
render_image: Handle<Image>,
_lights: Vec<Entity>,
queue: VecDeque<ThumbnailJob>,
active: Option<ActiveModelThumbnail>,
cooldown_frames: u8,
}
struct ActiveModelThumbnail {
cache_key: String,
model_path: String,
root: Entity,
meshes_ready: bool,
mesh_warmup_frames: u8,
camera_active: bool,
post_attach_frames: u8,
framed: bool,
frames_remaining: u8,
wait_frames: u32,
}
pub struct ThumbnailStudioPlugin;
impl Plugin for ThumbnailStudioPlugin {
fn build(&self, app: &mut App) {
app.add_systems(Startup, setup_thumbnail_studio)
.add_systems(PostUpdate, apply_thumbnail_studio_layers)
.add_systems(Last, process_thumbnail_studio);
}
}
impl ThumbnailStudio {
pub fn enqueue(&mut self, cache_key: String, model_path: String) -> bool {
if self
.active
.as_ref()
.is_some_and(|active| active.cache_key == cache_key)
{
return false;
}
if self.queue.iter().any(|job| job.cache_key == cache_key) {
return false;
}
self.queue.push_back(ThumbnailJob {
cache_key,
model_path,
});
true
}
pub fn clear_queue(&mut self) {
self.queue.clear();
self.cooldown_frames = 0;
}
pub fn clear_jobs(&mut self) -> StudioCleanup {
StudioCleanup {
camera: self.camera,
active_root: self.active.take().map(|active| active.root),
}
}
}
pub struct StudioCleanup {
pub camera: Entity,
pub active_root: Option<Entity>,
}
pub fn model_scene_asset_path(path: &str, scene_index: usize) -> String {
let path = asset_server_path(path);
if path.ends_with(".fbx") {
ModelRef::fbx_scene_asset_path(&path, scene_index)
} else {
GltfAssetLabel::Scene(scene_index)
.from_asset(path)
.to_string()
}
}
fn setup_thumbnail_studio(mut commands: Commands, mut images: ResMut<Assets<Image>>) {
let render_image = images.add(Image::new_target_texture(
THUMB_SIZE,
THUMB_SIZE,
TextureFormat::Rgba8UnormSrgb,
None,
));
let camera = commands
.spawn((
Name::new("Thumbnail Studio Camera"),
EditorOnly,
ThumbnailStudioCamera,
ThumbnailStudioLayer,
RenderLayers::layer(THUMBNAIL_LAYER),
Camera3d::default(),
Camera {
is_active: false,
order: -50,
clear_color: ClearColorConfig::Custom(Color::srgb(0.12, 0.12, 0.14)),
..default()
},
RenderTarget::Image(render_image.clone().into()),
Transform::from_xyz(2.0, 1.4, 2.0).looking_at(Vec3::new(0.0, 0.5, 0.0), Vec3::Y),
Projection::Perspective(PerspectiveProjection {
fov: 40.0_f32.to_radians(),
..default()
}),
))
.id();
let key_light = commands
.spawn((
EditorOnly,
ThumbnailStudioLight,
ThumbnailStudioLayer,
RenderLayers::layer(THUMBNAIL_LAYER),
DirectionalLight {
illuminance: 12_000.0,
shadows_enabled: false,
..default()
},
Transform::from_rotation(Quat::from_euler(EulerRot::XYZ, -0.8, 0.9, 0.0)),
))
.id();
let fill_light = commands
.spawn((
EditorOnly,
ThumbnailStudioLight,
ThumbnailStudioLayer,
RenderLayers::layer(THUMBNAIL_LAYER),
DirectionalLight {
illuminance: 3_500.0,
shadows_enabled: false,
..default()
},
Transform::from_rotation(Quat::from_euler(EulerRot::XYZ, -0.4, -2.2, 0.0)),
))
.id();
commands.insert_resource(ThumbnailStudio {
camera,
render_image,
_lights: vec![key_light, fill_light],
queue: VecDeque::new(),
active: None,
cooldown_frames: 0,
});
}
#[allow(clippy::too_many_arguments)]
fn process_thumbnail_studio(
mut commands: Commands,
mut studio: ResMut<ThumbnailStudio>,
mut cache: ResMut<AssetThumbnailCache>,
mut textures: ResMut<EguiUserTextures>,
mut materials: ResMut<Assets<StandardMaterial>>,
mut mesh_storage: ResMut<Assets<Mesh>>,
asset_server: Res<AssetServer>,
mut cameras: Query<&mut Camera, With<ThumbnailStudioCamera>>,
mut camera_transforms: Query<&mut Transform, With<ThumbnailStudioCamera>>,
children: Query<&Children>,
transforms: Query<&GlobalTransform>,
mesh3d: Query<&Mesh3d>,
) {
if studio.cooldown_frames > 0 {
studio.cooldown_frames -= 1;
return;
}
if let Some(mut active) = studio.active.take() {
if !active.framed {
active.wait_frames += 1;
if !active.meshes_ready {
if thumbnail_meshes_present(active.root, &children, &mesh3d, &mesh_storage) {
active.meshes_ready = true;
active.mesh_warmup_frames = 0;
}
} else if active.mesh_warmup_frames < MESH_WARMUP_FRAMES {
active.mesh_warmup_frames += 1;
} else if frame_thumbnail_scene(
active.root,
&children,
&transforms,
&mesh3d,
&mesh_storage,
&mut camera_transforms,
) {
active.framed = true;
active.post_attach_frames = 0;
studio.active = Some(active);
return;
}
if active.wait_frames >= LOAD_TIMEOUT_FRAMES {
warn!(
"Model thumbnail timed out framing {} (meshes may still be loading)",
active.model_path
);
fail_active_thumbnail(
&mut commands,
&mut studio,
&mut cache,
&mut cameras,
active,
"load timeout",
true,
);
} else {
studio.active = Some(active);
}
return;
}
if !active.camera_active {
active.post_attach_frames += 1;
if active.post_attach_frames >= POST_ATTACH_FRAMES {
if let Ok(mut camera) = cameras.get_mut(studio.camera) {
camera.is_active = true;
}
active.camera_active = true;
active.frames_remaining = RENDER_FRAMES;
}
studio.active = Some(active);
return;
}
if active.camera_active {
if active.frames_remaining > 0 {
active.frames_remaining -= 1;
studio.active = Some(active);
} else {
cache.complete_studio_thumbnail(
&active.cache_key,
studio.render_image.clone(),
&mut textures,
);
finish_active_thumbnail(&mut commands, &mut studio, &mut cameras, active);
}
return;
}
studio.active = Some(active);
return;
}
let Some(job) = studio.queue.pop_front() else {
deactivate_studio_camera(&mut cameras, studio.camera);
return;
};
let mut root_entity = commands.spawn((
EditorOnly,
ThumbnailSceneRoot,
ThumbnailStudioLayer,
RenderLayers::layer(THUMBNAIL_LAYER),
Transform::default(),
));
if uses_scene_root(&job.model_path) {
root_entity.insert(SceneRoot(
asset_server.load(model_scene_asset_path(&job.model_path, 0)),
));
}
let root = root_entity.id();
let content_spawned = if let Some(source) = source_for_extension(&job.model_path) {
source.spawn_preview(
&mut commands,
&mut mesh_storage,
&mut materials,
root,
&job.model_path,
)
} else {
uses_scene_root(&job.model_path)
};
if source_for_extension(&job.model_path).is_some() && !content_spawned {
fail_active_thumbnail(
&mut commands,
&mut studio,
&mut cache,
&mut cameras,
ActiveModelThumbnail {
cache_key: job.cache_key,
model_path: job.model_path,
root,
meshes_ready: false,
mesh_warmup_frames: 0,
camera_active: false,
post_attach_frames: 0,
framed: false,
frames_remaining: 0,
wait_frames: 0,
},
"no renderable meshes",
true,
);
return;
}
studio.active = Some(ActiveModelThumbnail {
cache_key: job.cache_key,
model_path: job.model_path,
root,
meshes_ready: false,
mesh_warmup_frames: 0,
camera_active: false,
post_attach_frames: 0,
framed: false,
frames_remaining: 0,
wait_frames: 0,
});
}
fn finish_active_thumbnail(
commands: &mut Commands,
studio: &mut ThumbnailStudio,
cameras: &mut Query<&mut Camera, With<ThumbnailStudioCamera>>,
active: ActiveModelThumbnail,
) {
despawn_thumbnail_root(commands, active.root);
deactivate_studio_camera(cameras, studio.camera);
studio.cooldown_frames = COOLDOWN_FRAMES;
}
fn fail_active_thumbnail(
commands: &mut Commands,
studio: &mut ThumbnailStudio,
cache: &mut AssetThumbnailCache,
cameras: &mut Query<&mut Camera, With<ThumbnailStudioCamera>>,
active: ActiveModelThumbnail,
reason: &str,
retryable: bool,
) {
cache.mark_studio_failed(&active.cache_key, reason, retryable);
finish_active_thumbnail(commands, studio, cameras, active);
}
fn apply_thumbnail_studio_layers(
mut commands: Commands,
roots: Query<Entity, With<ThumbnailSceneRoot>>,
children: Query<&Children>,
tagged: Query<(), With<ThumbnailStudioLayer>>,
) {
for root in &roots {
let mut stack = vec![root];
while let Some(entity) = stack.pop() {
if tagged.get(entity).is_err() {
commands
.entity(entity)
.insert((ThumbnailStudioLayer, RenderLayers::layer(THUMBNAIL_LAYER)));
}
if let Ok(kids) = children.get(entity) {
stack.extend(kids.iter());
}
}
}
}
fn deactivate_studio_camera(
cameras: &mut Query<&mut Camera, With<ThumbnailStudioCamera>>,
camera: Entity,
) {
if let Ok(mut camera) = cameras.get_mut(camera) {
camera.is_active = false;
}
}
fn despawn_thumbnail_root(commands: &mut Commands, root: Entity) {
commands.entity(root).despawn_children();
commands.entity(root).despawn();
}
fn thumbnail_meshes_present(
root: Entity,
children: &Query<&Children>,
meshes: &Query<&Mesh3d>,
mesh_assets: &Assets<Mesh>,
) -> bool {
let mut entities = Vec::new();
collect_descendants(root, children, &mut entities);
entities.iter().any(|&entity| {
let Ok(mesh3d) = meshes.get(entity) else {
return false;
};
mesh_assets
.get(&mesh3d.0)
.is_some_and(|mesh| mesh_positions(mesh).next().is_some())
})
}
fn mesh_positions(mesh: &Mesh) -> impl Iterator<Item = [f32; 3]> + '_ {
let positions = mesh
.attribute(Mesh::ATTRIBUTE_POSITION)
.and_then(|values| match values {
VertexAttributeValues::Float32x3(positions) => Some(positions.as_slice()),
_ => None,
});
positions
.into_iter()
.flat_map(|slice| slice.iter().copied())
}
fn frame_thumbnail_scene(
root: Entity,
children: &Query<&Children>,
transforms: &Query<&GlobalTransform>,
meshes: &Query<&Mesh3d>,
mesh_assets: &Assets<Mesh>,
camera_transforms: &mut Query<&mut Transform, With<ThumbnailStudioCamera>>,
) -> bool {
let mut entities = Vec::new();
collect_descendants(root, children, &mut entities);
let mut min = Vec3::splat(f32::INFINITY);
let mut max = Vec3::splat(f32::NEG_INFINITY);
let mut found_mesh = false;
for entity in entities {
let Ok(mesh3d) = meshes.get(entity) else {
continue;
};
let Ok(global) = transforms.get(entity) else {
continue;
};
if let Some(mesh) = mesh_assets.get(&mesh3d.0) {
let mut local_min = Vec3::splat(f32::INFINITY);
let mut local_max = Vec3::splat(f32::NEG_INFINITY);
let mut has_positions = false;
for position in mesh_positions(mesh) {
let p = Vec3::from_array(position);
local_min = local_min.min(p);
local_max = local_max.max(p);
has_positions = true;
}
if has_positions {
found_mesh = true;
for corner in aabb_corners(&Aabb3d::from_min_max(
Vec3A::from(local_min),
Vec3A::from(local_max),
)) {
let world = global.transform_point(corner);
min = min.min(world);
max = max.max(world);
}
}
}
}
if !found_mesh {
return false;
}
let center = (min + max) * 0.5;
let radius = (max - min).length().max(0.25) * 0.5;
let distance = radius / (20.0_f32.to_radians()).tan() * 1.35;
let eye = center + Vec3::new(1.0, 0.75, 1.0).normalize() * distance;
if let Ok(mut transform) = camera_transforms.single_mut() {
*transform = Transform::from_translation(eye).looking_at(center, Vec3::Y);
}
true
}
fn collect_descendants(entity: Entity, children: &Query<&Children>, out: &mut Vec<Entity>) {
out.push(entity);
let Ok(child_list) = children.get(entity) else {
return;
};
for child in child_list.iter() {
collect_descendants(child, children, out);
}
}
fn aabb_corners(aabb: &Aabb3d) -> [Vec3; 8] {
let min = Vec3::from(aabb.min);
let max = Vec3::from(aabb.max);
[
Vec3::new(min.x, min.y, min.z),
Vec3::new(max.x, min.y, min.z),
Vec3::new(min.x, max.y, min.z),
Vec3::new(max.x, max.y, min.z),
Vec3::new(min.x, min.y, max.z),
Vec3::new(max.x, min.y, max.z),
Vec3::new(min.x, max.y, max.z),
Vec3::new(max.x, max.y, max.z),
]
}
/// Skip studio jobs when the source file is missing on disk.
pub fn model_file_exists(catalog_path: &str) -> bool {
Path::new(catalog_path).is_file()
}