Expand asset browser subasset workflow
CI / Format, lint, test, build (push) Waiting to run

This commit is contained in:
Rbanh committed 2026-06-06 01:38:27 -04:00
1 parent f29712d158
commit 3e053a81ab
123 files changed
+31930 -1404

No files matched your search

@@ -0,0 +1,24 @@
#import bevy_pbr::forward_io::VertexOutput
struct ActorIconOverlayMaterial {
brightness: f32,
}
@group(#{MATERIAL_BIND_GROUP}) @binding(0)
var icon_texture: texture_2d<f32>;
@group(#{MATERIAL_BIND_GROUP}) @binding(1)
var icon_sampler: sampler;
@group(#{MATERIAL_BIND_GROUP}) @binding(2)
var<uniform> material: ActorIconOverlayMaterial;
@fragment
fn fragment(in: VertexOutput) -> @location(0) vec4<f32> {
let texel = textureSample(icon_texture, icon_sampler, in.uv);
if texel.a < 0.01 {
discard;
}
return vec4(texel.rgb * material.brightness, texel.a);
}
+160 -2
View File
@@ -11,7 +11,8 @@ use shared::{
use walkdir::WalkDir;
use crate::asset_db::{
find_asset_by_path, find_asset_mut_by_path, AssetRegistry, ModelPlacementMode,
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,
@@ -21,10 +22,24 @@ use crate::history::{spawn_with_history, EditorEntitySnapshot};
pub const BUILTINS_FOLDER: &str = "__builtins__";
pub const ASSETS_ROOT: &str = "assets";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum AssetSubAssetKind {
Mesh,
Material,
Texture,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum AssetSelection {
Builtin(String),
File(String),
SubAsset {
parent_path: String,
sub_asset_id: String,
label: String,
kind: AssetSubAssetKind,
source_path: Option<String>,
},
}
impl AssetSelection {
@@ -34,6 +49,21 @@ impl AssetSelection {
None => AssetSelection::Builtin(asset.label.clone()),
}
}
pub fn parent_path(&self) -> Option<&str> {
match self {
AssetSelection::Builtin(_) => None,
AssetSelection::File(path) => Some(path),
AssetSelection::SubAsset { parent_path, .. } => Some(parent_path),
}
}
pub fn display_label(&self) -> &str {
match self {
AssetSelection::Builtin(label) | AssetSelection::File(label) => label,
AssetSelection::SubAsset { label, .. } => label,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -137,6 +167,10 @@ impl EditorAssets {
.assets
.iter()
.find(|asset| asset.path.as_deref() == Some(path.as_str())),
AssetSelection::SubAsset { parent_path, .. } => self
.assets
.iter()
.find(|asset| asset.path.as_deref() == Some(parent_path.as_str())),
}
}
@@ -152,10 +186,20 @@ impl EditorAssets {
.and_then(|selection| self.asset_for_selection(selection))
}
pub fn dragging_selection(&self) -> Option<&AssetSelection> {
self.dragging.as_ref()
}
pub fn select(&mut self, selection: AssetSelection) {
if let Some(asset) = self.asset_for_selection(&selection).cloned() {
let selected_label = match &selection {
AssetSelection::SubAsset { label, kind, .. } => {
format!("{kind:?}: {label}")
}
_ => asset.label.clone(),
};
self.selected = Some(selection);
self.status = format!("Selected {}", asset.label);
self.status = format!("Selected {selected_label}");
}
}
@@ -302,6 +346,7 @@ fn should_skip_asset_path(path: &Path) -> bool {
let normalized = normalize_asset_path(path);
normalized == "assets/project.ron"
|| normalized.starts_with("assets/.index/")
|| normalized.starts_with("assets/.trash/")
|| normalized.starts_with(crate::assets::static_mesh::STATIC_MESH_ARTIFACT_DIR)
}
@@ -543,6 +588,101 @@ pub fn spawn_asset_at(world: &mut World, asset: &EditorAsset, translation: Vec3)
Some(spawn_with_history(world, snapshot))
}
pub fn spawn_subasset_at(
world: &mut World,
selection: &AssetSelection,
translation: Vec3,
) -> Option<Entity> {
let AssetSelection::SubAsset {
parent_path,
sub_asset_id,
label,
kind: AssetSubAssetKind::Mesh,
..
} = selection
else {
return None;
};
let record = world
.get_resource::<AssetRegistry>()
.and_then(|registry| find_asset_by_path(registry, parent_path))?;
let manifest_path = record
.import_settings
.static_mesh_manifest_path
.as_deref()?;
let manifest = load_static_mesh_manifest(manifest_path).ok()?;
let part = manifest
.parts
.iter()
.find(|part| part_effective_id_for_selection(part) == *sub_asset_id)?;
let mesh_ref = shared::EditorAssetRef::new(
manifest.asset_id.clone(),
sub_asset_id.clone(),
label.clone(),
);
let material = matches!(
record.import_settings.material_policy,
MaterialImportPolicy::SourceMaterials
)
.then(|| {
part_effective_material_id_for_selection(part).map(|id| {
shared::EditorAssetRef::new(
manifest.asset_id.clone(),
id,
part.material_slot_name.clone(),
)
})
})
.flatten();
let slot = shared::StaticMeshRendererEntry {
id: shared::ComponentInstanceId::new("slot:0"),
name: label.clone(),
mesh: mesh_ref.clone(),
material,
local_transform: part.local_transform,
visible: true,
cast_shadows: true,
receive_shadows: true,
};
let mut snapshot = EditorEntitySnapshot {
actor_id: None,
actor_kind: ActorKind::StaticMesh,
actor_name: None,
name: Some(label.clone()),
transform: Transform::from_translation(translation + Vec3::Y * 0.1),
primitive: None,
static_mesh_renderer: Some(shared::StaticMeshRenderer::single(slot)),
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(),
};
snapshot.transform.scale *= record.import_settings.scale;
if record.import_settings.generate_collider {
snapshot.rigid_body = Some(RigidBodyDesc::default());
snapshot.collider = Some(ColliderDesc::static_mesh(vec![mesh_ref]));
}
Some(spawn_with_history(world, snapshot))
}
fn apply_static_mesh_placement_mode(
snapshot: &mut EditorEntitySnapshot,
renderer: shared::StaticMeshRenderer,
@@ -619,6 +759,24 @@ fn static_mesh_collider_for_renderer(renderer: &shared::StaticMeshRenderer) -> C
)
}
fn part_effective_id_for_selection(part: &crate::assets::static_mesh::StaticMeshPart) -> String {
if part.id.trim().is_empty() {
crate::assets::static_mesh::part_id_from_label(&part.mesh_label)
} else {
part.id.clone()
}
}
fn part_effective_material_id_for_selection(
part: &crate::assets::static_mesh::StaticMeshPart,
) -> Option<String> {
part.material_id.clone().or_else(|| {
part.material_label
.as_ref()
.map(|label| crate::assets::static_mesh::material_id_from_label(label))
})
}
fn static_mesh_renderer_for_asset(
world: &mut World,
path: &str,
+1 -1
View File
@@ -11,5 +11,5 @@ 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,
AssetThumbnailCache, ThumbnailCacheSnapshot, ThumbnailState, ThumbnailStudio, ThumbnailsPlugin,
};
+108 -1
View File
@@ -8,6 +8,7 @@ use egui_phosphor_icons::icons;
use super::sources::gltf::gltf_base_color_texture_path;
use super::studio::{model_file_exists, ThumbnailStudio};
use super::ThumbnailJobSource;
use crate::assets::{
asset_cache_key, asset_server_path, EditorAsset, EditorAssetKind, EditorAssets,
};
@@ -114,6 +115,97 @@ impl AssetThumbnailCache {
}
}
pub fn request_mesh_subasset(
&mut self,
key: String,
model_path: String,
mesh_label: String,
material_label: Option<String>,
studio: &mut ThumbnailStudio,
) {
if matches!(
self.state(&key),
Some(ThumbnailState::Ready | ThumbnailState::Pending)
) || self.failed.contains_key(&key)
{
return;
}
if !model_file_exists(&model_path) {
self.mark_studio_failed(&key, "file not found", false);
return;
}
if studio.enqueue_source(
key.clone(),
ThumbnailJobSource::MeshSubAsset {
model_path,
mesh_label,
material_label,
},
) {
self.studio_pending.insert(key);
}
}
pub fn request_source_material(
&mut self,
key: String,
model_path: String,
material_label: String,
studio: &mut ThumbnailStudio,
) {
if matches!(
self.state(&key),
Some(ThumbnailState::Ready | ThumbnailState::Pending)
) || self.failed.contains_key(&key)
{
return;
}
if !model_file_exists(&model_path) {
self.mark_studio_failed(&key, "file not found", false);
return;
}
if studio.enqueue_source(
key.clone(),
ThumbnailJobSource::SourceMaterial {
model_path,
material_label,
},
) {
self.studio_pending.insert(key);
}
}
pub fn request_material_asset(
&mut self,
key: String,
path: String,
studio: &mut ThumbnailStudio,
) {
if matches!(
self.state(&key),
Some(ThumbnailState::Ready | ThumbnailState::Pending)
) || self.failed.contains_key(&key)
{
return;
}
let material = match shared::MaterialAsset::load_from_path(&path) {
Ok(asset) => asset,
Err(error) => {
self.mark_studio_failed(&key, &error, true);
return;
}
};
if studio.enqueue_source(
key.clone(),
ThumbnailJobSource::MaterialAsset {
label: material.label.clone(),
material: material.material,
},
) {
self.studio_pending.insert(key);
}
}
pub(crate) fn complete_studio_thumbnail(
&mut self,
key: &str,
@@ -297,6 +389,18 @@ pub struct ThumbnailCacheSnapshot {
}
impl ThumbnailCacheSnapshot {
pub fn texture_for_key(&self, key: &str) -> Option<egui::TextureId> {
self.texture_ids.get(key).copied()
}
pub fn is_pending_key(&self, key: &str) -> bool {
self.pending_keys.iter().any(|pending| pending == key)
}
pub fn is_failed_key(&self, key: &str) -> bool {
self.failed_keys.iter().any(|failed| failed == key)
}
pub fn texture_for(&self, asset: &EditorAsset) -> Option<egui::TextureId> {
self.texture_ids.get(&asset_cache_key(asset)).copied()
}
@@ -331,7 +435,7 @@ pub fn prefetch_folder_thumbnails(world: &mut World, folder: &str) {
.filter(|asset| {
matches!(
asset.kind,
EditorAssetKind::Texture | EditorAssetKind::Model
EditorAssetKind::Texture | EditorAssetKind::Model | EditorAssetKind::Material
)
})
.filter_map(|asset| {
@@ -352,6 +456,9 @@ pub fn prefetch_folder_thumbnails(world: &mut World, folder: &str) {
EditorAssetKind::Model => {
cache.request_model(key, path, &asset_server, &mut studio)
}
EditorAssetKind::Material => {
cache.request_material_asset(key, path, &mut studio)
}
_ => {}
}
}
+34 -1
View File
@@ -1,7 +1,40 @@
//! Thumbnail generation job descriptor.
use shared::MaterialDesc;
#[derive(Debug, Clone)]
pub struct ThumbnailJob {
pub cache_key: String,
pub model_path: String,
pub source: ThumbnailJobSource,
}
#[derive(Debug, Clone)]
pub enum ThumbnailJobSource {
Model {
model_path: String,
},
MeshSubAsset {
model_path: String,
mesh_label: String,
material_label: Option<String>,
},
SourceMaterial {
model_path: String,
material_label: String,
},
MaterialAsset {
label: String,
material: MaterialDesc,
},
}
impl ThumbnailJobSource {
pub fn label(&self) -> &str {
match self {
Self::Model { model_path }
| Self::MeshSubAsset { model_path, .. }
| Self::SourceMaterial { model_path, .. } => model_path,
Self::MaterialAsset { label, .. } => label,
}
}
}
+1 -1
View File
@@ -11,7 +11,7 @@ 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 job::{ThumbnailJob, ThumbnailJobSource};
pub use sources::{FbxThumbnailSource, GltfThumbnailSource, ThumbnailModelSource};
pub use studio::{
model_file_exists, model_scene_asset_path, ThumbnailStudio, ThumbnailStudioPlugin,
+168 -44
View File
@@ -12,10 +12,10 @@ use bevy::prelude::*;
use bevy::render::render_resource::TextureFormat;
use bevy::scene::SceneRoot;
use bevy_egui::EguiUserTextures;
use shared::ModelRef;
use shared::{material_from_desc, ModelRef};
use super::cache::AssetThumbnailCache;
use super::job::ThumbnailJob;
use super::job::{ThumbnailJob, ThumbnailJobSource};
use super::sources::{source_for_extension, uses_scene_root};
use crate::assets::asset_server_path;
use crate::infra::EditorOnly;
@@ -52,7 +52,8 @@ pub struct ThumbnailStudio {
struct ActiveModelThumbnail {
cache_key: String,
model_path: String,
label: String,
render_image: Handle<Image>,
root: Entity,
meshes_ready: bool,
mesh_warmup_frames: u8,
@@ -75,6 +76,10 @@ impl Plugin for ThumbnailStudioPlugin {
impl ThumbnailStudio {
pub fn enqueue(&mut self, cache_key: String, model_path: String) -> bool {
self.enqueue_source(cache_key, ThumbnailJobSource::Model { model_path })
}
pub fn enqueue_source(&mut self, cache_key: String, source: ThumbnailJobSource) -> bool {
if self
.active
.as_ref()
@@ -85,10 +90,7 @@ impl ThumbnailStudio {
if self.queue.iter().any(|job| job.cache_key == cache_key) {
return false;
}
self.queue.push_back(ThumbnailJob {
cache_key,
model_path,
});
self.queue.push_back(ThumbnailJob { cache_key, source });
true
}
@@ -122,12 +124,7 @@ pub fn model_scene_asset_path(path: &str, scene_index: usize) -> 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 render_image = images.add(studio_render_image());
let camera = commands
.spawn((
@@ -200,8 +197,10 @@ fn process_thumbnail_studio(
mut textures: ResMut<EguiUserTextures>,
mut materials: ResMut<Assets<StandardMaterial>>,
mut mesh_storage: ResMut<Assets<Mesh>>,
mut images: ResMut<Assets<Image>>,
asset_server: Res<AssetServer>,
mut cameras: Query<&mut Camera, With<ThumbnailStudioCamera>>,
mut camera_targets: Query<&mut RenderTarget, With<ThumbnailStudioCamera>>,
mut camera_transforms: Query<&mut Transform, With<ThumbnailStudioCamera>>,
children: Query<&Children>,
transforms: Query<&GlobalTransform>,
@@ -240,13 +239,14 @@ fn process_thumbnail_studio(
if active.wait_frames >= LOAD_TIMEOUT_FRAMES {
warn!(
"Model thumbnail timed out framing {} (meshes may still be loading)",
active.model_path
active.label
);
fail_active_thumbnail(
&mut commands,
&mut studio,
&mut cache,
&mut cameras,
&mut camera_targets,
active,
"load timeout",
true,
@@ -277,10 +277,16 @@ fn process_thumbnail_studio(
} else {
cache.complete_studio_thumbnail(
&active.cache_key,
studio.render_image.clone(),
active.render_image.clone(),
&mut textures,
);
finish_active_thumbnail(&mut commands, &mut studio, &mut cameras, active);
finish_active_thumbnail(
&mut commands,
&mut studio,
&mut cameras,
&mut camera_targets,
active,
);
}
return;
}
@@ -294,43 +300,45 @@ fn process_thumbnail_studio(
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 render_image = images.add(studio_render_image());
if let Ok(mut target) = camera_targets.get_mut(studio.camera) {
*target = RenderTarget::Image(render_image.clone().into());
}
if let Ok(mut camera) = cameras.get_mut(studio.camera) {
camera.is_active = false;
}
let root = root_entity.id();
let root = commands
.spawn((
EditorOnly,
ThumbnailSceneRoot,
ThumbnailStudioLayer,
RenderLayers::layer(THUMBNAIL_LAYER),
Transform::default(),
))
.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)
};
let label = job.source.label().to_string();
let content_spawned = spawn_thumbnail_job_content(
&mut commands,
&mut mesh_storage,
&mut materials,
&asset_server,
root,
&job.source,
);
if source_for_extension(&job.model_path).is_some() && !content_spawned {
if !content_spawned {
fail_active_thumbnail(
&mut commands,
&mut studio,
&mut cache,
&mut cameras,
&mut camera_targets,
ActiveModelThumbnail {
cache_key: job.cache_key,
model_path: job.model_path,
label,
render_image,
root,
meshes_ready: false,
mesh_warmup_frames: 0,
@@ -348,7 +356,8 @@ fn process_thumbnail_studio(
studio.active = Some(ActiveModelThumbnail {
cache_key: job.cache_key,
model_path: job.model_path,
label,
render_image,
root,
meshes_ready: false,
mesh_warmup_frames: 0,
@@ -360,13 +369,127 @@ fn process_thumbnail_studio(
});
}
fn spawn_thumbnail_job_content(
commands: &mut Commands,
mesh_storage: &mut Assets<Mesh>,
materials: &mut Assets<StandardMaterial>,
asset_server: &AssetServer,
root: Entity,
source: &ThumbnailJobSource,
) -> bool {
match source {
ThumbnailJobSource::Model { model_path } => {
if uses_scene_root(model_path) {
commands.entity(root).insert(SceneRoot(
asset_server.load(model_scene_asset_path(model_path, 0)),
));
}
if let Some(source) = source_for_extension(model_path) {
source.spawn_preview(commands, mesh_storage, materials, root, model_path)
} else {
uses_scene_root(model_path)
}
}
ThumbnailJobSource::MeshSubAsset {
model_path,
mesh_label,
material_label,
} => spawn_mesh_subasset_preview(
commands,
materials,
asset_server,
root,
model_path,
mesh_label,
material_label.as_deref(),
),
ThumbnailJobSource::SourceMaterial {
model_path,
material_label,
} => spawn_material_sphere(
commands,
mesh_storage,
root,
asset_server.load(labeled_asset_path(
&asset_server_path(model_path),
material_label,
)),
),
ThumbnailJobSource::MaterialAsset { material, .. } => {
let material = materials.add(material_from_desc(asset_server, material));
spawn_material_sphere(commands, mesh_storage, root, material)
}
}
}
fn spawn_mesh_subasset_preview(
commands: &mut Commands,
materials: &mut Assets<StandardMaterial>,
asset_server: &AssetServer,
root: Entity,
model_path: &str,
mesh_label: &str,
material_label: Option<&str>,
) -> bool {
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))
} else {
materials.add(StandardMaterial {
base_color: Color::srgb(0.72, 0.72, 0.75),
perceptual_roughness: 0.65,
..default()
})
};
commands.entity(root).with_children(|parent| {
parent.spawn((
RenderLayers::layer(THUMBNAIL_LAYER),
Mesh3d(mesh),
MeshMaterial3d(material),
Transform::default(),
));
});
true
}
fn spawn_material_sphere(
commands: &mut Commands,
mesh_storage: &mut Assets<Mesh>,
root: Entity,
material: Handle<StandardMaterial>,
) -> bool {
let mesh = mesh_storage.add(Sphere::new(0.65).mesh().uv(48, 24));
commands.entity(root).with_children(|parent| {
parent.spawn((
RenderLayers::layer(THUMBNAIL_LAYER),
Mesh3d(mesh),
MeshMaterial3d(material),
Transform::default(),
));
});
true
}
fn labeled_asset_path(path: &str, label: &str) -> String {
format!("{path}#{label}")
}
fn studio_render_image() -> Image {
Image::new_target_texture(THUMB_SIZE, THUMB_SIZE, TextureFormat::Rgba8UnormSrgb, None)
}
fn finish_active_thumbnail(
commands: &mut Commands,
studio: &mut ThumbnailStudio,
cameras: &mut Query<&mut Camera, With<ThumbnailStudioCamera>>,
camera_targets: &mut Query<&mut RenderTarget, With<ThumbnailStudioCamera>>,
active: ActiveModelThumbnail,
) {
despawn_thumbnail_root(commands, active.root);
if let Ok(mut target) = camera_targets.get_mut(studio.camera) {
*target = RenderTarget::Image(studio.render_image.clone().into());
}
deactivate_studio_camera(cameras, studio.camera);
studio.cooldown_frames = COOLDOWN_FRAMES;
}
@@ -376,12 +499,13 @@ fn fail_active_thumbnail(
studio: &mut ThumbnailStudio,
cache: &mut AssetThumbnailCache,
cameras: &mut Query<&mut Camera, With<ThumbnailStudioCamera>>,
camera_targets: &mut Query<&mut RenderTarget, With<ThumbnailStudioCamera>>,
active: ActiveModelThumbnail,
reason: &str,
retryable: bool,
) {
cache.mark_studio_failed(&active.cache_key, reason, retryable);
finish_active_thumbnail(commands, studio, cameras, active);
finish_active_thumbnail(commands, studio, cameras, camera_targets, active);
}
fn apply_thumbnail_studio_layers(
File diff suppressed because it is too large. Load diff
+32 -1
View File
@@ -3,8 +3,10 @@
use std::collections::HashSet;
use bevy::prelude::*;
use shared::MaterialAsset;
use crate::assets::{ASSETS_ROOT, BUILTINS_FOLDER};
use crate::asset_db::ImportSettings;
use crate::assets::{AssetSelection, ASSETS_ROOT, BUILTINS_FOLDER};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum AssetBrowserView {
@@ -41,6 +43,31 @@ pub struct AssetBrowserUiState {
pub(crate) recursive: bool,
pub(crate) show_details: bool,
pub(crate) expanded_folders: HashSet<String>,
pub(crate) expanded_assets: HashSet<String>,
pub(crate) pending_delete: Option<AssetDeleteRequest>,
pub(crate) import_draft: Option<ImportSettingsDraft>,
pub(crate) material_draft: Option<MaterialAssetDraft>,
}
#[derive(Debug, Clone)]
pub(crate) struct AssetDeleteRequest {
pub(crate) selection: AssetSelection,
pub(crate) label: String,
pub(crate) files: Vec<String>,
pub(crate) warnings: Vec<String>,
}
#[derive(Debug, Clone)]
pub(crate) struct ImportSettingsDraft {
pub(crate) path: String,
pub(crate) settings: ImportSettings,
}
#[derive(Debug, Clone)]
pub(crate) struct MaterialAssetDraft {
pub(crate) path: String,
pub(crate) asset: MaterialAsset,
pub(crate) error: Option<String>,
}
impl Default for AssetBrowserUiState {
@@ -57,6 +84,10 @@ impl Default for AssetBrowserUiState {
recursive: false,
show_details: true,
expanded_folders,
expanded_assets: HashSet::new(),
pending_delete: None,
import_draft: None,
material_draft: None,
}
}
}
+67 -6
View File
@@ -4,12 +4,14 @@ use bevy::prelude::*;
use bevy_egui::{egui, EguiTextureHandle, EguiUserTextures};
use bevy_inspector_egui::bevy_inspector::hierarchy::SelectedEntities;
use egui_phosphor_icons::icons;
use transform_gizmo_bevy::prelude::GizmoOptions;
use crate::assets::EditorAssets;
use crate::assets::{AssetSelection, AssetSubAssetKind, EditorAssets};
use crate::gizmos::{EditorGizmoMode, EditorGizmoSpace};
use crate::render_target::ViewportRenderTarget;
use crate::selection::ViewportClick;
use crate::state::PlayPossession;
use crate::viewport::actor_icons::ActorIconSettings;
use crate::viewport::{
snap_translation, viewport_ground_position, EditorViewportMode, ViewportDisplayMode,
ViewportSettings,
@@ -378,6 +380,13 @@ fn scene_options_popover(
.text("Snap step"),
);
}
if let Some(mut gizmo_options) = world.get_resource_mut::<GizmoOptions>() {
ui.separator();
ui.add(
egui::Slider::new(&mut gizmo_options.visuals.gizmo_size, 40.0..=160.0)
.text("Gizmo size"),
);
}
if let Some(mut mode) = world.get_resource_mut::<EditorViewportMode>() {
ui.separator();
ui.label("Shading");
@@ -387,6 +396,7 @@ fn scene_options_popover(
ui.selectable_value(&mut *mode, EditorViewportMode::Collider, "Colliders");
});
}
let mut actor_icons_active = false;
if let Some(mut visualizers) =
world.get_resource_mut::<crate::visualizers::EditorVisualizationSettings>()
{
@@ -409,6 +419,7 @@ fn scene_options_popover(
ui.checkbox(&mut visualizers.show_actor_icon_debug, "Warnings");
});
});
actor_icons_active = visualizers.enabled && visualizers.show_actor_icons;
ui.separator();
ui.checkbox(&mut visualizers.show_colliders, "Colliders");
ui.checkbox(&mut visualizers.show_lights, "Lights");
@@ -421,6 +432,18 @@ fn scene_options_popover(
ui.checkbox(&mut visualizers.pickable_proxies, "Selectable proxies");
});
}
if actor_icons_active {
if let Some(mut icon_settings) = world.get_resource_mut::<ActorIconSettings>() {
ui.add(
egui::Slider::new(
&mut icon_settings.size_pixels,
ActorIconSettings::MIN_SIZE_PIXELS
..=ActorIconSettings::MAX_SIZE_PIXELS,
)
.text("Icon size"),
);
}
}
ui.horizontal(|ui| {
if ui.button("Save bookmark").clicked() {
viewport_save_bookmark(world);
@@ -502,12 +525,53 @@ fn viewport_asset_drop_ui(
return;
}
let asset = {
let selection = {
let assets = world.resource::<EditorAssets>();
assets.dragging_asset().cloned()
assets.dragging_selection().cloned()
};
world.resource_mut::<EditorAssets>().clear_drag();
let Some(selection) = selection else {
return;
};
let placement = viewport_ground_position(world, pointer_pos.unwrap(), viewport_rect)
.map(|pos| snap_translation(pos, world.resource::<ViewportSettings>()))
.unwrap_or(Vec3::ZERO);
if matches!(
selection,
AssetSelection::SubAsset {
kind: AssetSubAssetKind::Mesh,
..
}
) {
crate::assets::spawn_subasset_at(world, &selection, placement);
return;
}
if let AssetSelection::SubAsset {
kind: AssetSubAssetKind::Texture,
source_path: Some(path),
label,
..
} = &selection
{
let asset = crate::assets::EditorAsset {
label: label.clone(),
path: Some(path.clone()),
folder_path: std::path::Path::new(path)
.parent()
.map(|parent| parent.to_string_lossy().replace('\\', "/"))
.unwrap_or_else(|| crate::assets::ASSETS_ROOT.to_string()),
kind: crate::assets::EditorAssetKind::Texture,
};
crate::ui::helpers::apply_texture_to_selection(world, &asset, selected);
return;
}
let asset = {
let assets = world.resource::<EditorAssets>();
assets.asset_for_selection(&selection).cloned()
};
let Some(asset) = asset else {
return;
};
@@ -523,8 +587,5 @@ fn viewport_asset_drop_ui(
_ => {}
}
let placement = viewport_ground_position(world, pointer_pos.unwrap(), viewport_rect)
.map(|pos| snap_translation(pos, world.resource::<ViewportSettings>()))
.unwrap_or(Vec3::ZERO);
crate::assets::spawn_asset_at(world, &asset, placement);
}
+158 -24
View File
@@ -2,10 +2,17 @@
use std::collections::{HashMap, HashSet};
use bevy::asset::{load_internal_binary_asset, uuid_handle, RenderAssetUsages};
use bevy::asset::{
load_internal_asset, load_internal_binary_asset, uuid_handle, RenderAssetUsages,
};
use bevy::camera::visibility::NoFrustumCulling;
use bevy::image::{CompressedImageFormats, ImageSampler, ImageType};
use bevy::pbr::{Material, MaterialPlugin};
use bevy::prelude::*;
use bevy::render::render_resource::{
AsBindGroup, BlendState, CompareFunction, RenderPipelineDescriptor, ShaderType,
};
use bevy::shader::ShaderRef;
use shared::{
ActorKind, AuthoringLightKind, ColliderDesc, LevelObject, LightDesc, ModelRef, ObjectiveMarker,
PhysicsBody, PlayerSpawn, PostProcessVolumeDesc, PrefabInstance, PrefabRef, Primitive,
@@ -19,11 +26,13 @@ use crate::ui::UiState;
use crate::viewport::ViewportDisplayMode;
use crate::visualizers::EditorVisualizationSettings;
const ICON_TARGET_PIXELS: f32 = 30.0;
const ICON_MIN_WORLD_SIZE: f32 = 0.2;
const ICON_MAX_WORLD_SIZE: f32 = 3.0;
const ICON_MIN_WORLD_SIZE: f32 = 0.001;
const ICON_MAX_WORLD_SIZE: f32 = 10_000.0;
const ICON_BRIGHTNESS: f32 = 1.6;
const DEFAULT_PERSPECTIVE_FOV: f32 = std::f32::consts::FRAC_PI_4;
const ACTOR_ICON_OVERLAY_SHADER: Handle<Shader> =
uuid_handle!("2edfe544-3ed1-4e13-a880-f56b09804b52");
const ICON_01_ACTOR_EMPTY: Handle<Image> = uuid_handle!("d87c7796-b219-4011-8305-4db55422f1c7");
const ICON_02_ACTOR_GENERIC: Handle<Image> = uuid_handle!("c9a1a84f-4dcd-4a2b-a5b6-c365dc7d6795");
const ICON_03_ACTOR_MISSING: Handle<Image> = uuid_handle!("cca7cdf9-0c7d-4546-9bb9-1176e49a635c");
@@ -69,6 +78,85 @@ pub struct ActorIconProxy {
pub target: Entity,
}
#[derive(Resource, Debug, Clone)]
pub struct ActorIconSettings {
pub size_pixels: f32,
}
impl ActorIconSettings {
pub const DEFAULT_SIZE_PIXELS: f32 = 34.0;
pub const MIN_SIZE_PIXELS: f32 = 16.0;
pub const MAX_SIZE_PIXELS: f32 = 96.0;
pub fn clamped_size_pixels(&self) -> f32 {
self.size_pixels
.clamp(Self::MIN_SIZE_PIXELS, Self::MAX_SIZE_PIXELS)
}
}
impl Default for ActorIconSettings {
fn default() -> Self {
Self {
size_pixels: Self::DEFAULT_SIZE_PIXELS,
}
}
}
#[derive(Clone, Copy, ShaderType)]
struct ActorIconOverlayUniform {
brightness: f32,
}
#[derive(Asset, TypePath, AsBindGroup, Clone)]
struct ActorIconOverlayMaterial {
#[texture(0)]
#[sampler(1)]
texture: Handle<Image>,
#[uniform(2)]
uniform: ActorIconOverlayUniform,
}
impl Material for ActorIconOverlayMaterial {
fn fragment_shader() -> ShaderRef {
ACTOR_ICON_OVERLAY_SHADER.into()
}
fn alpha_mode(&self) -> AlphaMode {
AlphaMode::Blend
}
fn enable_prepass() -> bool {
false
}
fn enable_shadows() -> bool {
false
}
fn specialize(
_pipeline: &bevy::pbr::MaterialPipeline,
descriptor: &mut RenderPipelineDescriptor,
_layout: &bevy::mesh::MeshVertexBufferLayoutRef,
_key: bevy::pbr::MaterialPipelineKey<Self>,
) -> Result<(), bevy::render::render_resource::SpecializedMeshPipelineError> {
descriptor.primitive.cull_mode = None;
if let Some(depth) = &mut descriptor.depth_stencil {
depth.depth_write_enabled = false;
depth.depth_compare = CompareFunction::Always;
}
if let Some(fragment) = &mut descriptor.fragment {
if let Some(target) = fragment
.targets
.first_mut()
.and_then(|target| target.as_mut())
{
target.blend = Some(BlendState::ALPHA_BLENDING);
}
}
Ok(())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
enum ActorIconImage {
Empty,
@@ -126,7 +214,7 @@ struct ActorIconComponents {
#[derive(Resource)]
struct ActorIconAssets {
mesh: Handle<Mesh>,
materials: HashMap<ActorIconImage, Handle<StandardMaterial>>,
materials: HashMap<ActorIconImage, Handle<ActorIconOverlayMaterial>>,
}
pub struct ActorIconsPlugin;
@@ -134,7 +222,16 @@ pub struct ActorIconsPlugin;
impl Plugin for ActorIconsPlugin {
fn build(&self, app: &mut App) {
register_actor_icon_images(app);
app.add_systems(Startup, init_actor_icon_assets)
load_internal_asset!(
app,
ACTOR_ICON_OVERLAY_SHADER,
"../../assets/shaders/actor_icon_overlay.wgsl",
Shader::from_wgsl
);
app.init_resource::<ActorIconSettings>()
.add_plugins(MaterialPlugin::<ActorIconOverlayMaterial>::default())
.add_systems(Startup, init_actor_icon_assets)
.add_systems(Update, sync_actor_icons.run_if(scene_tools_active));
}
}
@@ -204,7 +301,7 @@ fn register_actor_icon_images(app: &mut App) {
fn init_actor_icon_assets(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
mut materials: ResMut<Assets<ActorIconOverlayMaterial>>,
) {
let mesh = meshes.add(Rectangle::new(1.0, 1.0));
let mut actor_materials = HashMap::new();
@@ -229,14 +326,11 @@ fn init_actor_icon_assets(
] {
actor_materials.insert(
image,
materials.add(StandardMaterial {
base_color_texture: Some(texture.clone()),
alpha_mode: AlphaMode::Blend,
unlit: true,
cull_mode: None,
fog_enabled: false,
depth_bias: -40.0,
..default()
materials.add(ActorIconOverlayMaterial {
texture: texture.clone(),
uniform: ActorIconOverlayUniform {
brightness: ICON_BRIGHTNESS,
},
}),
);
}
@@ -251,13 +345,14 @@ fn init_actor_icon_assets(
fn sync_actor_icons(
display: Res<ViewportDisplayMode>,
settings: Res<EditorVisualizationSettings>,
icon_settings: Res<ActorIconSettings>,
ui_state: Res<UiState>,
assets: Res<ActorIconAssets>,
mut commands: Commands,
mut icons: Query<(
Entity,
&ActorIconProxy,
&MeshMaterial3d<StandardMaterial>,
&MeshMaterial3d<ActorIconOverlayMaterial>,
&mut Transform,
)>,
camera_query: Query<(&Camera, &GlobalTransform, Option<&Projection>), With<EditorCamera>>,
@@ -325,7 +420,12 @@ fn sync_actor_icons(
if !icon_category_enabled(&settings, spec.category) {
continue;
}
let transform = desired_icon_transform(global, camera, ui_state.viewport_rect.height());
let transform = desired_icon_transform(
global,
camera,
ui_state.viewport_rect.height(),
icon_settings.clamped_size_pixels(),
);
desired.insert(target, (spec.image, transform));
}
}
@@ -390,7 +490,12 @@ fn sync_actor_icons(
let Some(material) = assets.materials.get(&spec.image).cloned() else {
continue;
};
let transform = desired_icon_transform(global, camera, ui_state.viewport_rect.height());
let transform = desired_icon_transform(
global,
camera,
ui_state.viewport_rect.height(),
icon_settings.clamped_size_pixels(),
);
commands.spawn((
EditorOnly,
RaytracingExcluded,
@@ -419,6 +524,7 @@ fn desired_icon_transform(
parent_global: &GlobalTransform,
camera: Option<(&Camera, &GlobalTransform, Option<&Projection>)>,
viewport_height: f32,
target_pixels: f32,
) -> Transform {
let translation = parent_global.translation();
let Some((_, camera_global, projection)) = camera else {
@@ -429,6 +535,7 @@ fn desired_icon_transform(
camera_global,
projection,
viewport_height.max(1.0),
target_pixels,
);
let desired_global = Transform {
translation,
@@ -444,18 +551,20 @@ fn icon_world_size(
camera_global: &GlobalTransform,
projection: Option<&Projection>,
viewport_height: f32,
target_pixels: f32,
) -> f32 {
let camera_position = camera_global.translation();
let pixels_to_view = ICON_TARGET_PIXELS / viewport_height;
let pixels_to_view = target_pixels / viewport_height;
let world_height = match projection {
Some(Projection::Perspective(projection)) => {
let distance = camera_position.distance(target).max(0.1);
2.0 * distance * (projection.fov * 0.5).tan()
let target_view = camera_global.affine().inverse().transform_point3(target);
let depth = (-target_view.z).abs().max(0.1);
2.0 * depth * (projection.fov * 0.5).tan()
}
Some(Projection::Orthographic(projection)) => projection.area.height().abs().max(0.1),
_ => {
let distance = camera_position.distance(target).max(0.1);
2.0 * distance * (DEFAULT_PERSPECTIVE_FOV * 0.5).tan()
let target_view = camera_global.affine().inverse().transform_point3(target);
let depth = (-target_view.z).abs().max(0.1);
2.0 * depth * (DEFAULT_PERSPECTIVE_FOV * 0.5).tan()
}
};
(world_height * pixels_to_view).clamp(ICON_MIN_WORLD_SIZE, ICON_MAX_WORLD_SIZE)
@@ -653,4 +762,29 @@ mod tests {
assert_eq!(spec.image, ActorIconImage::PhysicsCollider);
assert_eq!(spec.category, ActorIconCategory::Physics);
}
#[test]
fn perspective_icon_size_uses_view_depth() {
let camera = GlobalTransform::IDENTITY;
let projection = Projection::Perspective(PerspectiveProjection {
fov: DEFAULT_PERSPECTIVE_FOV,
..default()
});
let centered = icon_world_size(
Vec3::new(0.0, 0.0, -12.0),
&camera,
Some(&projection),
900.0,
ActorIconSettings::DEFAULT_SIZE_PIXELS,
);
let offset = icon_world_size(
Vec3::new(8.0, 0.0, -12.0),
&camera,
Some(&projection),
900.0,
ActorIconSettings::DEFAULT_SIZE_PIXELS,
);
assert_eq!(centered, offset);
}
}
+14 -7
View File
@@ -306,13 +306,20 @@ fn collect_viewport_pick_hits(
let mut seen = std::collections::HashSet::new();
let mut ordered = Vec::new();
for (entity, _) in hits {
let Some(target) = pick_target_for_entity(*entity, level_objects, proxies, icon_proxies)
else {
continue;
};
if seen.insert(target) {
ordered.push(target);
for icon_priority in [true, false] {
for (entity, _) in hits {
let is_icon = icon_proxies.get(*entity).is_ok();
if is_icon != icon_priority {
continue;
}
let Some(target) =
pick_target_for_entity(*entity, level_objects, proxies, icon_proxies)
else {
continue;
};
if seen.insert(target) {
ordered.push(target);
}
}
}
ordered
+2 -1
View File
@@ -17,7 +17,8 @@ use bevy::ecs::system::SystemState;
use bevy::prelude::*;
use lights::{hydrate_lights, reconcile_missing_runtime_lights};
use materials::{hydrate_materials, material_from_desc};
use materials::hydrate_materials;
pub use materials::material_from_desc;
use models::hydrate_models;
use physics::hydrate_physics;
use prefabs::hydrate_prefabs;
+2 -2
View File
@@ -14,8 +14,8 @@ mod rendering_profile_asset;
pub use actor::{infer_actor_kind, validate_actor, ActorValidationError};
pub use components::*;
pub use hydration::{
cascade_config_from_rendering, flush_level_object_hydration, strip_hydrated,
strip_hydrated_entity, HydrationPlugin,
cascade_config_from_rendering, flush_level_object_hydration, material_from_desc,
strip_hydrated, strip_hydrated_entity, HydrationPlugin,
};
pub use material_asset::{
MaterialAsset, ShaderPropertyDesc, ShaderPropertyType, ShaderSchemaAsset,