This commit is contained in:
commit
f29712d158
259 files changed
+52069
No files matched your search
@@ -0,0 +1,138 @@
|
||||
//! Actor-centric inspector (authoring components only).
|
||||
|
||||
mod transform;
|
||||
|
||||
use bevy::prelude::*;
|
||||
use bevy_egui::egui;
|
||||
use egui_phosphor_icons::icons;
|
||||
use shared::{ActorId, ActorKind, ActorName, LevelObject};
|
||||
|
||||
use crate::ext::extensibility::ActorInspectorSectionRegistry;
|
||||
use crate::ui::inspector;
|
||||
use crate::ui::theme::{panel_heading, BORDER, TEXT_DIM, WIDGET_BG};
|
||||
use crate::ui::widgets::phosphor_icon;
|
||||
|
||||
use transform::transform_inspector_ui;
|
||||
|
||||
const COMPACT_ACTOR_HEADER_WIDTH: f32 = 360.0;
|
||||
|
||||
pub fn draw_actor_inspector(world: &mut World, ui: &mut egui::Ui, entity: Entity) {
|
||||
let Some(entity_ref) = world.get_entity(entity).ok() else {
|
||||
ui.label("Entity no longer exists.");
|
||||
return;
|
||||
};
|
||||
if !entity_ref.contains::<LevelObject>() {
|
||||
ui.label("Not a level object.");
|
||||
return;
|
||||
}
|
||||
|
||||
let kind = entity_ref
|
||||
.get::<ActorKind>()
|
||||
.copied()
|
||||
.unwrap_or(ActorKind::Empty);
|
||||
|
||||
egui::Frame::new()
|
||||
.fill(WIDGET_BG)
|
||||
.stroke(egui::Stroke::new(1.0, BORDER))
|
||||
.corner_radius(egui::CornerRadius::same(4))
|
||||
.inner_margin(egui::Margin::symmetric(8, 8))
|
||||
.show(ui, |ui| {
|
||||
let compact = ui.available_width() < COMPACT_ACTOR_HEADER_WIDTH;
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(phosphor_icon(actor_icon(kind), 28.0).color(TEXT_DIM));
|
||||
let text_max_width = (ui.available_width() - 28.0).max(96.0);
|
||||
ui.vertical(|ui| {
|
||||
ui.set_max_width(text_max_width);
|
||||
let name = entity_ref
|
||||
.get::<ActorName>()
|
||||
.map(|name| name.0.as_str())
|
||||
.or_else(|| entity_ref.get::<Name>().map(|name| name.as_str()))
|
||||
.unwrap_or("Unnamed");
|
||||
let actor_id = entity_ref
|
||||
.get::<ActorId>()
|
||||
.map(|id| id.0.as_str())
|
||||
.filter(|id| !id.trim().is_empty())
|
||||
.unwrap_or("unpersisted");
|
||||
ui.add(egui::Label::new(panel_heading(name)).truncate());
|
||||
if compact {
|
||||
ui.small(
|
||||
egui::RichText::new(format!("{kind:?} | Actor {actor_id}"))
|
||||
.color(TEXT_DIM),
|
||||
);
|
||||
ui.small(
|
||||
egui::RichText::new(format!("Runtime {entity:?}")).color(TEXT_DIM),
|
||||
);
|
||||
} else {
|
||||
ui.small(
|
||||
egui::RichText::new(format!(
|
||||
"{kind:?} | Actor {actor_id} | Runtime {entity:?}"
|
||||
))
|
||||
.color(TEXT_DIM),
|
||||
);
|
||||
}
|
||||
});
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
ui.label(phosphor_icon(icons::DOTS_THREE_VERTICAL, 16.0).color(TEXT_DIM));
|
||||
ui.label(phosphor_icon(icons::LOCK_SIMPLE, 16.0).color(TEXT_DIM));
|
||||
});
|
||||
});
|
||||
});
|
||||
ui.add_space(6.0);
|
||||
|
||||
let footer_reserve = 52.0;
|
||||
let body_height = (ui.available_height() - footer_reserve).max(1.0);
|
||||
ui.allocate_ui_with_layout(
|
||||
egui::vec2(ui.available_width(), body_height),
|
||||
egui::Layout::top_down(egui::Align::Min),
|
||||
|ui| {
|
||||
egui::ScrollArea::vertical()
|
||||
.auto_shrink([false, false])
|
||||
.show(ui, |ui| {
|
||||
transform_inspector_ui(world, ui, entity);
|
||||
|
||||
match kind {
|
||||
ActorKind::StaticMesh
|
||||
| ActorKind::ImportedModel
|
||||
| ActorKind::Light
|
||||
| ActorKind::Empty
|
||||
| ActorKind::PrefabAnchor
|
||||
| ActorKind::PlayerSpawn
|
||||
| ActorKind::WeaponSpawn
|
||||
| ActorKind::TriggerVolume
|
||||
| ActorKind::PostProcessVolume
|
||||
| ActorKind::TeamSpawn
|
||||
| ActorKind::Objective => {
|
||||
inspector::authoring_inspector_ui(world, ui, entity);
|
||||
}
|
||||
}
|
||||
|
||||
world.resource_scope(|world, registry: Mut<ActorInspectorSectionRegistry>| {
|
||||
registry.draw_sections(world, ui, entity);
|
||||
});
|
||||
});
|
||||
},
|
||||
);
|
||||
inspector::add_component_footer(world, ui, entity);
|
||||
}
|
||||
|
||||
fn actor_icon(kind: ActorKind) -> egui_phosphor_icons::Icon {
|
||||
match kind {
|
||||
ActorKind::StaticMesh | ActorKind::ImportedModel => icons::CUBE,
|
||||
ActorKind::Light => icons::LIGHTBULB,
|
||||
ActorKind::PrefabAnchor => icons::PACKAGE,
|
||||
ActorKind::PlayerSpawn => icons::PERSON_SIMPLE_RUN,
|
||||
ActorKind::WeaponSpawn => icons::CROSSHAIR,
|
||||
ActorKind::TriggerVolume => icons::SELECTION,
|
||||
ActorKind::PostProcessVolume => icons::APERTURE,
|
||||
ActorKind::TeamSpawn | ActorKind::Objective => icons::FLAG,
|
||||
ActorKind::Empty => icons::CIRCLE,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn draw_multi_actor_inspector(world: &mut World, ui: &mut egui::Ui, entities: &[Entity]) {
|
||||
ui.heading(format!("{} objects selected", entities.len()));
|
||||
ui.label("Multi-edit: use the viewport gizmo for shared transform.");
|
||||
if entities.len() == 1 {
|
||||
draw_actor_inspector(world, ui, entities[0]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
//! Transform section (authoring) for the actor inspector.
|
||||
|
||||
use bevy::prelude::*;
|
||||
use bevy_egui::egui;
|
||||
use egui_phosphor_icons::icons;
|
||||
|
||||
use crate::history::set_transform_with_history;
|
||||
use crate::ui::inspector::{
|
||||
apply_component_card_response, component_card, component_card_context, ComponentCardOptions,
|
||||
COMPONENT_TRANSFORM,
|
||||
};
|
||||
use crate::ui::theme::TEXT_DIM;
|
||||
|
||||
const WIDE_TRANSFORM_ROW_WIDTH: f32 = 360.0;
|
||||
const TRANSFORM_LABEL_WIDTH: f32 = 124.0;
|
||||
const AXIS_FIELD_WIDTH: f32 = 76.0;
|
||||
|
||||
pub fn transform_inspector_ui(world: &mut World, ui: &mut egui::Ui, entity: Entity) {
|
||||
let Some(mut transform) = world.get::<Transform>(entity).cloned() else {
|
||||
return;
|
||||
};
|
||||
let old = transform;
|
||||
let mut changed = false;
|
||||
|
||||
let card = component_card_context(
|
||||
world,
|
||||
entity,
|
||||
ComponentCardOptions::fixed(COMPONENT_TRANSFORM, "Transform", icons::ARROWS_OUT_CARDINAL),
|
||||
);
|
||||
let card_response = component_card(ui, &card, |ui| {
|
||||
if transform_row(ui, "Position", &mut transform.translation, 0.1) {
|
||||
changed = true;
|
||||
}
|
||||
|
||||
let (yaw, pitch, roll) = transform.rotation.to_euler(EulerRot::YXZ);
|
||||
let mut rotation_deg = Vec3::new(pitch.to_degrees(), yaw.to_degrees(), roll.to_degrees());
|
||||
if transform_row(ui, "Rotation (degrees)", &mut rotation_deg, 0.5) {
|
||||
transform.rotation = Quat::from_euler(
|
||||
EulerRot::YXZ,
|
||||
rotation_deg.y.to_radians(),
|
||||
rotation_deg.x.to_radians(),
|
||||
rotation_deg.z.to_radians(),
|
||||
);
|
||||
changed = true;
|
||||
}
|
||||
|
||||
if transform_row(ui, "Scale", &mut transform.scale, 0.05) {
|
||||
changed = true;
|
||||
}
|
||||
});
|
||||
|
||||
let reset = card_response.reset;
|
||||
apply_component_card_response(world, entity, card_response);
|
||||
|
||||
if reset {
|
||||
set_transform_with_history(world, entity, old, Transform::default());
|
||||
} else if changed {
|
||||
set_transform_with_history(world, entity, old, transform);
|
||||
}
|
||||
}
|
||||
|
||||
fn transform_row(ui: &mut egui::Ui, label: &str, value: &mut Vec3, speed: f64) -> bool {
|
||||
let mut changed = false;
|
||||
if ui.available_width() < WIDE_TRANSFORM_ROW_WIDTH {
|
||||
ui.vertical(|ui| {
|
||||
ui.label(label);
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
changed |= axis_drag(ui, "X", &mut value.x, speed);
|
||||
changed |= axis_drag(ui, "Y", &mut value.y, speed);
|
||||
changed |= axis_drag(ui, "Z", &mut value.z, speed);
|
||||
});
|
||||
});
|
||||
} else {
|
||||
ui.horizontal(|ui| {
|
||||
ui.add_sized(
|
||||
[TRANSFORM_LABEL_WIDTH.min(ui.available_width()), 20.0],
|
||||
egui::Label::new(label),
|
||||
);
|
||||
changed |= axis_drag(ui, "X", &mut value.x, speed);
|
||||
changed |= axis_drag(ui, "Y", &mut value.y, speed);
|
||||
changed |= axis_drag(ui, "Z", &mut value.z, speed);
|
||||
});
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
fn axis_drag(ui: &mut egui::Ui, axis: &str, value: &mut f32, speed: f64) -> bool {
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(egui::RichText::new(axis).color(axis_color(axis)).strong());
|
||||
ui.add_sized(
|
||||
[AXIS_FIELD_WIDTH.min(ui.available_width().max(44.0)), 20.0],
|
||||
egui::DragValue::new(value)
|
||||
.speed(speed)
|
||||
.max_decimals(3)
|
||||
.min_decimals(1),
|
||||
)
|
||||
.changed()
|
||||
})
|
||||
.inner
|
||||
}
|
||||
|
||||
fn axis_color(axis: &str) -> egui::Color32 {
|
||||
match axis {
|
||||
"X" => egui::Color32::from_rgb(229, 82, 73),
|
||||
"Y" => egui::Color32::from_rgb(103, 190, 92),
|
||||
"Z" => egui::Color32::from_rgb(88, 132, 241),
|
||||
_ => TEXT_DIM,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
mod panel;
|
||||
mod state;
|
||||
|
||||
pub use panel::*;
|
||||
pub use state::AssetBrowserUiState;
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,62 @@
|
||||
//! Asset browser UI state and view enums.
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use bevy::prelude::*;
|
||||
|
||||
use crate::assets::{ASSETS_ROOT, BUILTINS_FOLDER};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum AssetBrowserView {
|
||||
Grid,
|
||||
List,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum AssetSort {
|
||||
Name,
|
||||
Kind,
|
||||
Modified,
|
||||
Size,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum AssetKindFilter {
|
||||
All,
|
||||
Model,
|
||||
Texture,
|
||||
Material,
|
||||
Level,
|
||||
Prefab,
|
||||
Builtin,
|
||||
}
|
||||
|
||||
#[derive(Resource, Debug)]
|
||||
pub struct AssetBrowserUiState {
|
||||
pub(crate) search: String,
|
||||
pub(crate) view: AssetBrowserView,
|
||||
pub(crate) sort: AssetSort,
|
||||
pub(crate) kind_filter: AssetKindFilter,
|
||||
pub(crate) thumbnail_size: f32,
|
||||
pub(crate) recursive: bool,
|
||||
pub(crate) show_details: bool,
|
||||
pub(crate) expanded_folders: HashSet<String>,
|
||||
}
|
||||
|
||||
impl Default for AssetBrowserUiState {
|
||||
fn default() -> Self {
|
||||
let mut expanded_folders = HashSet::new();
|
||||
expanded_folders.insert(ASSETS_ROOT.to_string());
|
||||
expanded_folders.insert(BUILTINS_FOLDER.to_string());
|
||||
Self {
|
||||
search: String::new(),
|
||||
view: AssetBrowserView::Grid,
|
||||
sort: AssetSort::Name,
|
||||
kind_filter: AssetKindFilter::All,
|
||||
thumbnail_size: 72.0,
|
||||
recursive: false,
|
||||
show_details: true,
|
||||
expanded_folders,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
//! Editor-visible component registry for actor inspector palettes.
|
||||
|
||||
use bevy::prelude::*;
|
||||
use egui_phosphor_icons::icons;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum EditorComponentCategory {
|
||||
Rendering,
|
||||
Physics,
|
||||
Gameplay,
|
||||
Editor,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct EditorComponentDescriptor {
|
||||
pub type_name: &'static str,
|
||||
pub display_name: &'static str,
|
||||
pub category: EditorComponentCategory,
|
||||
pub addable: bool,
|
||||
pub removable: bool,
|
||||
pub reorderable: bool,
|
||||
pub icon: &'static str,
|
||||
pub search_terms: &'static [&'static str],
|
||||
}
|
||||
|
||||
#[derive(Resource, Debug, Clone)]
|
||||
pub struct EditorComponentRegistry {
|
||||
pub descriptors: Vec<EditorComponentDescriptor>,
|
||||
}
|
||||
|
||||
impl Default for EditorComponentRegistry {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
descriptors: vec![
|
||||
EditorComponentDescriptor {
|
||||
type_name: "shared::components::StaticMeshRenderer",
|
||||
display_name: "Static Mesh Renderer",
|
||||
category: EditorComponentCategory::Rendering,
|
||||
addable: true,
|
||||
removable: true,
|
||||
reorderable: true,
|
||||
icon: icons::CUBE.as_str(),
|
||||
search_terms: &["mesh", "renderer", "rendering", "model"],
|
||||
},
|
||||
EditorComponentDescriptor {
|
||||
type_name: "shared::components::MaterialDesc",
|
||||
display_name: "Authoring Material",
|
||||
category: EditorComponentCategory::Rendering,
|
||||
addable: true,
|
||||
removable: true,
|
||||
reorderable: true,
|
||||
icon: icons::PALETTE.as_str(),
|
||||
search_terms: &["material", "shader", "texture"],
|
||||
},
|
||||
EditorComponentDescriptor {
|
||||
type_name: "shared::components::RigidBodyDesc",
|
||||
display_name: "Rigid Body",
|
||||
category: EditorComponentCategory::Physics,
|
||||
addable: true,
|
||||
removable: true,
|
||||
reorderable: true,
|
||||
icon: icons::SPHERE.as_str(),
|
||||
search_terms: &["body", "physics", "rigidbody"],
|
||||
},
|
||||
EditorComponentDescriptor {
|
||||
type_name: "shared::components::ColliderDesc",
|
||||
display_name: "Collider",
|
||||
category: EditorComponentCategory::Physics,
|
||||
addable: true,
|
||||
removable: true,
|
||||
reorderable: true,
|
||||
icon: icons::SELECTION.as_str(),
|
||||
search_terms: &["collision", "trigger", "physics"],
|
||||
},
|
||||
EditorComponentDescriptor {
|
||||
type_name: "shared::components::LightDesc",
|
||||
display_name: "Light",
|
||||
category: EditorComponentCategory::Rendering,
|
||||
addable: true,
|
||||
removable: true,
|
||||
reorderable: true,
|
||||
icon: icons::LIGHTBULB.as_str(),
|
||||
search_terms: &["light", "lamp", "illumination"],
|
||||
},
|
||||
EditorComponentDescriptor {
|
||||
type_name: "shared::components::Primitive",
|
||||
display_name: "Primitive",
|
||||
category: EditorComponentCategory::Rendering,
|
||||
addable: true,
|
||||
removable: true,
|
||||
reorderable: true,
|
||||
icon: icons::CUBE.as_str(),
|
||||
search_terms: &["box", "sphere", "ramp", "primitive"],
|
||||
},
|
||||
EditorComponentDescriptor {
|
||||
type_name: "shared::components::PlayerSpawn",
|
||||
display_name: "Player Spawn",
|
||||
category: EditorComponentCategory::Gameplay,
|
||||
addable: true,
|
||||
removable: true,
|
||||
reorderable: true,
|
||||
icon: icons::PERSON_SIMPLE_RUN.as_str(),
|
||||
search_terms: &["player", "spawn", "start"],
|
||||
},
|
||||
EditorComponentDescriptor {
|
||||
type_name: "shared::components::WeaponSpawn",
|
||||
display_name: "Weapon Spawn",
|
||||
category: EditorComponentCategory::Gameplay,
|
||||
addable: true,
|
||||
removable: true,
|
||||
reorderable: true,
|
||||
icon: icons::CROSSHAIR.as_str(),
|
||||
search_terms: &["weapon", "spawn"],
|
||||
},
|
||||
EditorComponentDescriptor {
|
||||
type_name: "shared::components::TriggerVolume",
|
||||
display_name: "Trigger Volume",
|
||||
category: EditorComponentCategory::Gameplay,
|
||||
addable: true,
|
||||
removable: true,
|
||||
reorderable: true,
|
||||
icon: icons::SELECTION.as_str(),
|
||||
search_terms: &["trigger", "volume", "event"],
|
||||
},
|
||||
EditorComponentDescriptor {
|
||||
type_name: "shared::components::TeamSpawn",
|
||||
display_name: "Team Spawn",
|
||||
category: EditorComponentCategory::Gameplay,
|
||||
addable: true,
|
||||
removable: true,
|
||||
reorderable: true,
|
||||
icon: icons::FLAG.as_str(),
|
||||
search_terms: &["team", "spawn"],
|
||||
},
|
||||
EditorComponentDescriptor {
|
||||
type_name: "shared::components::ObjectiveMarker",
|
||||
display_name: "Objective Marker",
|
||||
category: EditorComponentCategory::Gameplay,
|
||||
addable: true,
|
||||
removable: true,
|
||||
reorderable: true,
|
||||
icon: icons::FLAG.as_str(),
|
||||
search_terms: &["objective", "marker", "gameplay"],
|
||||
},
|
||||
EditorComponentDescriptor {
|
||||
type_name: "shared::components::InspectorOrder",
|
||||
display_name: "Inspector Order",
|
||||
category: EditorComponentCategory::Editor,
|
||||
addable: false,
|
||||
removable: false,
|
||||
reorderable: false,
|
||||
icon: icons::LIST_BULLETS.as_str(),
|
||||
search_terms: &["editor", "order"],
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
//! Detailed diagnostics (relocated from Status dock tab).
|
||||
|
||||
use bevy::prelude::*;
|
||||
use bevy_egui::egui;
|
||||
use shared::LevelObject;
|
||||
|
||||
use crate::assets::EditorAssets;
|
||||
use crate::history::EditorHistory;
|
||||
use crate::project_io::ProjectWorkspace;
|
||||
use crate::scene_io::SceneIo;
|
||||
|
||||
#[derive(Resource, Default)]
|
||||
pub struct DiagnosticsPanel {
|
||||
pub open: bool,
|
||||
}
|
||||
|
||||
pub fn diagnostics_ui(world: &mut World, ui: &mut egui::Ui) {
|
||||
let scene_io = world.resource::<SceneIo>();
|
||||
let dirty = if scene_io.dirty { " (dirty)" } else { "" };
|
||||
ui.label(format!("Scene: {}{dirty}", scene_io.active_path_label()));
|
||||
ui.label(format!("Status: {}", scene_io.status));
|
||||
ui.label(format!(
|
||||
"History: {}",
|
||||
world.resource::<EditorHistory>().status
|
||||
));
|
||||
ui.label(format!(
|
||||
"Assets: {}",
|
||||
world.resource::<EditorAssets>().status
|
||||
));
|
||||
|
||||
let workspace = world.resource::<ProjectWorkspace>();
|
||||
ui.label(format!("Project root: {}", workspace.root));
|
||||
ui.label(format!(
|
||||
"Project settings: {}{}",
|
||||
workspace.settings_path,
|
||||
if workspace.settings_dirty {
|
||||
" (dirty)"
|
||||
} else {
|
||||
""
|
||||
}
|
||||
));
|
||||
if workspace.layout_dirty {
|
||||
ui.small("Dock layout modified (unsaved)");
|
||||
}
|
||||
|
||||
let mut level_query = world.query_filtered::<Entity, With<LevelObject>>();
|
||||
let count = level_query.iter(world).count();
|
||||
ui.label(format!("Level objects: {count}"));
|
||||
|
||||
ui.separator();
|
||||
ui.small("Native Bevy scenes are saved to assets/levels/*.scn.ron");
|
||||
ui.small("BRP is enabled on the editor for external tooling.");
|
||||
}
|
||||
|
||||
pub fn diagnostics_window(world: &mut World, ctx: &egui::Context, open: &mut bool) {
|
||||
if !*open {
|
||||
return;
|
||||
}
|
||||
egui::Window::new("Diagnostics")
|
||||
.open(open)
|
||||
.default_width(420.0)
|
||||
.show(ctx, |ui| {
|
||||
diagnostics_ui(world, ui);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
//! Dock tab open/focus helpers and default panel node placement.
|
||||
|
||||
use egui_dock::{DockState, Node, NodeIndex, SurfaceIndex, TabIndex, Tree};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::EditorTab;
|
||||
|
||||
/// Preferred leaf nodes for re-opening closed panels (updated when layout is built or loaded).
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
|
||||
pub struct PanelNodes {
|
||||
pub main_view: usize,
|
||||
pub hierarchy: usize,
|
||||
pub inspector: usize,
|
||||
pub bottom: usize,
|
||||
}
|
||||
|
||||
impl PanelNodes {
|
||||
pub fn main_view(&self) -> NodeIndex {
|
||||
NodeIndex::from(self.main_view)
|
||||
}
|
||||
|
||||
pub fn hierarchy(&self) -> NodeIndex {
|
||||
NodeIndex::from(self.hierarchy)
|
||||
}
|
||||
|
||||
pub fn inspector(&self) -> NodeIndex {
|
||||
NodeIndex::from(self.inspector)
|
||||
}
|
||||
|
||||
pub fn bottom(&self) -> NodeIndex {
|
||||
NodeIndex::from(self.bottom)
|
||||
}
|
||||
|
||||
pub fn preferred_node(&self, tab: &EditorTab) -> NodeIndex {
|
||||
match tab {
|
||||
EditorTab::Viewport | EditorTab::GameView => self.main_view(),
|
||||
EditorTab::Hierarchy => self.hierarchy(),
|
||||
EditorTab::Inspector => self.inspector(),
|
||||
EditorTab::AssetBrowser | EditorTab::Toolbar => self.bottom(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Scan the main surface for open tabs and refresh node indices (handles user drag/split).
|
||||
pub fn discover(dock: &DockState<EditorTab>, fallback: Self) -> Self {
|
||||
let mut nodes = fallback;
|
||||
for ((surface, node_idx), tab) in dock.iter_all_tabs() {
|
||||
if surface != SurfaceIndex::main() {
|
||||
continue;
|
||||
}
|
||||
match tab {
|
||||
EditorTab::Viewport | EditorTab::GameView => nodes.main_view = node_idx.0,
|
||||
EditorTab::Hierarchy => nodes.hierarchy = node_idx.0,
|
||||
EditorTab::Inspector => nodes.inspector = node_idx.0,
|
||||
EditorTab::AssetBrowser | EditorTab::Toolbar => nodes.bottom = node_idx.0,
|
||||
}
|
||||
}
|
||||
nodes
|
||||
}
|
||||
}
|
||||
|
||||
pub const PANEL_TABS: [EditorTab; 4] = [
|
||||
EditorTab::Viewport,
|
||||
EditorTab::Hierarchy,
|
||||
EditorTab::Inspector,
|
||||
EditorTab::AssetBrowser,
|
||||
];
|
||||
|
||||
pub fn tab_label(tab: &EditorTab) -> &'static str {
|
||||
match tab {
|
||||
EditorTab::Viewport | EditorTab::GameView => "Viewport",
|
||||
EditorTab::Hierarchy => "Hierarchy",
|
||||
EditorTab::Inspector => "Inspector",
|
||||
EditorTab::AssetBrowser => "Asset Browser",
|
||||
EditorTab::Toolbar => "Toolbar (legacy)",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn tab_is_open(dock: &DockState<EditorTab>, tab: &EditorTab) -> bool {
|
||||
dock.find_main_surface_tab(tab).is_some()
|
||||
}
|
||||
|
||||
/// Opens `tab` on the main surface if missing, then focuses it.
|
||||
pub fn open_and_focus_tab(
|
||||
dock: &mut DockState<EditorTab>,
|
||||
tab: EditorTab,
|
||||
panels: &PanelNodes,
|
||||
) -> (NodeIndex, TabIndex) {
|
||||
let (node, tab_idx) = if let Some(loc) = dock.find_main_surface_tab(&tab) {
|
||||
loc
|
||||
} else {
|
||||
let tree = dock.main_surface_mut();
|
||||
let node = panels.preferred_node(&tab);
|
||||
let tab_idx = push_tab_to_node(tree, node, tab);
|
||||
(node, tab_idx)
|
||||
};
|
||||
dock.set_active_tab((SurfaceIndex::main(), node, tab_idx));
|
||||
dock.set_focused_node_and_surface((SurfaceIndex::main(), node));
|
||||
(node, tab_idx)
|
||||
}
|
||||
|
||||
pub fn ensure_viewport_for_play(dock: &mut DockState<EditorTab>, panels: &PanelNodes) {
|
||||
open_and_focus_tab(dock, EditorTab::Viewport, panels);
|
||||
}
|
||||
|
||||
/// Migrates old saved layouts by replacing/removing legacy Game View tabs.
|
||||
pub fn normalize_unified_viewport_tabs(dock: &mut DockState<EditorTab>) {
|
||||
let has_viewport = dock
|
||||
.iter_all_tabs()
|
||||
.any(|(_, tab)| matches!(tab, EditorTab::Viewport));
|
||||
|
||||
if !has_viewport {
|
||||
if let Some((_, tab)) = dock
|
||||
.iter_all_tabs_mut()
|
||||
.find(|(_, tab)| matches!(tab, EditorTab::GameView))
|
||||
{
|
||||
*tab = EditorTab::Viewport;
|
||||
}
|
||||
}
|
||||
|
||||
let mut seen_viewport = false;
|
||||
dock.retain_tabs(|tab| match tab {
|
||||
EditorTab::GameView => false,
|
||||
EditorTab::Viewport => {
|
||||
if seen_viewport {
|
||||
false
|
||||
} else {
|
||||
seen_viewport = true;
|
||||
true
|
||||
}
|
||||
}
|
||||
_ => true,
|
||||
});
|
||||
|
||||
if !seen_viewport {
|
||||
dock.main_surface_mut()
|
||||
.push_to_first_leaf(EditorTab::Viewport);
|
||||
}
|
||||
}
|
||||
|
||||
fn push_tab_to_node(tree: &mut Tree<EditorTab>, node_index: NodeIndex, tab: EditorTab) -> TabIndex {
|
||||
match &mut tree[node_index] {
|
||||
Node::Leaf(leaf) => {
|
||||
let tab_idx = TabIndex(leaf.tabs.len());
|
||||
leaf.tabs.push(tab);
|
||||
leaf.active = tab_idx;
|
||||
tab_idx
|
||||
}
|
||||
Node::Empty => {
|
||||
tree[node_index] = Node::leaf(tab);
|
||||
TabIndex(0)
|
||||
}
|
||||
_ => {
|
||||
let kind = tab.clone();
|
||||
tree.push_to_first_leaf(tab);
|
||||
tree.find_tab(&kind).expect("tab was just pushed").1
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
//! Phosphor icon font registration for the primary egui context.
|
||||
|
||||
use bevy::prelude::*;
|
||||
use bevy_egui::{EguiContext, PrimaryEguiContext};
|
||||
|
||||
pub struct EditorFontsPlugin;
|
||||
|
||||
impl Plugin for EditorFontsPlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
app.add_systems(Update, configure_editor_fonts);
|
||||
}
|
||||
}
|
||||
|
||||
fn configure_editor_fonts(mut contexts: Query<&mut EguiContext, Added<PrimaryEguiContext>>) {
|
||||
let Some(mut ctx) = contexts.iter_mut().next() else {
|
||||
return;
|
||||
};
|
||||
let mut fonts = bevy_egui::egui::FontDefinitions::default();
|
||||
egui_phosphor_icons::add_fonts(&mut fonts);
|
||||
ctx.get_mut().set_fonts(fonts);
|
||||
}
|
||||
@@ -0,0 +1,297 @@
|
||||
//! Spawn helpers, bookmarks, hierarchy tree, and asset labeling.
|
||||
|
||||
use bevy::prelude::*;
|
||||
use bevy_inspector_egui::bevy_inspector::hierarchy::SelectedEntities;
|
||||
use shared::{
|
||||
AuthoringLightKind, LevelObject, LightDesc, MaterialDesc, PlayerSpawn, PrimitiveShape,
|
||||
ProjectSun,
|
||||
};
|
||||
use sim::Player;
|
||||
|
||||
use crate::assets::{snapshot_for_asset, EditorAsset, EditorAssetKind};
|
||||
use crate::camera::EditorCamera;
|
||||
use crate::gizmos::{EditorGizmoMode, EditorGizmoSpace};
|
||||
use crate::history::{set_material_with_history, spawn_with_history, EditorEntitySnapshot};
|
||||
use crate::play::default_player_spawn;
|
||||
use crate::scene_io::SceneIo;
|
||||
use crate::viewport::{recall_camera_bookmark, save_camera_bookmark, CameraBookmarks};
|
||||
|
||||
pub use super::play_controls::{toggle_play_mode, toggle_play_paused, toggle_possession};
|
||||
pub use super::selection_ops::{
|
||||
delete_selection, duplicate_selection, entity_name, focus_editor_camera_on_selection,
|
||||
is_level_object, selected_level_entities,
|
||||
};
|
||||
|
||||
pub fn set_gizmo_mode(world: &mut World, mode: EditorGizmoMode) {
|
||||
*world.resource_mut::<EditorGizmoMode>() = mode;
|
||||
}
|
||||
|
||||
pub fn set_gizmo_space(world: &mut World, space: EditorGizmoSpace) {
|
||||
*world.resource_mut::<EditorGizmoSpace>() = space;
|
||||
}
|
||||
|
||||
pub fn viewport_save_bookmark(world: &mut World) {
|
||||
let scene_key = world
|
||||
.resource::<SceneIo>()
|
||||
.active_path
|
||||
.as_ref()
|
||||
.map(|path| path.display().to_string())
|
||||
.unwrap_or_else(|| "__unsaved__".into());
|
||||
let Some(transform) = world
|
||||
.query_filtered::<&Transform, With<EditorCamera>>()
|
||||
.single(world)
|
||||
.ok()
|
||||
.copied()
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let mut bookmarks = world.resource_mut::<CameraBookmarks>();
|
||||
save_camera_bookmark(&mut bookmarks, &scene_key, transform);
|
||||
}
|
||||
|
||||
pub fn viewport_recall_bookmark(world: &mut World) {
|
||||
let scene_key = world
|
||||
.resource::<SceneIo>()
|
||||
.active_path
|
||||
.as_ref()
|
||||
.map(|path| path.display().to_string())
|
||||
.unwrap_or_else(|| "__unsaved__".into());
|
||||
let saved = {
|
||||
let bookmarks = world.resource::<CameraBookmarks>();
|
||||
match recall_camera_bookmark(bookmarks, &scene_key) {
|
||||
Some(transform) => transform,
|
||||
None => return,
|
||||
}
|
||||
};
|
||||
for mut transform in world
|
||||
.query_filtered::<&mut Transform, With<EditorCamera>>()
|
||||
.iter_mut(world)
|
||||
{
|
||||
*transform = saved;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn primitive_snapshot(name: &str, shape: PrimitiveShape, origin: Vec3) -> EditorEntitySnapshot {
|
||||
let asset = EditorAsset {
|
||||
label: name.to_string(),
|
||||
path: None,
|
||||
folder_path: crate::assets::BUILTINS_FOLDER.to_string(),
|
||||
kind: EditorAssetKind::Primitive(shape),
|
||||
};
|
||||
snapshot_for_asset(&asset, origin).expect("primitive assets are spawnable")
|
||||
}
|
||||
|
||||
pub fn light_snapshot(name: &str, translation: Vec3) -> EditorEntitySnapshot {
|
||||
EditorEntitySnapshot {
|
||||
actor_id: None,
|
||||
actor_kind: shared::ActorKind::Light,
|
||||
actor_name: None,
|
||||
name: Some(name.to_string()),
|
||||
transform: Transform::from_translation(translation),
|
||||
primitive: None,
|
||||
static_mesh_renderer: None,
|
||||
material: None,
|
||||
material_override: None,
|
||||
rigid_body: None,
|
||||
collider: None,
|
||||
physics: None,
|
||||
light: Some(LightDesc::default()),
|
||||
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: shared::EditorVisibility::default(),
|
||||
children: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn ensure_player_spawn_for_edit(world: &mut World) -> Entity {
|
||||
if let Some(entity) = world
|
||||
.query_filtered::<Entity, With<PlayerSpawn>>()
|
||||
.iter(world)
|
||||
.next()
|
||||
{
|
||||
return entity;
|
||||
}
|
||||
|
||||
let transform = world
|
||||
.query_filtered::<&Transform, With<Player>>()
|
||||
.iter(world)
|
||||
.next()
|
||||
.copied()
|
||||
.unwrap_or_else(default_player_spawn);
|
||||
|
||||
spawn_with_history(
|
||||
world,
|
||||
EditorEntitySnapshot {
|
||||
actor_id: None,
|
||||
actor_kind: shared::ActorKind::PlayerSpawn,
|
||||
actor_name: None,
|
||||
name: Some("Player Start".to_string()),
|
||||
transform,
|
||||
primitive: None,
|
||||
static_mesh_renderer: None,
|
||||
material: None,
|
||||
material_override: None,
|
||||
rigid_body: None,
|
||||
collider: None,
|
||||
physics: None,
|
||||
light: None,
|
||||
player_spawn: true,
|
||||
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: shared::EditorVisibility::default(),
|
||||
children: Vec::new(),
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/// Removes all authored [`LightDesc`] so project sun/ambient drive outdoor lighting.
|
||||
pub fn reset_scene_lighting_to_project_defaults(world: &mut World) {
|
||||
let mut query = world.query_filtered::<Entity, With<LevelObject>>();
|
||||
let with_lights: Vec<Entity> = query
|
||||
.iter(world)
|
||||
.filter(|entity| world.get::<LightDesc>(*entity).is_some())
|
||||
.collect();
|
||||
for entity in with_lights {
|
||||
if let Ok(mut entity_mut) = world.get_entity_mut(entity) {
|
||||
entity_mut.remove::<LightDesc>();
|
||||
}
|
||||
}
|
||||
world
|
||||
.resource_mut::<crate::scene_io::SceneIo>()
|
||||
.mark_dirty();
|
||||
}
|
||||
|
||||
/// Removes authored directional lights so [`ProjectSun`] drives outdoor lighting.
|
||||
pub fn use_project_sun(world: &mut World) {
|
||||
let mut query = world.query_filtered::<(Entity, &LightDesc), With<LevelObject>>();
|
||||
let directionals: Vec<Entity> = query
|
||||
.iter(world)
|
||||
.filter(|(_, light)| matches!(light.kind, AuthoringLightKind::Directional))
|
||||
.map(|(e, _)| e)
|
||||
.collect();
|
||||
for entity in directionals {
|
||||
if let Ok(mut entity_mut) = world.get_entity_mut(entity) {
|
||||
entity_mut.remove::<LightDesc>();
|
||||
}
|
||||
}
|
||||
world
|
||||
.resource_mut::<crate::scene_io::SceneIo>()
|
||||
.mark_dirty();
|
||||
}
|
||||
|
||||
pub fn create_scene_sun_override_from_project_settings(world: &mut World) -> Entity {
|
||||
let (transform, light) = {
|
||||
let sun_illuminance = world
|
||||
.resource::<settings::ProjectSettings>()
|
||||
.rendering
|
||||
.sun_illuminance;
|
||||
let transform = world
|
||||
.query_filtered::<&Transform, With<ProjectSun>>()
|
||||
.iter(world)
|
||||
.next()
|
||||
.copied()
|
||||
.unwrap_or_else(|| {
|
||||
Transform::from_xyz(0.0, 0.0, 0.0)
|
||||
.looking_to(Vec3::new(-0.35, -0.85, -0.4), Vec3::Y)
|
||||
});
|
||||
let mut light = LightDesc::for_kind(AuthoringLightKind::Directional);
|
||||
light.intensity = sun_illuminance;
|
||||
(transform, light)
|
||||
};
|
||||
|
||||
spawn_with_history(
|
||||
world,
|
||||
EditorEntitySnapshot {
|
||||
actor_id: None,
|
||||
actor_kind: shared::ActorKind::Light,
|
||||
actor_name: None,
|
||||
name: Some("Scene Sun".to_string()),
|
||||
transform,
|
||||
primitive: None,
|
||||
static_mesh_renderer: None,
|
||||
material: None,
|
||||
material_override: None,
|
||||
rigid_body: None,
|
||||
collider: None,
|
||||
physics: None,
|
||||
light: Some(light),
|
||||
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: shared::EditorVisibility::default(),
|
||||
children: Vec::new(),
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
pub fn asset_label(asset: &EditorAsset) -> String {
|
||||
let prefix = match asset.kind {
|
||||
EditorAssetKind::Primitive(_) => "Primitive",
|
||||
EditorAssetKind::Light(_) => "Light",
|
||||
EditorAssetKind::Model => "Model",
|
||||
EditorAssetKind::Texture => "Texture",
|
||||
EditorAssetKind::Material => "Material",
|
||||
EditorAssetKind::Level => "Level",
|
||||
EditorAssetKind::Prefab => "Prefab",
|
||||
EditorAssetKind::PostProcessVolume => "Post Process Volume",
|
||||
EditorAssetKind::PostProcessEffect => "Post FX",
|
||||
EditorAssetKind::RenderingProfile => "Rendering Profile",
|
||||
EditorAssetKind::ShaderSchema => "Shader Schema",
|
||||
};
|
||||
format!("{prefix}: {}", asset.label)
|
||||
}
|
||||
|
||||
pub fn apply_texture_to_selection(
|
||||
world: &mut World,
|
||||
asset: &EditorAsset,
|
||||
selected: &SelectedEntities,
|
||||
) {
|
||||
let Some(path) = asset.path.clone() else {
|
||||
return;
|
||||
};
|
||||
for entity in selected_level_entities(world, selected) {
|
||||
let mut material = world
|
||||
.get::<MaterialDesc>(entity)
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
material.base_color_texture = Some(path.clone());
|
||||
set_material_with_history(world, entity, material);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn apply_material_asset_to_selection(
|
||||
world: &mut World,
|
||||
asset: &EditorAsset,
|
||||
selected: &SelectedEntities,
|
||||
) {
|
||||
crate::assets::materials::apply_material_asset_to_selection(world, asset, selected);
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum HierarchyNodeKind {
|
||||
Authored,
|
||||
Runtime,
|
||||
Generated,
|
||||
}
|
||||
@@ -0,0 +1,718 @@
|
||||
//! Hierarchy outliner: tree view, drag-and-drop, visibility, and lock toggles.
|
||||
|
||||
use bevy::prelude::*;
|
||||
use bevy_egui::egui;
|
||||
use bevy_inspector_egui::bevy_inspector::hierarchy::SelectedEntities;
|
||||
use egui::containers::scroll_area::ScrollSource;
|
||||
use egui_phosphor_icons::icons;
|
||||
use shared::EditorVisibility;
|
||||
|
||||
use crate::history::{
|
||||
create_empty_child_with_history, delete_entities_with_history, duplicate_entities_with_history,
|
||||
group_selection_with_history, rename_entity_with_history, reorder_siblings_with_history,
|
||||
reparent_with_history, set_editor_visibility_with_history,
|
||||
};
|
||||
use crate::project_io::UserPreferences;
|
||||
use crate::selection::SelectedEntity;
|
||||
use crate::ui::helpers::{
|
||||
entity_name, focus_editor_camera_on_selection, is_level_object, HierarchyNodeKind,
|
||||
};
|
||||
use crate::ui::hierarchy_ops::{
|
||||
authored_children, editor_visibility, entity_hierarchy_path, entity_matches_filter,
|
||||
hierarchy_label_for_entity, is_entity_locked, level_object_roots, sort_siblings,
|
||||
would_create_cycle,
|
||||
};
|
||||
use crate::ui::hierarchy_state::{HierarchyPanelState, HierarchySort};
|
||||
use crate::ui::theme::panel_heading;
|
||||
|
||||
#[derive(Clone)]
|
||||
struct HierarchyDragPayload {
|
||||
entities: Vec<Entity>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum DropTarget {
|
||||
Root,
|
||||
On(Entity),
|
||||
Before(Entity),
|
||||
}
|
||||
|
||||
pub fn hierarchy_panel_ui(
|
||||
world: &mut World,
|
||||
ui: &mut egui::Ui,
|
||||
selected_entities: &mut SelectedEntities,
|
||||
renaming_entity: &mut Option<Entity>,
|
||||
rename_buffer: &mut String,
|
||||
) {
|
||||
let (filter, sort_mode, show_generated, show_runtime, _expanded, _locked, prefs_paths) = {
|
||||
let state = world.resource::<HierarchyPanelState>();
|
||||
(
|
||||
state.filter.clone(),
|
||||
state.sort_mode,
|
||||
state.show_generated,
|
||||
state.show_runtime,
|
||||
state.expanded.clone(),
|
||||
state.locked.clone(),
|
||||
world
|
||||
.resource::<UserPreferences>()
|
||||
.hierarchy_expanded_paths
|
||||
.clone(),
|
||||
)
|
||||
};
|
||||
|
||||
if _expanded.is_empty() && !prefs_paths.is_empty() {
|
||||
let synced = crate::ui::hierarchy_state::expanded_entities_for_paths(world, &prefs_paths);
|
||||
world.resource_mut::<HierarchyPanelState>().expanded = synced;
|
||||
}
|
||||
|
||||
let expanded = world.resource::<HierarchyPanelState>().expanded.clone();
|
||||
let locked = world.resource::<HierarchyPanelState>().locked.clone();
|
||||
|
||||
let mut filter = filter;
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(icons::MAGNIFYING_GLASS.regular());
|
||||
if ui
|
||||
.add(
|
||||
egui::TextEdit::singleline(&mut filter)
|
||||
.hint_text("Search hierarchy...")
|
||||
.desired_width(f32::INFINITY),
|
||||
)
|
||||
.changed()
|
||||
{
|
||||
world.resource_mut::<HierarchyPanelState>().filter = filter.clone();
|
||||
world.resource_mut::<HierarchyPanelState>().mark_dirty();
|
||||
}
|
||||
});
|
||||
|
||||
ui.horizontal(|ui| {
|
||||
ui.label("Sort:");
|
||||
let mut sort = sort_mode;
|
||||
egui::ComboBox::from_id_salt("hierarchy_sort")
|
||||
.selected_text(sort_label(sort))
|
||||
.show_ui(ui, |ui| {
|
||||
for candidate in [
|
||||
HierarchySort::Manual,
|
||||
HierarchySort::Name,
|
||||
HierarchySort::Type,
|
||||
] {
|
||||
if ui
|
||||
.selectable_value(&mut sort, candidate, sort_label(candidate))
|
||||
.clicked()
|
||||
{
|
||||
world.resource_mut::<HierarchyPanelState>().sort_mode = candidate;
|
||||
world.resource_mut::<HierarchyPanelState>().mark_dirty();
|
||||
}
|
||||
}
|
||||
});
|
||||
let mut show_gen = show_generated;
|
||||
if ui.checkbox(&mut show_gen, "Generated").changed() {
|
||||
world.resource_mut::<HierarchyPanelState>().show_generated = show_gen;
|
||||
world.resource_mut::<HierarchyPanelState>().mark_dirty();
|
||||
}
|
||||
let mut show_rt = show_runtime;
|
||||
if ui.checkbox(&mut show_rt, "Runtime").changed() {
|
||||
world.resource_mut::<HierarchyPanelState>().show_runtime = show_rt;
|
||||
world.resource_mut::<HierarchyPanelState>().mark_dirty();
|
||||
}
|
||||
});
|
||||
|
||||
ui.add_space(4.0);
|
||||
ui.label(panel_heading("Scene"));
|
||||
|
||||
if ui.input(|input| input.key_pressed(egui::Key::F2)) {
|
||||
if let Some(entity) = selected_entities.as_slice().first().copied() {
|
||||
if is_level_object(world, entity) {
|
||||
*renaming_entity = Some(entity);
|
||||
*rename_buffer = entity_name(world, entity);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let filter_lower = filter.trim().to_lowercase();
|
||||
let mut drop_target = None;
|
||||
let mut invalid_drop = false;
|
||||
|
||||
let dragging = world
|
||||
.resource::<HierarchyPanelState>()
|
||||
.active_drag
|
||||
.is_some();
|
||||
|
||||
egui::ScrollArea::vertical()
|
||||
.scroll_source(ScrollSource {
|
||||
scroll_bar: true,
|
||||
drag: !dragging,
|
||||
mouse_wheel: true,
|
||||
})
|
||||
.show(ui, |ui| {
|
||||
ui.spacing_mut().item_spacing.y = 2.0;
|
||||
|
||||
if dragging {
|
||||
draw_root_drop_zone(ui, &mut drop_target);
|
||||
}
|
||||
|
||||
let mut roots = level_object_roots(world);
|
||||
sort_siblings(world, &mut roots, sort_mode);
|
||||
|
||||
let visible_roots: Vec<Entity> = roots
|
||||
.into_iter()
|
||||
.filter(|entity| subtree_matches_filter(world, *entity, &filter_lower, sort_mode))
|
||||
.collect();
|
||||
|
||||
for entity in visible_roots {
|
||||
draw_authored_node(
|
||||
world,
|
||||
ui,
|
||||
entity,
|
||||
0,
|
||||
selected_entities,
|
||||
renaming_entity,
|
||||
rename_buffer,
|
||||
&filter_lower,
|
||||
sort_mode,
|
||||
show_generated,
|
||||
dragging,
|
||||
&expanded,
|
||||
&locked,
|
||||
&prefs_paths,
|
||||
&mut drop_target,
|
||||
&mut invalid_drop,
|
||||
);
|
||||
}
|
||||
|
||||
if show_runtime {
|
||||
let runtime_roots = runtime_roots(world);
|
||||
if !runtime_roots.is_empty() {
|
||||
ui.add_space(6.0);
|
||||
ui.small(egui::RichText::new("Runtime").weak());
|
||||
for entity in runtime_roots {
|
||||
draw_runtime_node(world, ui, entity, 0, selected_entities, show_runtime);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if ui.ctx().input(|input| input.pointer.any_released()) {
|
||||
if let Some(target) = drop_target {
|
||||
let drag_entities = world
|
||||
.resource_mut::<HierarchyPanelState>()
|
||||
.active_drag
|
||||
.take();
|
||||
if let Some(entities) = drag_entities {
|
||||
let payload = HierarchyDragPayload { entities };
|
||||
apply_drop(world, &payload, target, invalid_drop);
|
||||
}
|
||||
} else {
|
||||
world.resource_mut::<HierarchyPanelState>().active_drag = None;
|
||||
}
|
||||
}
|
||||
|
||||
if selected_entities.as_slice().first().copied() != world.resource::<SelectedEntity>().0 {
|
||||
world.resource_mut::<SelectedEntity>().0 = selected_entities.as_slice().first().copied();
|
||||
}
|
||||
}
|
||||
|
||||
fn sort_label(sort: HierarchySort) -> &'static str {
|
||||
match sort {
|
||||
HierarchySort::Manual => "Manual",
|
||||
HierarchySort::Name => "Name",
|
||||
HierarchySort::Type => "Type",
|
||||
}
|
||||
}
|
||||
|
||||
fn draw_root_drop_zone(ui: &mut egui::Ui, drop_target: &mut Option<DropTarget>) {
|
||||
let (rect, response) =
|
||||
ui.allocate_exact_size(egui::vec2(ui.available_width(), 2.0), egui::Sense::hover());
|
||||
if let Some(hover) = response.dnd_hover_payload::<HierarchyDragPayload>() {
|
||||
ui.painter()
|
||||
.rect_filled(rect, 1.0, egui::Color32::from_rgb(80, 120, 200));
|
||||
*drop_target = Some(DropTarget::Root);
|
||||
let _ = hover;
|
||||
}
|
||||
}
|
||||
|
||||
fn draw_authored_node(
|
||||
world: &mut World,
|
||||
ui: &mut egui::Ui,
|
||||
entity: Entity,
|
||||
depth: usize,
|
||||
selected_entities: &mut SelectedEntities,
|
||||
renaming_entity: &mut Option<Entity>,
|
||||
rename_buffer: &mut String,
|
||||
filter_lower: &str,
|
||||
sort_mode: HierarchySort,
|
||||
show_generated: bool,
|
||||
drag_active: bool,
|
||||
expanded: &std::collections::HashSet<Entity>,
|
||||
locked: &std::collections::HashSet<Entity>,
|
||||
prefs_paths: &[String],
|
||||
drop_target: &mut Option<DropTarget>,
|
||||
invalid_drop: &mut bool,
|
||||
) {
|
||||
let path = entity_hierarchy_path(world, entity);
|
||||
let mut is_expanded = expanded.contains(&entity) || prefs_paths.iter().any(|p| p == &path);
|
||||
let has_children = authored_children(world, entity)
|
||||
.iter()
|
||||
.any(|child| subtree_matches_filter(world, *child, filter_lower, sort_mode))
|
||||
|| (show_generated
|
||||
&& world.get::<Children>(entity).is_some_and(|children| {
|
||||
children
|
||||
.iter()
|
||||
.any(|child| is_hierarchy_generated_child(world, child))
|
||||
}));
|
||||
|
||||
draw_drop_before(
|
||||
world,
|
||||
ui,
|
||||
entity,
|
||||
depth,
|
||||
drag_active,
|
||||
drop_target,
|
||||
invalid_drop,
|
||||
);
|
||||
|
||||
ui.horizontal(|ui| {
|
||||
ui.add_space(depth as f32 * 14.0);
|
||||
if has_children {
|
||||
let twistie = if is_expanded {
|
||||
icons::CARET_DOWN
|
||||
} else {
|
||||
icons::CARET_RIGHT
|
||||
};
|
||||
if ui.small_button(twistie.as_str()).clicked() {
|
||||
let path = path.clone();
|
||||
let expanding = !world
|
||||
.resource::<HierarchyPanelState>()
|
||||
.expanded
|
||||
.contains(&entity);
|
||||
{
|
||||
let mut state = world.resource_mut::<HierarchyPanelState>();
|
||||
if expanding {
|
||||
state.expanded.insert(entity);
|
||||
} else {
|
||||
state.expanded.remove(&entity);
|
||||
}
|
||||
state.mark_dirty();
|
||||
}
|
||||
let mut prefs = world.resource_mut::<UserPreferences>();
|
||||
if expanding {
|
||||
if !prefs
|
||||
.hierarchy_expanded_paths
|
||||
.iter()
|
||||
.any(|entry| entry == &path)
|
||||
{
|
||||
prefs.hierarchy_expanded_paths.push(path);
|
||||
}
|
||||
} else {
|
||||
prefs
|
||||
.hierarchy_expanded_paths
|
||||
.retain(|entry| entry != &path);
|
||||
}
|
||||
is_expanded = expanding;
|
||||
}
|
||||
} else {
|
||||
ui.add_space(18.0);
|
||||
}
|
||||
|
||||
let visible = editor_visibility(world, entity).visible;
|
||||
let eye_icon = if visible {
|
||||
icons::EYE.regular()
|
||||
} else {
|
||||
icons::EYE_SLASH.regular()
|
||||
};
|
||||
if ui.small_button(eye_icon).clicked() {
|
||||
set_editor_visibility_with_history(
|
||||
world,
|
||||
entity,
|
||||
EditorVisibility { visible: !visible },
|
||||
);
|
||||
}
|
||||
|
||||
let is_locked = is_entity_locked(locked, entity);
|
||||
let lock_icon = if is_locked {
|
||||
icons::LOCK.regular()
|
||||
} else {
|
||||
icons::LOCK_OPEN.regular()
|
||||
};
|
||||
if ui.small_button(lock_icon).clicked() {
|
||||
let mut state = world.resource_mut::<HierarchyPanelState>();
|
||||
if is_locked {
|
||||
state.locked.remove(&entity);
|
||||
} else {
|
||||
state.locked.insert(entity);
|
||||
}
|
||||
}
|
||||
|
||||
if *renaming_entity == Some(entity) {
|
||||
let response = ui.text_edit_singleline(rename_buffer);
|
||||
let commit =
|
||||
response.lost_focus() || ui.input(|input| input.key_pressed(egui::Key::Enter));
|
||||
if commit {
|
||||
rename_entity_with_history(world, entity, rename_buffer.clone());
|
||||
*renaming_entity = None;
|
||||
}
|
||||
} else {
|
||||
let selected = selected_entities.contains(entity);
|
||||
let label = hierarchy_label_for_entity(world, entity, HierarchyNodeKind::Authored);
|
||||
let response = ui.selectable_label(selected, label);
|
||||
if response.clicked() && !is_locked {
|
||||
let additive = ui.input(|input| {
|
||||
input.modifiers.shift || input.modifiers.command || input.modifiers.ctrl
|
||||
});
|
||||
if additive {
|
||||
selected_entities.select_maybe_add(entity, true);
|
||||
} else {
|
||||
selected_entities.select_replace(entity);
|
||||
}
|
||||
world.resource_mut::<SelectedEntity>().0 = Some(entity);
|
||||
}
|
||||
if response.double_clicked() && is_level_object(world, entity) {
|
||||
*renaming_entity = Some(entity);
|
||||
*rename_buffer = entity_name(world, entity);
|
||||
}
|
||||
|
||||
if response.drag_started() {
|
||||
let drag_entities: Vec<Entity> = if selected_entities.contains(entity) {
|
||||
selected_entities
|
||||
.iter()
|
||||
.filter(|e| is_level_object(world, *e))
|
||||
.collect()
|
||||
} else {
|
||||
vec![entity]
|
||||
};
|
||||
response.dnd_set_drag_payload(HierarchyDragPayload {
|
||||
entities: drag_entities.clone(),
|
||||
});
|
||||
world.resource_mut::<HierarchyPanelState>().active_drag = Some(drag_entities);
|
||||
}
|
||||
|
||||
if let Some(hover) = response.dnd_hover_payload::<HierarchyDragPayload>() {
|
||||
let invalid = would_create_cycle(world, &hover.entities, Some(entity));
|
||||
*invalid_drop = invalid;
|
||||
*drop_target = Some(DropTarget::On(entity));
|
||||
if invalid {
|
||||
ui.painter().rect_stroke(
|
||||
response.rect,
|
||||
2.0,
|
||||
egui::Stroke::new(2.0, egui::Color32::RED),
|
||||
egui::StrokeKind::Outside,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
response.context_menu(|ui| {
|
||||
authored_context_menu(
|
||||
world,
|
||||
ui,
|
||||
entity,
|
||||
selected_entities,
|
||||
renaming_entity,
|
||||
rename_buffer,
|
||||
)
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
if !is_expanded {
|
||||
return;
|
||||
}
|
||||
|
||||
let mut children = authored_children(world, entity);
|
||||
sort_siblings(world, &mut children, sort_mode);
|
||||
for child in children {
|
||||
if subtree_matches_filter(world, child, filter_lower, sort_mode) {
|
||||
draw_authored_node(
|
||||
world,
|
||||
ui,
|
||||
child,
|
||||
depth + 1,
|
||||
selected_entities,
|
||||
renaming_entity,
|
||||
rename_buffer,
|
||||
filter_lower,
|
||||
sort_mode,
|
||||
show_generated,
|
||||
drag_active,
|
||||
expanded,
|
||||
locked,
|
||||
prefs_paths,
|
||||
drop_target,
|
||||
invalid_drop,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if show_generated {
|
||||
if let Some(children) = world.get::<Children>(entity) {
|
||||
for child in children.iter() {
|
||||
if is_hierarchy_generated_child(world, child) {
|
||||
draw_generated_node(world, ui, child, depth + 1, expanded, show_generated);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn draw_drop_before(
|
||||
world: &World,
|
||||
ui: &mut egui::Ui,
|
||||
entity: Entity,
|
||||
depth: usize,
|
||||
drag_active: bool,
|
||||
drop_target: &mut Option<DropTarget>,
|
||||
invalid_drop: &mut bool,
|
||||
) {
|
||||
if !drag_active {
|
||||
return;
|
||||
}
|
||||
|
||||
ui.horizontal(|ui| {
|
||||
ui.add_space(depth as f32 * 14.0 + 18.0);
|
||||
let (rect, response) =
|
||||
ui.allocate_exact_size(egui::vec2(ui.available_width(), 2.0), egui::Sense::hover());
|
||||
if let Some(hover) = response.dnd_hover_payload::<HierarchyDragPayload>() {
|
||||
*invalid_drop = would_create_cycle(
|
||||
world,
|
||||
&hover.entities,
|
||||
world
|
||||
.get::<ChildOf>(entity)
|
||||
.map(|child_of| child_of.parent()),
|
||||
);
|
||||
*drop_target = Some(DropTarget::Before(entity));
|
||||
let color = if *invalid_drop {
|
||||
egui::Color32::RED
|
||||
} else {
|
||||
egui::Color32::from_rgb(80, 120, 200)
|
||||
};
|
||||
ui.painter().rect_filled(rect, 1.0, color);
|
||||
let _ = hover;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn draw_generated_node(
|
||||
world: &World,
|
||||
ui: &mut egui::Ui,
|
||||
entity: Entity,
|
||||
depth: usize,
|
||||
expanded: &std::collections::HashSet<Entity>,
|
||||
show_generated: bool,
|
||||
) {
|
||||
let _ = show_generated;
|
||||
let has_children = world.get::<Children>(entity).is_some_and(|children| {
|
||||
children
|
||||
.iter()
|
||||
.any(|child| is_hierarchy_generated_child(world, child))
|
||||
});
|
||||
let mut is_expanded = expanded.contains(&entity);
|
||||
ui.horizontal(|ui| {
|
||||
ui.add_space(depth as f32 * 14.0);
|
||||
if has_children {
|
||||
let twistie = if is_expanded {
|
||||
icons::CARET_DOWN
|
||||
} else {
|
||||
icons::CARET_RIGHT
|
||||
};
|
||||
if ui.small_button(twistie.as_str()).clicked() {
|
||||
is_expanded = !is_expanded;
|
||||
}
|
||||
} else {
|
||||
ui.add_space(18.0);
|
||||
}
|
||||
ui.add_enabled(
|
||||
false,
|
||||
egui::Label::new(
|
||||
egui::RichText::new(hierarchy_label_for_entity(
|
||||
world,
|
||||
entity,
|
||||
HierarchyNodeKind::Generated,
|
||||
))
|
||||
.weak(),
|
||||
),
|
||||
);
|
||||
});
|
||||
if !is_expanded {
|
||||
return;
|
||||
}
|
||||
if let Some(children) = world.get::<Children>(entity) {
|
||||
for child in children.iter() {
|
||||
if is_hierarchy_generated_child(world, child) {
|
||||
draw_generated_node(world, ui, child, depth + 1, expanded, show_generated);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn draw_runtime_node(
|
||||
world: &World,
|
||||
ui: &mut egui::Ui,
|
||||
entity: Entity,
|
||||
depth: usize,
|
||||
selected_entities: &mut SelectedEntities,
|
||||
show_runtime: bool,
|
||||
) {
|
||||
let _ = show_runtime;
|
||||
ui.horizontal(|ui| {
|
||||
ui.add_space(depth as f32 * 14.0);
|
||||
ui.add_space(18.0);
|
||||
let label = hierarchy_label_for_entity(world, entity, HierarchyNodeKind::Runtime);
|
||||
let response = ui.selectable_label(selected_entities.contains(entity), label);
|
||||
if response.clicked() {
|
||||
selected_entities.select_replace(entity);
|
||||
}
|
||||
response.context_menu(|ui| {
|
||||
if ui.button("Focus").clicked() {
|
||||
selected_entities.select_replace(entity);
|
||||
ui.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
if let Some(children) = world.get::<Children>(entity) {
|
||||
for child in children.iter() {
|
||||
if is_runtime_hierarchy_entity(world, child) {
|
||||
draw_runtime_node(world, ui, child, depth + 1, selected_entities, show_runtime);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn authored_context_menu(
|
||||
world: &mut World,
|
||||
ui: &mut egui::Ui,
|
||||
entity: Entity,
|
||||
selected_entities: &mut SelectedEntities,
|
||||
renaming_entity: &mut Option<Entity>,
|
||||
rename_buffer: &mut String,
|
||||
) {
|
||||
if ui.button("Rename").clicked() {
|
||||
*renaming_entity = Some(entity);
|
||||
*rename_buffer = entity_name(world, entity);
|
||||
ui.close();
|
||||
}
|
||||
if ui.button("Duplicate").clicked() {
|
||||
duplicate_entities_with_history(world, &[entity]);
|
||||
ui.close();
|
||||
}
|
||||
if ui.button("Delete").clicked() {
|
||||
delete_entities_with_history(world, &[entity]);
|
||||
ui.close();
|
||||
}
|
||||
if selected_entities.len() >= 2 && selected_entities.contains(entity) {
|
||||
if ui.button("Group").clicked() {
|
||||
let entities: Vec<Entity> = selected_entities
|
||||
.iter()
|
||||
.filter(|e| is_level_object(world, *e))
|
||||
.collect();
|
||||
group_selection_with_history(world, &entities);
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
if ui.button("Unparent").clicked() {
|
||||
reparent_with_history(world, entity, None);
|
||||
ui.close();
|
||||
}
|
||||
if ui.button("Create child Empty").clicked() {
|
||||
create_empty_child_with_history(world, entity);
|
||||
ui.close();
|
||||
}
|
||||
if ui.button("Focus").clicked() {
|
||||
selected_entities.select_replace(entity);
|
||||
world.resource_mut::<SelectedEntity>().0 = Some(entity);
|
||||
focus_editor_camera_on_selection(world);
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_drop(world: &mut World, drag: &HierarchyDragPayload, target: DropTarget, invalid: bool) {
|
||||
if invalid || drag.entities.is_empty() {
|
||||
return;
|
||||
}
|
||||
match target {
|
||||
DropTarget::Root => {
|
||||
reorder_siblings_with_history(world, &drag.entities, None, i32::MAX);
|
||||
}
|
||||
DropTarget::On(parent) => {
|
||||
reorder_siblings_with_history(world, &drag.entities, Some(parent), i32::MAX);
|
||||
}
|
||||
DropTarget::Before(before) => {
|
||||
let parent = world
|
||||
.get::<ChildOf>(before)
|
||||
.map(|child_of| child_of.parent());
|
||||
let siblings = match parent {
|
||||
Some(parent) => authored_children(world, parent),
|
||||
None => level_object_roots(world),
|
||||
};
|
||||
let insert_index = siblings
|
||||
.iter()
|
||||
.position(|entity| *entity == before)
|
||||
.unwrap_or(siblings.len()) as i32;
|
||||
reorder_siblings_with_history(world, &drag.entities, parent, insert_index);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn subtree_matches_filter(
|
||||
world: &World,
|
||||
entity: Entity,
|
||||
filter_lower: &str,
|
||||
sort_mode: HierarchySort,
|
||||
) -> bool {
|
||||
if filter_lower.is_empty() {
|
||||
return true;
|
||||
}
|
||||
if entity_matches_filter(world, entity, filter_lower) {
|
||||
return true;
|
||||
}
|
||||
let mut children = authored_children(world, entity);
|
||||
sort_siblings(world, &mut children, sort_mode);
|
||||
children
|
||||
.iter()
|
||||
.any(|child| subtree_matches_filter(world, *child, filter_lower, sort_mode))
|
||||
}
|
||||
|
||||
fn runtime_roots(world: &mut World) -> Vec<Entity> {
|
||||
use shared::ProjectSun;
|
||||
use sim::{Player, PlayerCamera};
|
||||
|
||||
let mut query = world.query_filtered::<
|
||||
(Entity, Option<&ChildOf>),
|
||||
Or<(With<Player>, With<PlayerCamera>, With<ProjectSun>)>,
|
||||
>();
|
||||
query
|
||||
.iter(world)
|
||||
.filter_map(|(entity, parent)| {
|
||||
if parent
|
||||
.map(|parent| is_runtime_hierarchy_entity(world, parent.parent()))
|
||||
.unwrap_or(false)
|
||||
{
|
||||
None
|
||||
} else {
|
||||
Some(entity)
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(crate) fn is_hierarchy_generated_child(world: &World, entity: Entity) -> bool {
|
||||
use shared::LevelObject;
|
||||
world.get_entity(entity).is_ok_and(|entity_ref| {
|
||||
!entity_ref.contains::<crate::infra::EditorOnly>()
|
||||
&& !entity_ref.contains::<LevelObject>()
|
||||
&& !entity_ref.contains::<crate::visualizers::EditorVisualizerProxy>()
|
||||
&& (entity_ref.contains::<Transform>() || entity_ref.contains::<GlobalTransform>())
|
||||
&& (entity_ref.contains::<Name>()
|
||||
|| entity_ref.contains::<Mesh3d>()
|
||||
|| entity_ref.contains::<SceneRoot>())
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn is_runtime_hierarchy_entity(world: &World, entity: Entity) -> bool {
|
||||
use shared::ProjectSun;
|
||||
use sim::{Player, PlayerCamera};
|
||||
|
||||
world.get_entity(entity).is_ok_and(|entity_ref| {
|
||||
!entity_ref.contains::<crate::infra::EditorOnly>()
|
||||
&& (entity_ref.contains::<Player>()
|
||||
|| entity_ref.contains::<PlayerCamera>()
|
||||
|| entity_ref.contains::<ProjectSun>())
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,445 @@
|
||||
//! Hierarchy tree building, sibling ordering, and reparent helpers.
|
||||
|
||||
use bevy::prelude::*;
|
||||
use shared::{
|
||||
ActorKind, AuthoringLightKind, EditorVisibility, HierarchySiblingIndex, LevelObject, LightDesc,
|
||||
ModelRef, PhysicsBody, PlayerSpawn,
|
||||
};
|
||||
|
||||
use super::helpers::{entity_name, is_level_object, HierarchyNodeKind};
|
||||
use super::hierarchy_state::HierarchySort;
|
||||
use crate::history::SiblingChange;
|
||||
|
||||
pub fn sibling_index(world: &World, entity: Entity) -> i32 {
|
||||
world
|
||||
.get::<HierarchySiblingIndex>(entity)
|
||||
.map(|index| index.0)
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
pub fn is_ancestor(world: &World, ancestor: Entity, descendant: Entity) -> bool {
|
||||
if ancestor == descendant {
|
||||
return true;
|
||||
}
|
||||
let mut current = world
|
||||
.get::<ChildOf>(descendant)
|
||||
.map(|child_of| child_of.parent());
|
||||
while let Some(entity) = current {
|
||||
if entity == ancestor {
|
||||
return true;
|
||||
}
|
||||
current = world
|
||||
.get::<ChildOf>(entity)
|
||||
.map(|child_of| child_of.parent());
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
pub fn would_create_cycle(world: &World, targets: &[Entity], new_parent: Option<Entity>) -> bool {
|
||||
let Some(parent) = new_parent else {
|
||||
return false;
|
||||
};
|
||||
targets
|
||||
.iter()
|
||||
.any(|entity| is_ancestor(world, *entity, parent))
|
||||
}
|
||||
|
||||
pub fn level_object_roots(world: &mut World) -> Vec<Entity> {
|
||||
let mut query = world.query_filtered::<(Entity, Option<&ChildOf>), With<LevelObject>>();
|
||||
query
|
||||
.iter(world)
|
||||
.filter_map(|(entity, parent)| match parent {
|
||||
Some(parent) if is_level_object(world, parent.parent()) => None,
|
||||
_ => Some(entity),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn authored_children(world: &World, parent: Entity) -> Vec<Entity> {
|
||||
world
|
||||
.get::<Children>(parent)
|
||||
.map(|children| {
|
||||
children
|
||||
.iter()
|
||||
.filter(|child| is_level_object(world, *child))
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn entity_tie_break(a: Entity, b: Entity) -> std::cmp::Ordering {
|
||||
a.to_bits().cmp(&b.to_bits())
|
||||
}
|
||||
|
||||
pub fn sort_siblings(world: &World, entities: &mut [Entity], sort_mode: HierarchySort) {
|
||||
match sort_mode {
|
||||
HierarchySort::Manual => {
|
||||
entities.sort_by(|a, b| {
|
||||
sibling_index(world, *a)
|
||||
.cmp(&sibling_index(world, *b))
|
||||
.then_with(|| entity_tie_break(*a, *b))
|
||||
});
|
||||
}
|
||||
HierarchySort::Name => {
|
||||
entities.sort_by(|a, b| {
|
||||
entity_name(world, *a)
|
||||
.cmp(&entity_name(world, *b))
|
||||
.then_with(|| sibling_index(world, *a).cmp(&sibling_index(world, *b)))
|
||||
.then_with(|| entity_tie_break(*a, *b))
|
||||
});
|
||||
}
|
||||
HierarchySort::Type => {
|
||||
entities.sort_by(|a, b| {
|
||||
actor_kind_sort_key(world, *a)
|
||||
.cmp(&actor_kind_sort_key(world, *b))
|
||||
.then_with(|| entity_name(world, *a).cmp(&entity_name(world, *b)))
|
||||
.then_with(|| sibling_index(world, *a).cmp(&sibling_index(world, *b)))
|
||||
.then_with(|| entity_tie_break(*a, *b))
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn actor_kind_sort_key(world: &World, entity: Entity) -> u8 {
|
||||
world
|
||||
.get::<ActorKind>(entity)
|
||||
.copied()
|
||||
.map(|kind| match kind {
|
||||
ActorKind::Empty => 0,
|
||||
ActorKind::StaticMesh | ActorKind::ImportedModel => 1,
|
||||
ActorKind::Light => 2,
|
||||
ActorKind::PrefabAnchor => 3,
|
||||
ActorKind::PlayerSpawn => 4,
|
||||
ActorKind::WeaponSpawn => 5,
|
||||
ActorKind::TriggerVolume => 6,
|
||||
ActorKind::PostProcessVolume => 6,
|
||||
ActorKind::TeamSpawn => 7,
|
||||
ActorKind::Objective => 8,
|
||||
})
|
||||
.unwrap_or(9)
|
||||
}
|
||||
|
||||
pub fn entity_hierarchy_path(world: &World, entity: Entity) -> String {
|
||||
let mut parts = vec![entity_name(world, entity)];
|
||||
let mut current = world
|
||||
.get::<ChildOf>(entity)
|
||||
.map(|child_of| child_of.parent());
|
||||
while let Some(parent) = current {
|
||||
if !is_level_object(world, parent) {
|
||||
break;
|
||||
}
|
||||
parts.push(entity_name(world, parent));
|
||||
current = world
|
||||
.get::<ChildOf>(parent)
|
||||
.map(|child_of| child_of.parent());
|
||||
}
|
||||
parts.reverse();
|
||||
parts.join("/")
|
||||
}
|
||||
|
||||
pub fn next_sibling_index(world: &mut World, parent: Option<Entity>) -> i32 {
|
||||
let siblings = match parent {
|
||||
Some(parent) => authored_children(world, parent),
|
||||
None => level_object_roots(world),
|
||||
};
|
||||
siblings
|
||||
.iter()
|
||||
.map(|entity| sibling_index(world, *entity))
|
||||
.max()
|
||||
.map(|max| max + 1)
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
pub fn renumber_siblings(world: &mut World, parent: Option<Entity>, ordered: &[Entity]) {
|
||||
for (index, entity) in ordered.iter().enumerate() {
|
||||
if let Ok(mut entity_mut) = world.get_entity_mut(*entity) {
|
||||
entity_mut.insert(HierarchySiblingIndex(index as i32));
|
||||
}
|
||||
}
|
||||
let _ = parent;
|
||||
}
|
||||
|
||||
pub fn capture_sibling_state(world: &World, entity: Entity) -> SiblingChange {
|
||||
SiblingChange {
|
||||
entity,
|
||||
old_parent: world
|
||||
.get::<ChildOf>(entity)
|
||||
.map(|child_of| child_of.parent()),
|
||||
new_parent: world
|
||||
.get::<ChildOf>(entity)
|
||||
.map(|child_of| child_of.parent()),
|
||||
old_index: sibling_index(world, entity),
|
||||
new_index: sibling_index(world, entity),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn apply_sibling_change(world: &mut World, change: &SiblingChange) {
|
||||
if let Ok(mut entity_mut) = world.get_entity_mut(change.entity) {
|
||||
if let Some(parent) = change.old_parent {
|
||||
entity_mut.insert(ChildOf(parent));
|
||||
} else {
|
||||
entity_mut.remove::<ChildOf>();
|
||||
}
|
||||
entity_mut.insert(HierarchySiblingIndex(change.old_index));
|
||||
}
|
||||
}
|
||||
|
||||
pub fn apply_sibling_change_new(world: &mut World, change: &SiblingChange) {
|
||||
if let Ok(mut entity_mut) = world.get_entity_mut(change.entity) {
|
||||
if let Some(parent) = change.new_parent {
|
||||
entity_mut.insert(ChildOf(parent));
|
||||
} else {
|
||||
entity_mut.remove::<ChildOf>();
|
||||
}
|
||||
entity_mut.insert(HierarchySiblingIndex(change.new_index));
|
||||
}
|
||||
}
|
||||
|
||||
pub fn reorder_entities_under_parent(
|
||||
world: &mut World,
|
||||
moving: &[Entity],
|
||||
new_parent: Option<Entity>,
|
||||
insert_index: i32,
|
||||
) -> Vec<SiblingChange> {
|
||||
let mut changes = Vec::new();
|
||||
let old_parents: std::collections::HashSet<Option<Entity>> = moving
|
||||
.iter()
|
||||
.map(|entity| {
|
||||
world
|
||||
.get::<ChildOf>(*entity)
|
||||
.map(|child_of| child_of.parent())
|
||||
})
|
||||
.collect();
|
||||
|
||||
changes.extend(renumber_inserted_siblings(
|
||||
world,
|
||||
moving,
|
||||
new_parent,
|
||||
insert_index,
|
||||
));
|
||||
|
||||
for old_parent in old_parents {
|
||||
if old_parent == new_parent {
|
||||
continue;
|
||||
}
|
||||
changes.extend(renumber_existing_siblings(world, old_parent, moving));
|
||||
}
|
||||
|
||||
changes
|
||||
}
|
||||
|
||||
fn renumber_inserted_siblings(
|
||||
world: &mut World,
|
||||
moving: &[Entity],
|
||||
new_parent: Option<Entity>,
|
||||
insert_index: i32,
|
||||
) -> Vec<SiblingChange> {
|
||||
let mut siblings = match new_parent {
|
||||
Some(parent) => authored_children(world, parent),
|
||||
None => level_object_roots(world),
|
||||
};
|
||||
siblings.retain(|entity| !moving.contains(entity));
|
||||
let insert = insert_index.clamp(0, siblings.len() as i32) as usize;
|
||||
for (offset, entity) in moving.iter().enumerate() {
|
||||
siblings.insert(insert + offset, *entity);
|
||||
}
|
||||
apply_sibling_order(world, new_parent, &siblings)
|
||||
}
|
||||
|
||||
fn renumber_existing_siblings(
|
||||
world: &mut World,
|
||||
parent: Option<Entity>,
|
||||
exclude: &[Entity],
|
||||
) -> Vec<SiblingChange> {
|
||||
let mut siblings = match parent {
|
||||
Some(parent) => authored_children(world, parent),
|
||||
None => level_object_roots(world),
|
||||
};
|
||||
siblings.retain(|entity| !exclude.contains(entity));
|
||||
sort_siblings(world, &mut siblings, HierarchySort::Manual);
|
||||
apply_sibling_order(world, parent, &siblings)
|
||||
}
|
||||
|
||||
fn apply_sibling_order(
|
||||
world: &mut World,
|
||||
parent: Option<Entity>,
|
||||
siblings: &[Entity],
|
||||
) -> Vec<SiblingChange> {
|
||||
let mut changes = Vec::new();
|
||||
for (index, entity) in siblings.iter().enumerate() {
|
||||
let old_parent = world
|
||||
.get::<ChildOf>(*entity)
|
||||
.map(|child_of| child_of.parent());
|
||||
let old_index = sibling_index(world, *entity);
|
||||
let new_index = index as i32;
|
||||
if old_parent != parent || old_index != new_index {
|
||||
changes.push(SiblingChange {
|
||||
entity: *entity,
|
||||
old_parent,
|
||||
new_parent: parent,
|
||||
old_index,
|
||||
new_index,
|
||||
});
|
||||
}
|
||||
if let Ok(mut entity_mut) = world.get_entity_mut(*entity) {
|
||||
if let Some(parent) = parent {
|
||||
entity_mut.insert(ChildOf(parent));
|
||||
} else {
|
||||
entity_mut.remove::<ChildOf>();
|
||||
}
|
||||
entity_mut.insert(HierarchySiblingIndex(new_index));
|
||||
}
|
||||
}
|
||||
changes
|
||||
}
|
||||
|
||||
pub fn backfill_missing_editor_visibility(world: &mut World) {
|
||||
let mut query =
|
||||
world.query_filtered::<Entity, (With<LevelObject>, Without<EditorVisibility>)>();
|
||||
let entities: Vec<Entity> = query.iter(world).collect();
|
||||
for entity in entities {
|
||||
if let Ok(mut entity_mut) = world.get_entity_mut(entity) {
|
||||
entity_mut.insert(EditorVisibility::default());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn backfill_missing_sibling_indices(world: &mut World) {
|
||||
let mut roots = level_object_roots(world);
|
||||
if roots
|
||||
.iter()
|
||||
.any(|entity| world.get::<HierarchySiblingIndex>(*entity).is_none())
|
||||
{
|
||||
sort_siblings(world, &mut roots, HierarchySort::Manual);
|
||||
renumber_siblings(world, None, &roots);
|
||||
}
|
||||
for root in roots {
|
||||
backfill_children(world, root);
|
||||
}
|
||||
}
|
||||
|
||||
fn backfill_children(world: &mut World, parent: Entity) {
|
||||
let mut children = authored_children(world, parent);
|
||||
if children
|
||||
.iter()
|
||||
.any(|entity| world.get::<HierarchySiblingIndex>(*entity).is_none())
|
||||
{
|
||||
sort_siblings(world, &mut children, HierarchySort::Manual);
|
||||
renumber_siblings(world, Some(parent), &children);
|
||||
}
|
||||
for child in children {
|
||||
backfill_children(world, child);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn actor_kind_icon(kind: ActorKind) -> &'static str {
|
||||
use egui_phosphor_icons::icons;
|
||||
match kind {
|
||||
ActorKind::Empty => icons::FOLDER.as_str(),
|
||||
ActorKind::StaticMesh => icons::CUBE.as_str(),
|
||||
ActorKind::ImportedModel => icons::CUBE_TRANSPARENT.as_str(),
|
||||
ActorKind::Light => icons::LIGHTBULB.as_str(),
|
||||
ActorKind::PrefabAnchor => icons::PACKAGE.as_str(),
|
||||
ActorKind::PlayerSpawn => icons::USER_CIRCLE.as_str(),
|
||||
ActorKind::WeaponSpawn => icons::CROSSHAIR.as_str(),
|
||||
ActorKind::TriggerVolume => icons::BROADCAST.as_str(),
|
||||
ActorKind::PostProcessVolume => icons::CAMERA.as_str(),
|
||||
ActorKind::TeamSpawn => icons::FLAG.as_str(),
|
||||
ActorKind::Objective => icons::TARGET.as_str(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn hierarchy_label_for_entity(
|
||||
world: &World,
|
||||
entity: Entity,
|
||||
kind: HierarchyNodeKind,
|
||||
) -> String {
|
||||
use egui_phosphor_icons::icons;
|
||||
let icon = world
|
||||
.get::<ActorKind>(entity)
|
||||
.copied()
|
||||
.map(actor_kind_icon)
|
||||
.unwrap_or_else(|| match kind {
|
||||
HierarchyNodeKind::Authored => icons::CUBE.as_str(),
|
||||
HierarchyNodeKind::Generated => icons::STACK.as_str(),
|
||||
HierarchyNodeKind::Runtime => icons::CPU.as_str(),
|
||||
});
|
||||
let mut label = format!("{} {}", icon, entity_name(world, entity));
|
||||
if let Some(light) = world.get::<LightDesc>(entity) {
|
||||
if matches!(light.kind, AuthoringLightKind::Directional) {
|
||||
label.push_str(" ☀");
|
||||
}
|
||||
}
|
||||
match kind {
|
||||
HierarchyNodeKind::Authored => {}
|
||||
HierarchyNodeKind::Generated => label.push_str(" (generated)"),
|
||||
HierarchyNodeKind::Runtime => label.push_str(" (runtime)"),
|
||||
}
|
||||
label
|
||||
}
|
||||
|
||||
pub fn entity_matches_filter(world: &World, entity: Entity, filter_lower: &str) -> bool {
|
||||
if filter_lower.is_empty() {
|
||||
return true;
|
||||
}
|
||||
if entity_name(world, entity)
|
||||
.to_lowercase()
|
||||
.contains(filter_lower)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
if let Some(kind) = world.get::<ActorKind>(entity) {
|
||||
if format!("{kind:?}").to_lowercase().contains(filter_lower) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
let tags = [
|
||||
world.get::<LightDesc>(entity).is_some().then_some("light"),
|
||||
world
|
||||
.get::<PlayerSpawn>(entity)
|
||||
.is_some()
|
||||
.then_some("spawn"),
|
||||
world.get::<ModelRef>(entity).is_some().then_some("model"),
|
||||
world
|
||||
.get::<PhysicsBody>(entity)
|
||||
.is_some()
|
||||
.then_some("physics"),
|
||||
world
|
||||
.get::<shared::PostProcessVolumeDesc>(entity)
|
||||
.is_some()
|
||||
.then_some("postprocess volume"),
|
||||
];
|
||||
tags.into_iter()
|
||||
.flatten()
|
||||
.any(|tag| tag.contains(filter_lower))
|
||||
}
|
||||
|
||||
pub fn editor_visibility(world: &World, entity: Entity) -> EditorVisibility {
|
||||
world
|
||||
.get::<EditorVisibility>(entity)
|
||||
.copied()
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
pub fn is_entity_locked(locked: &std::collections::HashSet<Entity>, entity: Entity) -> bool {
|
||||
locked.contains(&entity)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn sort_by_name_is_stable_for_duplicate_names() {
|
||||
let mut world = World::new();
|
||||
let a = world.spawn((LevelObject, Name::new("Pillar"))).id();
|
||||
let b = world.spawn((LevelObject, Name::new("Pillar"))).id();
|
||||
let mut entities = vec![a, b];
|
||||
|
||||
sort_siblings(&world, &mut entities, HierarchySort::Name);
|
||||
let first = entities.clone();
|
||||
|
||||
sort_siblings(&world, &mut entities, HierarchySort::Name);
|
||||
assert_eq!(entities, first, "duplicate-name sort must be deterministic");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
//! Hierarchy panel UI state and user-preference persistence.
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use bevy::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::project_io::{write_user_preferences, UserPreferences};
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
|
||||
pub enum HierarchySort {
|
||||
#[default]
|
||||
Manual,
|
||||
Name,
|
||||
Type,
|
||||
}
|
||||
|
||||
#[derive(Resource, Debug)]
|
||||
pub struct HierarchyPanelState {
|
||||
pub expanded: HashSet<Entity>,
|
||||
pub filter: String,
|
||||
pub show_generated: bool,
|
||||
pub show_runtime: bool,
|
||||
pub sort_mode: HierarchySort,
|
||||
/// Editor-session lock: prevents selection and gizmo manipulation.
|
||||
pub locked: HashSet<Entity>,
|
||||
/// Active hierarchy drag (release payload for egui 0.33+).
|
||||
pub active_drag: Option<Vec<Entity>>,
|
||||
save_timer: f32,
|
||||
dirty: bool,
|
||||
}
|
||||
|
||||
impl Default for HierarchyPanelState {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
expanded: HashSet::new(),
|
||||
filter: String::new(),
|
||||
show_generated: true,
|
||||
show_runtime: false,
|
||||
sort_mode: HierarchySort::default(),
|
||||
locked: HashSet::new(),
|
||||
active_drag: None,
|
||||
save_timer: 0.0,
|
||||
dirty: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl HierarchyPanelState {
|
||||
pub fn from_prefs(prefs: &UserPreferences) -> Self {
|
||||
let mut state = Self::default();
|
||||
state.filter = prefs.hierarchy_filter.clone();
|
||||
state.show_generated = prefs.hierarchy_show_generated;
|
||||
state.show_runtime = prefs.hierarchy_show_runtime;
|
||||
state.sort_mode = prefs.hierarchy_sort_mode;
|
||||
state
|
||||
}
|
||||
|
||||
pub fn mark_dirty(&mut self) {
|
||||
self.dirty = true;
|
||||
self.save_timer = 1.0;
|
||||
}
|
||||
|
||||
pub fn toggle_expanded(&mut self, entity: Entity, path: &str, prefs: &mut UserPreferences) {
|
||||
if self.expanded.contains(&entity) {
|
||||
self.expanded.remove(&entity);
|
||||
prefs.hierarchy_expanded_paths.retain(|entry| entry != path);
|
||||
} else {
|
||||
self.expanded.insert(entity);
|
||||
if !prefs
|
||||
.hierarchy_expanded_paths
|
||||
.iter()
|
||||
.any(|entry| entry == path)
|
||||
{
|
||||
prefs.hierarchy_expanded_paths.push(path.to_string());
|
||||
}
|
||||
}
|
||||
self.mark_dirty();
|
||||
}
|
||||
|
||||
pub fn sync_expanded_from_paths(&mut self, world: &mut World, paths: &[String]) {
|
||||
self.expanded = expanded_entities_for_paths(world, paths);
|
||||
}
|
||||
|
||||
fn flush_prefs(&mut self, prefs: &mut UserPreferences) {
|
||||
prefs.hierarchy_filter = self.filter.clone();
|
||||
prefs.hierarchy_show_generated = self.show_generated;
|
||||
prefs.hierarchy_show_runtime = self.show_runtime;
|
||||
prefs.hierarchy_sort_mode = self.sort_mode;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn expanded_entities_for_paths(world: &mut World, paths: &[String]) -> HashSet<Entity> {
|
||||
use super::hierarchy_ops::entity_hierarchy_path;
|
||||
|
||||
let mut expanded = HashSet::new();
|
||||
if paths.is_empty() {
|
||||
return expanded;
|
||||
}
|
||||
let mut query = world.query_filtered::<Entity, With<shared::LevelObject>>();
|
||||
for entity in query.iter(world) {
|
||||
let path = entity_hierarchy_path(world, entity);
|
||||
if paths.iter().any(|entry| entry == &path) {
|
||||
expanded.insert(entity);
|
||||
}
|
||||
}
|
||||
expanded
|
||||
}
|
||||
|
||||
pub fn tick_hierarchy_prefs_save(
|
||||
mut state: ResMut<HierarchyPanelState>,
|
||||
mut prefs: ResMut<UserPreferences>,
|
||||
time: Res<Time>,
|
||||
) {
|
||||
if !state.dirty {
|
||||
return;
|
||||
}
|
||||
state.save_timer -= time.delta_secs();
|
||||
if state.save_timer > 0.0 {
|
||||
return;
|
||||
}
|
||||
state.flush_prefs(&mut prefs);
|
||||
if let Err(err) = write_user_preferences(&prefs) {
|
||||
warn!("Failed to save hierarchy preferences: {err}");
|
||||
} else {
|
||||
state.dirty = false;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn apply_hierarchy_prefs(world: &mut World, prefs: &UserPreferences) {
|
||||
if !world.contains_resource::<HierarchyPanelState>() {
|
||||
return;
|
||||
}
|
||||
let paths = prefs.hierarchy_expanded_paths.clone();
|
||||
let expanded = expanded_entities_for_paths(world, &paths);
|
||||
let mut state = world.resource_mut::<HierarchyPanelState>();
|
||||
state.filter = prefs.hierarchy_filter.clone();
|
||||
state.show_generated = prefs.hierarchy_show_generated;
|
||||
state.show_runtime = prefs.hierarchy_show_runtime;
|
||||
state.sort_mode = prefs.hierarchy_sort_mode;
|
||||
state.expanded = expanded;
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,145 @@
|
||||
//! Dock layout persistence in user preferences.
|
||||
|
||||
use bevy::prelude::*;
|
||||
use egui_dock::{DockState, NodeIndex};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::project_io::{write_user_preferences, UserPreferences};
|
||||
|
||||
use super::dock_tabs::{normalize_unified_viewport_tabs, PanelNodes};
|
||||
use super::EditorTab;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct DockLayoutSnapshot {
|
||||
pub dock_state: DockState<EditorTab>,
|
||||
pub main_view_node: usize,
|
||||
#[serde(default)]
|
||||
pub panel_nodes: Option<PanelNodes>,
|
||||
}
|
||||
|
||||
#[derive(Resource, Default)]
|
||||
pub struct LayoutSaveTimer {
|
||||
pub seconds_until_save: f32,
|
||||
pub last_serialized: Option<String>,
|
||||
}
|
||||
|
||||
const SAVE_DEBOUNCE_SECS: f32 = 1.0;
|
||||
|
||||
pub fn default_dock_layout() -> DockLayoutSnapshot {
|
||||
let mut dock_state = DockState::new(vec![EditorTab::Viewport]);
|
||||
let tree = dock_state.main_surface_mut();
|
||||
let [main_view_node, inspector_node] =
|
||||
tree.split_right(NodeIndex::root(), 0.76, vec![EditorTab::Inspector]);
|
||||
let [main_view_node, hierarchy_node] =
|
||||
tree.split_left(main_view_node, 0.2, vec![EditorTab::Hierarchy]);
|
||||
let [main_view_node, bottom_node] =
|
||||
tree.split_below(main_view_node, 0.88, vec![EditorTab::AssetBrowser]);
|
||||
|
||||
let panel_nodes = PanelNodes {
|
||||
main_view: main_view_node.0,
|
||||
hierarchy: hierarchy_node.0,
|
||||
inspector: inspector_node.0,
|
||||
bottom: bottom_node.0,
|
||||
};
|
||||
|
||||
DockLayoutSnapshot {
|
||||
dock_state,
|
||||
main_view_node: main_view_node.0,
|
||||
panel_nodes: Some(panel_nodes),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn load_dock_layout(prefs: &UserPreferences) -> DockLayoutSnapshot {
|
||||
let Some(text) = prefs.dock_layout.as_ref() else {
|
||||
return default_dock_layout();
|
||||
};
|
||||
let mut snapshot: DockLayoutSnapshot =
|
||||
ron::from_str(text).unwrap_or_else(|_| default_dock_layout());
|
||||
normalize_unified_viewport_tabs(&mut snapshot.dock_state);
|
||||
if snapshot.panel_nodes.is_none() {
|
||||
let fallback = PanelNodes {
|
||||
main_view: snapshot.main_view_node,
|
||||
hierarchy: snapshot.main_view_node,
|
||||
inspector: snapshot.main_view_node,
|
||||
bottom: snapshot.main_view_node,
|
||||
};
|
||||
snapshot.panel_nodes = Some(PanelNodes::discover(&snapshot.dock_state, fallback));
|
||||
}
|
||||
snapshot
|
||||
}
|
||||
|
||||
pub fn serialize_dock_layout(
|
||||
dock_state: &DockState<EditorTab>,
|
||||
main_view_node: NodeIndex,
|
||||
panel_nodes: PanelNodes,
|
||||
) -> String {
|
||||
let snapshot = DockLayoutSnapshot {
|
||||
dock_state: dock_state.clone(),
|
||||
main_view_node: main_view_node.0,
|
||||
panel_nodes: Some(panel_nodes),
|
||||
};
|
||||
ron::ser::to_string(&snapshot).unwrap_or_default()
|
||||
}
|
||||
|
||||
pub fn mark_layout_dirty_if_changed(
|
||||
world: &mut World,
|
||||
dock_state: &DockState<EditorTab>,
|
||||
main_view_node: NodeIndex,
|
||||
panel_nodes: PanelNodes,
|
||||
) {
|
||||
let serialized = serialize_dock_layout(dock_state, main_view_node, panel_nodes);
|
||||
let mut timer = world.resource_mut::<LayoutSaveTimer>();
|
||||
if timer.last_serialized.as_ref() == Some(&serialized) {
|
||||
return;
|
||||
}
|
||||
timer.last_serialized = Some(serialized);
|
||||
timer.seconds_until_save = SAVE_DEBOUNCE_SECS;
|
||||
world
|
||||
.resource_mut::<crate::project_io::ProjectWorkspace>()
|
||||
.layout_dirty = true;
|
||||
}
|
||||
|
||||
pub fn tick_layout_save(world: &mut World, dt: f32) {
|
||||
let mut timer = world.resource_mut::<LayoutSaveTimer>();
|
||||
if timer.seconds_until_save <= 0.0 {
|
||||
return;
|
||||
}
|
||||
timer.seconds_until_save -= dt;
|
||||
if timer.seconds_until_save > 0.0 {
|
||||
return;
|
||||
}
|
||||
|
||||
let Some(serialized) = timer.last_serialized.clone() else {
|
||||
return;
|
||||
};
|
||||
|
||||
let mut prefs = world.resource_mut::<UserPreferences>();
|
||||
prefs.dock_layout = Some(serialized);
|
||||
if let Err(err) = write_user_preferences(&prefs) {
|
||||
warn!("Failed to save editor layout: {err}");
|
||||
} else {
|
||||
world
|
||||
.resource_mut::<crate::project_io::ProjectWorkspace>()
|
||||
.layout_dirty = false;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn reset_and_save_layout(world: &mut World) -> DockLayoutSnapshot {
|
||||
let layout = default_dock_layout();
|
||||
let serialized = ron::ser::to_string(&layout).unwrap_or_default();
|
||||
|
||||
{
|
||||
let mut prefs = world.resource_mut::<UserPreferences>();
|
||||
prefs.dock_layout = Some(serialized.clone());
|
||||
let _ = write_user_preferences(&prefs);
|
||||
}
|
||||
|
||||
let mut timer = world.resource_mut::<LayoutSaveTimer>();
|
||||
timer.last_serialized = Some(serialized);
|
||||
timer.seconds_until_save = 0.0;
|
||||
world
|
||||
.resource_mut::<crate::project_io::ProjectWorkspace>()
|
||||
.layout_dirty = false;
|
||||
|
||||
layout
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
//! Top menu bar.
|
||||
|
||||
use bevy::prelude::*;
|
||||
use bevy_egui::egui;
|
||||
use bevy_inspector_egui::bevy_inspector::hierarchy::SelectedEntities;
|
||||
use egui_dock::DockState;
|
||||
|
||||
use crate::history::{apply_command_redo, apply_command_undo, EditorHistory};
|
||||
use crate::scene_io::{SceneIo, SceneIoRequest};
|
||||
use crate::settings_ui::{open_project_settings_panel, ProjectSettingsPanel};
|
||||
use crate::state::{EditorMode, PlayPaused};
|
||||
use crate::workspace::{request_new_project, request_open_project};
|
||||
|
||||
use super::diagnostics::DiagnosticsPanel;
|
||||
use super::dock_tabs::{open_and_focus_tab, tab_is_open, tab_label, PanelNodes, PANEL_TABS};
|
||||
use super::helpers::{
|
||||
delete_selection, duplicate_selection, toggle_play_mode, toggle_play_paused, toggle_possession,
|
||||
};
|
||||
use super::layout::reset_and_save_layout;
|
||||
use super::widgets::menu_item;
|
||||
use super::EditorTab;
|
||||
|
||||
pub fn top_menu_bar(
|
||||
world: &mut World,
|
||||
ctx: &egui::Context,
|
||||
selected: &SelectedEntities,
|
||||
dock_state: &mut DockState<EditorTab>,
|
||||
panel_nodes: &mut PanelNodes,
|
||||
) {
|
||||
egui::TopBottomPanel::top("editor_menu_bar").show(ctx, |ui| {
|
||||
egui::MenuBar::new().ui(ui, |ui| {
|
||||
ui.menu_button("File", |ui| {
|
||||
ui.menu_button("Project", |ui| {
|
||||
if menu_item(ui, "New Project", None, true).clicked() {
|
||||
request_new_project(world);
|
||||
ui.close();
|
||||
}
|
||||
if menu_item(ui, "Open Project...", None, true).clicked() {
|
||||
request_open_project(world);
|
||||
ui.close();
|
||||
}
|
||||
});
|
||||
ui.separator();
|
||||
if menu_item(ui, "New Scene", None, true).clicked() {
|
||||
world.resource_mut::<SceneIo>().request = Some(SceneIoRequest::New);
|
||||
ui.close();
|
||||
}
|
||||
if menu_item(ui, "Open Scene...", None, true).clicked() {
|
||||
world.resource_mut::<SceneIo>().request = Some(SceneIoRequest::Open);
|
||||
ui.close();
|
||||
}
|
||||
if menu_item(ui, "Save", Some("Ctrl+S"), true).clicked() {
|
||||
world.resource_mut::<SceneIo>().request = Some(SceneIoRequest::Save);
|
||||
ui.close();
|
||||
}
|
||||
if menu_item(ui, "Save Scene As...", None, true).clicked() {
|
||||
world.resource_mut::<SceneIo>().request = Some(SceneIoRequest::SaveAs);
|
||||
ui.close();
|
||||
}
|
||||
ui.separator();
|
||||
if menu_item(ui, "Import Assets...", None, true).clicked() {
|
||||
world.resource_mut::<SceneIo>().request = Some(SceneIoRequest::ImportAssets);
|
||||
ui.close();
|
||||
}
|
||||
if menu_item(ui, "Export Selection...", None, true).clicked() {
|
||||
world.resource_mut::<SceneIo>().request = Some(SceneIoRequest::ExportSelection);
|
||||
ui.close();
|
||||
}
|
||||
if menu_item(ui, "Save Selection As Prefab...", None, true).clicked() {
|
||||
world.resource_mut::<SceneIo>().request =
|
||||
Some(SceneIoRequest::SaveSelectionAsPrefab);
|
||||
ui.close();
|
||||
}
|
||||
let recent: Vec<(usize, String)> = world
|
||||
.resource::<SceneIo>()
|
||||
.recent_paths
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, path)| (index, path.display().to_string()))
|
||||
.collect();
|
||||
if !recent.is_empty() {
|
||||
ui.separator();
|
||||
ui.menu_button("Recent Scenes", |ui| {
|
||||
for (index, label) in recent {
|
||||
if menu_item(ui, &label, None, true).clicked() {
|
||||
world.resource_mut::<SceneIo>().request =
|
||||
Some(SceneIoRequest::OpenRecent(index));
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
ui.menu_button("Edit", |ui| {
|
||||
if menu_item(ui, "Project Settings...", None, true).clicked() {
|
||||
open_project_settings_panel(&mut world.resource_mut::<ProjectSettingsPanel>());
|
||||
ui.close();
|
||||
}
|
||||
ui.separator();
|
||||
let can_undo = world.resource::<EditorHistory>().can_undo();
|
||||
let can_redo = world.resource::<EditorHistory>().can_redo();
|
||||
if menu_item(ui, "Undo", Some("Ctrl+Z"), can_undo).clicked() {
|
||||
apply_command_undo(world);
|
||||
ui.close();
|
||||
}
|
||||
if menu_item(ui, "Redo", Some("Ctrl+Y"), can_redo).clicked() {
|
||||
apply_command_redo(world);
|
||||
ui.close();
|
||||
}
|
||||
ui.separator();
|
||||
let has_selection = !selected.as_slice().is_empty();
|
||||
if menu_item(ui, "Duplicate", Some("Ctrl+D"), has_selection).clicked() {
|
||||
duplicate_selection(world, selected);
|
||||
ui.close();
|
||||
}
|
||||
if menu_item(ui, "Delete", Some("Del"), has_selection).clicked() {
|
||||
delete_selection(world, selected);
|
||||
ui.close();
|
||||
}
|
||||
});
|
||||
|
||||
ui.menu_button("Scene", |ui| {
|
||||
if menu_item(ui, "Lighting → Use project sun", None, true).clicked() {
|
||||
super::helpers::use_project_sun(world);
|
||||
ui.close();
|
||||
}
|
||||
if menu_item(ui, "Lighting → Bake scene sun from project", None, true).clicked() {
|
||||
super::helpers::create_scene_sun_override_from_project_settings(world);
|
||||
ui.close();
|
||||
}
|
||||
if menu_item(ui, "Create → Post Process Volume", None, true).clicked() {
|
||||
crate::rendering_diagnostics::spawn_post_process_volume_at_camera(world);
|
||||
ui.close();
|
||||
}
|
||||
});
|
||||
|
||||
ui.menu_button("View", |ui| {
|
||||
if menu_item(ui, "Reset Layout", None, true).clicked() {
|
||||
let layout = reset_and_save_layout(world);
|
||||
*dock_state = layout.dock_state;
|
||||
if let Some(nodes) = layout.panel_nodes {
|
||||
*panel_nodes = nodes;
|
||||
}
|
||||
ui.close();
|
||||
}
|
||||
});
|
||||
|
||||
ui.menu_button("Window", |ui| {
|
||||
for tab in PANEL_TABS {
|
||||
let open = tab_is_open(dock_state, &tab);
|
||||
if ui.selectable_label(open, tab_label(&tab)).clicked() {
|
||||
open_and_focus_tab(dock_state, tab, panel_nodes);
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
ui.separator();
|
||||
let mut diagnostics = world.resource_mut::<DiagnosticsPanel>();
|
||||
if ui.checkbox(&mut diagnostics.open, "Diagnostics").clicked() {
|
||||
ui.close();
|
||||
}
|
||||
let mut rendering =
|
||||
world.resource_mut::<crate::rendering_diagnostics::RenderingDiagnosticsPanel>();
|
||||
if ui.checkbox(&mut rendering.open, "Rendering").clicked() {
|
||||
ui.close();
|
||||
}
|
||||
});
|
||||
|
||||
ui.menu_button("Play", |ui| {
|
||||
let playing = *world.resource::<State<EditorMode>>().get() == EditorMode::Playing;
|
||||
let paused = world.resource::<PlayPaused>().0;
|
||||
if menu_item(ui, "Toggle Play/Edit", Some("F5"), true).clicked() {
|
||||
toggle_play_mode(world);
|
||||
ui.close();
|
||||
}
|
||||
if menu_item(ui, "Pause / Resume", Some("F6"), playing).clicked() {
|
||||
toggle_play_paused(world);
|
||||
ui.close();
|
||||
}
|
||||
let possess_label = if playing {
|
||||
"Possess / Eject"
|
||||
} else {
|
||||
"Possess / Eject (while playing)"
|
||||
};
|
||||
if menu_item(ui, possess_label, Some("F8"), playing).clicked() {
|
||||
toggle_possession(world);
|
||||
ui.close();
|
||||
}
|
||||
if playing && paused {
|
||||
ui.label("Simulation paused");
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,347 @@
|
||||
mod actor_inspector;
|
||||
mod asset_browser;
|
||||
mod component_registry;
|
||||
mod diagnostics;
|
||||
mod dock_tabs;
|
||||
mod fonts;
|
||||
pub(crate) mod helpers;
|
||||
mod hierarchy;
|
||||
pub mod hierarchy_ops;
|
||||
pub mod hierarchy_state;
|
||||
pub(crate) mod inspector;
|
||||
mod layout;
|
||||
mod menu;
|
||||
mod play_controls;
|
||||
mod post_process_volume_ui;
|
||||
pub mod selection_ops;
|
||||
mod status_bar;
|
||||
pub(crate) mod theme;
|
||||
mod toolbar;
|
||||
mod viewport_chrome;
|
||||
mod widgets;
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use bevy::prelude::*;
|
||||
use bevy::window::{CursorGrabMode, CursorOptions, PrimaryWindow};
|
||||
use bevy_egui::{egui, EguiContext, EguiPrimaryContextPass, PrimaryEguiContext};
|
||||
use bevy_inspector_egui::bevy_inspector::hierarchy::SelectedEntities;
|
||||
use egui_dock::{DockArea, DockState};
|
||||
use egui_phosphor_icons::icons;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::project_io::UserPreferences;
|
||||
use crate::selection::SelectedEntity;
|
||||
use crate::state::EditorMode;
|
||||
|
||||
pub use diagnostics::DiagnosticsPanel;
|
||||
pub use layout::LayoutSaveTimer;
|
||||
pub use viewport_chrome::ViewportUiState;
|
||||
|
||||
use diagnostics::diagnostics_window;
|
||||
use dock_tabs::PanelNodes;
|
||||
use hierarchy_state::HierarchyPanelState;
|
||||
use layout::{load_dock_layout, mark_layout_dirty_if_changed, tick_layout_save};
|
||||
use menu::top_menu_bar;
|
||||
use status_bar::status_bar_ui;
|
||||
use theme::{apply_editor_theme, editor_dock_style};
|
||||
use toolbar::editor_toolbar_panel;
|
||||
use viewport_chrome::viewport_tab_ui;
|
||||
|
||||
use crate::settings_ui::{project_settings_window, ProjectSettingsPanel};
|
||||
|
||||
#[derive(Resource)]
|
||||
pub struct UiState {
|
||||
pub dock_state: DockState<EditorTab>,
|
||||
pub viewport_rect: egui::Rect,
|
||||
pub pointer_in_viewport: bool,
|
||||
/// Pointer position inside the viewport image (logical screen coords), for picking.
|
||||
pub viewport_pointer_pos: Option<egui::Pos2>,
|
||||
pub selected_entities: SelectedEntities,
|
||||
pub renaming_entity: Option<Entity>,
|
||||
pub rename_buffer: String,
|
||||
pub(crate) inspector_collapsed_components: HashSet<String>,
|
||||
pub(crate) panel_nodes: PanelNodes,
|
||||
last_mode_tab: Option<EditorMode>,
|
||||
}
|
||||
|
||||
impl UiState {
|
||||
pub fn default_layout() -> Self {
|
||||
Self::from_prefs(&UserPreferences::default())
|
||||
}
|
||||
|
||||
pub fn from_prefs(prefs: &UserPreferences) -> Self {
|
||||
let layout = load_dock_layout(prefs);
|
||||
let fallback_nodes = layout.panel_nodes.unwrap_or(PanelNodes {
|
||||
main_view: layout.main_view_node,
|
||||
hierarchy: layout.main_view_node,
|
||||
inspector: layout.main_view_node,
|
||||
bottom: layout.main_view_node,
|
||||
});
|
||||
let panel_nodes = PanelNodes::discover(&layout.dock_state, fallback_nodes);
|
||||
Self {
|
||||
dock_state: layout.dock_state,
|
||||
viewport_rect: egui::Rect::NOTHING,
|
||||
pointer_in_viewport: false,
|
||||
viewport_pointer_pos: None,
|
||||
selected_entities: SelectedEntities::default(),
|
||||
renaming_entity: None,
|
||||
rename_buffer: String::new(),
|
||||
inspector_collapsed_components: HashSet::new(),
|
||||
panel_nodes,
|
||||
last_mode_tab: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn ui(&mut self, world: &mut World, ctx: &mut egui::Context, dt: f32) {
|
||||
apply_editor_theme(ctx);
|
||||
|
||||
let mode = *world.resource::<State<EditorMode>>().get();
|
||||
if self.last_mode_tab != Some(mode) {
|
||||
self.last_mode_tab = Some(mode);
|
||||
if mode == EditorMode::Playing {
|
||||
dock_tabs::ensure_viewport_for_play(&mut self.dock_state, &self.panel_nodes);
|
||||
}
|
||||
}
|
||||
|
||||
top_menu_bar(
|
||||
world,
|
||||
ctx,
|
||||
&self.selected_entities,
|
||||
&mut self.dock_state,
|
||||
&mut self.panel_nodes,
|
||||
);
|
||||
|
||||
editor_toolbar_panel(world, ctx);
|
||||
|
||||
self.pointer_in_viewport = false;
|
||||
self.viewport_pointer_pos = None;
|
||||
|
||||
let playing = mode == EditorMode::Playing;
|
||||
let cursor_grabbed = world
|
||||
.query_filtered::<&CursorOptions, With<PrimaryWindow>>()
|
||||
.single(world)
|
||||
.is_ok_and(|cursor| cursor.grab_mode != CursorGrabMode::None);
|
||||
if playing && cursor_grabbed {
|
||||
ctx.input_mut(|input| {
|
||||
input.focused = false;
|
||||
});
|
||||
}
|
||||
|
||||
let mut viewer = TabViewer {
|
||||
world,
|
||||
viewport_rect: &mut self.viewport_rect,
|
||||
pointer_in_viewport: &mut self.pointer_in_viewport,
|
||||
viewport_pointer_pos: &mut self.viewport_pointer_pos,
|
||||
playing,
|
||||
cursor_grabbed,
|
||||
selected_entities: &mut self.selected_entities,
|
||||
renaming_entity: &mut self.renaming_entity,
|
||||
rename_buffer: &mut self.rename_buffer,
|
||||
};
|
||||
|
||||
DockArea::new(&mut self.dock_state)
|
||||
.style(editor_dock_style(ctx))
|
||||
.show(ctx, &mut viewer);
|
||||
|
||||
self.panel_nodes = PanelNodes::discover(&self.dock_state, self.panel_nodes);
|
||||
|
||||
mark_layout_dirty_if_changed(
|
||||
world,
|
||||
&self.dock_state,
|
||||
self.panel_nodes.main_view(),
|
||||
self.panel_nodes,
|
||||
);
|
||||
tick_layout_save(world, dt);
|
||||
|
||||
status_bar_ui(world, ctx, &self.selected_entities, mode);
|
||||
|
||||
let mut diagnostics_open = world.resource::<DiagnosticsPanel>().open;
|
||||
diagnostics_window(world, ctx, &mut diagnostics_open);
|
||||
world.resource_mut::<DiagnosticsPanel>().open = diagnostics_open;
|
||||
|
||||
let mut rendering_open = world
|
||||
.resource::<crate::rendering_diagnostics::RenderingDiagnosticsPanel>()
|
||||
.open;
|
||||
crate::rendering_diagnostics::rendering_diagnostics_window(world, ctx, &mut rendering_open);
|
||||
world
|
||||
.resource_mut::<crate::rendering_diagnostics::RenderingDiagnosticsPanel>()
|
||||
.open = rendering_open;
|
||||
|
||||
world.resource_scope(|world, mut panel: Mut<ProjectSettingsPanel>| {
|
||||
project_settings_window(world, ctx, &mut panel);
|
||||
});
|
||||
|
||||
if ctx.input(|input| input.key_pressed(egui::Key::F1)) {
|
||||
world.resource_mut::<ViewportUiState>().shortcuts_open = true;
|
||||
}
|
||||
|
||||
let selected = self.selected_entities.as_slice().first().copied();
|
||||
world.resource_mut::<SelectedEntity>().0 = selected;
|
||||
}
|
||||
}
|
||||
|
||||
fn tab_title(icon: egui_phosphor_icons::Icon, label: &str) -> egui::WidgetText {
|
||||
let mut job = egui::text::LayoutJob::default();
|
||||
job.append(
|
||||
icon.as_str(),
|
||||
0.0,
|
||||
egui::TextFormat {
|
||||
font_id: egui::FontId::new(13.0, egui::FontFamily::Name("phosphor-regular".into())),
|
||||
color: theme::TEXT,
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
job.append(
|
||||
&format!(" {label}"),
|
||||
0.0,
|
||||
egui::TextFormat {
|
||||
font_id: egui::FontId::new(13.0, egui::FontFamily::Proportional),
|
||||
color: theme::TEXT,
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
job.into()
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum EditorTab {
|
||||
Viewport,
|
||||
/// Legacy saved-layout tab. Loaded layouts are migrated to [`EditorTab::Viewport`].
|
||||
GameView,
|
||||
Hierarchy,
|
||||
Inspector,
|
||||
Toolbar,
|
||||
AssetBrowser,
|
||||
}
|
||||
|
||||
pub struct EditorUiPlugin;
|
||||
|
||||
impl Plugin for EditorUiPlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
app.insert_resource(UiState::default_layout())
|
||||
.add_plugins(fonts::EditorFontsPlugin)
|
||||
.init_resource::<DiagnosticsPanel>()
|
||||
.init_resource::<component_registry::EditorComponentRegistry>()
|
||||
.init_resource::<crate::rendering_diagnostics::RenderingDiagnosticsPanel>()
|
||||
.init_resource::<asset_browser::AssetBrowserUiState>()
|
||||
.init_resource::<inspector::InspectorClipboard>()
|
||||
.init_resource::<ViewportUiState>()
|
||||
.init_resource::<LayoutSaveTimer>()
|
||||
.add_systems(
|
||||
Startup,
|
||||
init_hierarchy_panel_from_prefs
|
||||
.after(crate::project_io::load_user_preferences_on_startup),
|
||||
)
|
||||
.add_systems(
|
||||
Startup,
|
||||
apply_ui_state_from_prefs
|
||||
.after(crate::project_io::load_user_preferences_on_startup),
|
||||
)
|
||||
.add_systems(EguiPrimaryContextPass, show_ui_system)
|
||||
.add_systems(Update, hierarchy_state::tick_hierarchy_prefs_save);
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_ui_state_from_prefs(mut ui_state: ResMut<UiState>, prefs: Res<UserPreferences>) {
|
||||
*ui_state = UiState::from_prefs(&prefs);
|
||||
}
|
||||
|
||||
fn init_hierarchy_panel_from_prefs(mut commands: Commands, prefs: Res<UserPreferences>) {
|
||||
commands.insert_resource(HierarchyPanelState::from_prefs(&prefs));
|
||||
}
|
||||
|
||||
pub(crate) fn show_ui_system(world: &mut World) {
|
||||
let Ok(egui_context) = world
|
||||
.query_filtered::<&mut EguiContext, With<PrimaryEguiContext>>()
|
||||
.single(world)
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let mut egui_context = egui_context.clone();
|
||||
let dt = world
|
||||
.get_resource::<Time>()
|
||||
.map(|time| time.delta_secs())
|
||||
.unwrap_or(0.0);
|
||||
|
||||
world.resource_scope::<UiState, _>(|world, mut ui_state| {
|
||||
ui_state.ui(world, egui_context.get_mut(), dt);
|
||||
});
|
||||
}
|
||||
|
||||
struct TabViewer<'a> {
|
||||
world: &'a mut World,
|
||||
viewport_rect: &'a mut egui::Rect,
|
||||
pointer_in_viewport: &'a mut bool,
|
||||
viewport_pointer_pos: &'a mut Option<egui::Pos2>,
|
||||
playing: bool,
|
||||
cursor_grabbed: bool,
|
||||
selected_entities: &'a mut SelectedEntities,
|
||||
renaming_entity: &'a mut Option<Entity>,
|
||||
rename_buffer: &'a mut String,
|
||||
}
|
||||
|
||||
impl egui_dock::TabViewer for TabViewer<'_> {
|
||||
type Tab = EditorTab;
|
||||
|
||||
fn ui(&mut self, ui: &mut egui::Ui, tab: &mut Self::Tab) {
|
||||
match tab {
|
||||
EditorTab::Viewport | EditorTab::GameView => {
|
||||
viewport_tab_ui(
|
||||
self.world,
|
||||
ui,
|
||||
self.viewport_rect,
|
||||
self.pointer_in_viewport,
|
||||
self.viewport_pointer_pos,
|
||||
self.selected_entities,
|
||||
self.playing,
|
||||
self.cursor_grabbed,
|
||||
);
|
||||
}
|
||||
EditorTab::Hierarchy => {
|
||||
hierarchy::hierarchy_panel_ui(
|
||||
self.world,
|
||||
ui,
|
||||
self.selected_entities,
|
||||
self.renaming_entity,
|
||||
self.rename_buffer,
|
||||
);
|
||||
}
|
||||
EditorTab::Inspector => match self.selected_entities.as_slice() {
|
||||
&[entity] if self.world.get_entity(entity).is_ok() => {
|
||||
actor_inspector::draw_actor_inspector(self.world, ui, entity);
|
||||
}
|
||||
&[entity] => {
|
||||
ui.label(format!("Entity {entity:?} is no longer in the world."));
|
||||
}
|
||||
entities => {
|
||||
actor_inspector::draw_multi_actor_inspector(self.world, ui, entities);
|
||||
}
|
||||
},
|
||||
EditorTab::Toolbar => {
|
||||
ui.label("Toolbar moved below the menu bar (Play, spawn, save).");
|
||||
}
|
||||
EditorTab::AssetBrowser => {
|
||||
asset_browser::asset_browser_ui(self.world, ui, self.selected_entities);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn title(&mut self, tab: &mut Self::Tab) -> egui::WidgetText {
|
||||
let (icon, label) = match tab {
|
||||
EditorTab::Viewport | EditorTab::GameView => (icons::FILM_SLATE, "Viewport"),
|
||||
EditorTab::Hierarchy => (icons::LIST_BULLETS, "Hierarchy"),
|
||||
EditorTab::Inspector => (icons::SLIDERS, "Inspector"),
|
||||
EditorTab::Toolbar => (icons::WRENCH, "Toolbar"),
|
||||
EditorTab::AssetBrowser => (icons::FOLDER, "Asset Browser"),
|
||||
};
|
||||
tab_title(icon, label)
|
||||
}
|
||||
|
||||
fn clear_background(&self, tab: &Self::Tab) -> bool {
|
||||
match tab {
|
||||
EditorTab::Viewport | EditorTab::GameView => true,
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
//! Play mode toggles and possession controls.
|
||||
|
||||
use bevy::prelude::*;
|
||||
|
||||
use crate::play::state::{toggle_play_possession_world, EditorMode, PlayPaused};
|
||||
use crate::project_io::UserPreferences;
|
||||
use crate::scene_io::{save_active_or_prompt_world, SceneIo};
|
||||
|
||||
pub fn toggle_play_mode(world: &mut World) {
|
||||
let entering_play = *world.resource::<State<EditorMode>>().get() == EditorMode::Editing;
|
||||
if entering_play {
|
||||
let save_before = world.resource::<UserPreferences>().save_before_play;
|
||||
if save_before && world.resource::<SceneIo>().dirty {
|
||||
let status = save_active_or_prompt_world(world);
|
||||
if status.contains("failed") || status.contains("cancelled") {
|
||||
world.resource_mut::<SceneIo>().status = status;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
let next = if entering_play {
|
||||
EditorMode::Playing
|
||||
} else {
|
||||
EditorMode::Editing
|
||||
};
|
||||
world.resource_mut::<NextState<EditorMode>>().set(next);
|
||||
}
|
||||
|
||||
pub fn toggle_play_paused(world: &mut World) {
|
||||
if *world.resource::<State<EditorMode>>().get() != EditorMode::Playing {
|
||||
return;
|
||||
}
|
||||
let mut paused = world.resource_mut::<PlayPaused>();
|
||||
paused.0 = !paused.0;
|
||||
}
|
||||
|
||||
pub fn toggle_possession(world: &mut World) {
|
||||
toggle_play_possession_world(world);
|
||||
}
|
||||
@@ -0,0 +1,341 @@
|
||||
//! Dedicated post-process volume inspector with inherit/override UX.
|
||||
|
||||
use bevy::prelude::*;
|
||||
use bevy_egui::egui;
|
||||
use egui_phosphor_icons::icons;
|
||||
use settings::ProjectSettings;
|
||||
use shared::{ColorDesc, PostProcessVolumeDesc, PostProcessVolumeOverrides, RenderingProfileAsset};
|
||||
use walkdir::WalkDir;
|
||||
|
||||
use crate::history::set_post_process_volume_with_history;
|
||||
use crate::ui::inspector::{
|
||||
apply_component_card_response, component_card, component_card_context, ComponentCardOptions,
|
||||
};
|
||||
use crate::ui::inspector::{property_row, text_field_width};
|
||||
use crate::ui::theme::panel_heading;
|
||||
|
||||
pub fn post_process_volume_inspector_ui(world: &mut World, ui: &mut egui::Ui, entity: Entity) {
|
||||
let Some(mut volume) = world.get::<PostProcessVolumeDesc>(entity).cloned() else {
|
||||
return;
|
||||
};
|
||||
let project = world.resource::<ProjectSettings>().rendering.clone();
|
||||
let original = volume.clone();
|
||||
let mut changed = false;
|
||||
|
||||
let card = component_card_context(
|
||||
world,
|
||||
entity,
|
||||
ComponentCardOptions::removable(
|
||||
shared::COMPONENT_POST_PROCESS_VOLUME,
|
||||
"Post Process Volume",
|
||||
icons::APERTURE,
|
||||
),
|
||||
);
|
||||
let card_response = component_card(ui, &card, |ui| {
|
||||
property_row(ui, "Label (HUD)", |ui| {
|
||||
let mut label_text = volume.label.clone().unwrap_or_default();
|
||||
if ui
|
||||
.add_sized(
|
||||
[text_field_width(ui), 20.0],
|
||||
egui::TextEdit::singleline(&mut label_text),
|
||||
)
|
||||
.changed()
|
||||
{
|
||||
volume.label = if label_text.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(label_text)
|
||||
};
|
||||
changed = true;
|
||||
}
|
||||
});
|
||||
property_row(ui, "Priority", |ui| {
|
||||
ui.add(egui::Slider::new(&mut volume.priority, -10..=100));
|
||||
});
|
||||
property_row(ui, "Blend distance", |ui| {
|
||||
ui.add(egui::Slider::new(&mut volume.blend_distance, 0.0..=20.0));
|
||||
});
|
||||
property_row(ui, "Half X", |ui| {
|
||||
ui.add(egui::Slider::new(&mut volume.half_extents.x, 0.5..=50.0));
|
||||
});
|
||||
property_row(ui, "Half Y", |ui| {
|
||||
ui.add(egui::Slider::new(&mut volume.half_extents.y, 0.5..=50.0));
|
||||
});
|
||||
property_row(ui, "Half Z", |ui| {
|
||||
ui.add(egui::Slider::new(&mut volume.half_extents.z, 0.5..=50.0));
|
||||
});
|
||||
if volume.half_extents != original.half_extents
|
||||
|| volume.priority != original.priority
|
||||
|| volume.blend_distance != original.blend_distance
|
||||
|| volume.label != original.label
|
||||
{
|
||||
changed = true;
|
||||
}
|
||||
|
||||
ui.separator();
|
||||
ui.label(panel_heading("Overrides"));
|
||||
changed |= override_f32_ui(
|
||||
ui,
|
||||
"Exposure EV100",
|
||||
&mut volume.overrides.exposure_ev100,
|
||||
project.exposure_ev100,
|
||||
);
|
||||
changed |= override_bool_ui(ui, "HDR", &mut volume.overrides.hdr, project.hdr);
|
||||
changed |= override_bool_ui(
|
||||
ui,
|
||||
"Tonemapping ACES",
|
||||
&mut volume.overrides.tonemapping_aces,
|
||||
project.tonemapping_aces,
|
||||
);
|
||||
changed |= override_bool_ui(ui, "Bloom", &mut volume.overrides.bloom, project.bloom);
|
||||
changed |= override_bool_ui(ui, "TAA", &mut volume.overrides.taa, project.taa);
|
||||
changed |= override_bool_ui(ui, "SSAO", &mut volume.overrides.ssao, project.ssao);
|
||||
changed |= override_bool_ui(
|
||||
ui,
|
||||
"Atmosphere",
|
||||
&mut volume.overrides.atmosphere,
|
||||
project.atmosphere,
|
||||
);
|
||||
changed |= override_fog_ui(ui, &mut volume.overrides, &project);
|
||||
|
||||
ui.separator();
|
||||
ui.label(panel_heading("Fullscreen Effect"));
|
||||
let effects = scan_post_fx_assets();
|
||||
let current = volume.fullscreen_effect.clone().unwrap_or_default();
|
||||
property_row(ui, "Effect", |ui| {
|
||||
egui::ComboBox::from_id_salt("post_process_fullscreen_effect")
|
||||
.selected_text(if current.is_empty() {
|
||||
"None".to_string()
|
||||
} else {
|
||||
current.clone()
|
||||
})
|
||||
.show_ui(ui, |ui| {
|
||||
if ui
|
||||
.selectable_label(volume.fullscreen_effect.is_none(), "None")
|
||||
.clicked()
|
||||
{
|
||||
volume.fullscreen_effect = None;
|
||||
changed = true;
|
||||
}
|
||||
for path in &effects {
|
||||
if ui
|
||||
.selectable_label(
|
||||
volume.fullscreen_effect.as_deref() == Some(path.as_str()),
|
||||
path,
|
||||
)
|
||||
.clicked()
|
||||
{
|
||||
volume.fullscreen_effect = Some(path.clone());
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
ui.separator();
|
||||
ui.label(panel_heading("Preset"));
|
||||
let profiles = scan_rendering_profiles();
|
||||
property_row(ui, "Profile", |ui| {
|
||||
egui::ComboBox::from_id_salt("post_process_profile")
|
||||
.selected_text(volume.profile.clone().unwrap_or_else(|| "None".to_string()))
|
||||
.show_ui(ui, |ui| {
|
||||
if ui
|
||||
.selectable_label(volume.profile.is_none(), "None")
|
||||
.clicked()
|
||||
{
|
||||
volume.profile = None;
|
||||
changed = true;
|
||||
}
|
||||
for path in &profiles {
|
||||
if ui
|
||||
.selectable_label(
|
||||
volume.profile.as_deref() == Some(path.as_str()),
|
||||
path,
|
||||
)
|
||||
.clicked()
|
||||
{
|
||||
volume.profile = Some(path.clone());
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
if ui.button("Apply preset").clicked() {
|
||||
if let Some(path) = &volume.profile {
|
||||
if let Ok(preset) = RenderingProfileAsset::load_from_path(path) {
|
||||
volume.overrides = preset.overrides;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if ui.button("Revert to preset").clicked() {
|
||||
if let Some(path) = &volume.profile {
|
||||
if let Ok(preset) = RenderingProfileAsset::load_from_path(path) {
|
||||
volume.overrides = preset.overrides;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
apply_component_card_response(world, entity, card_response);
|
||||
|
||||
if changed {
|
||||
set_post_process_volume_with_history(world, entity, volume);
|
||||
}
|
||||
}
|
||||
|
||||
fn override_bool_ui(
|
||||
ui: &mut egui::Ui,
|
||||
label: &str,
|
||||
field: &mut Option<bool>,
|
||||
inherited: bool,
|
||||
) -> bool {
|
||||
let mut changed = false;
|
||||
property_row(ui, label, |ui| {
|
||||
let mut overriding = field.is_some();
|
||||
if ui.checkbox(&mut overriding, "Override").changed() {
|
||||
*field = if overriding { Some(inherited) } else { None };
|
||||
changed = true;
|
||||
}
|
||||
});
|
||||
if let Some(value) = field.as_mut() {
|
||||
property_row(ui, "Value", |ui| {
|
||||
if ui.checkbox(value, "Enabled").changed() {
|
||||
changed = true;
|
||||
}
|
||||
if ui.small_button("Reset to project").clicked() {
|
||||
*value = inherited;
|
||||
changed = true;
|
||||
}
|
||||
});
|
||||
} else {
|
||||
property_row(ui, "Inherited", |ui| {
|
||||
ui.label(if inherited { "on" } else { "off" });
|
||||
});
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
fn override_f32_ui(
|
||||
ui: &mut egui::Ui,
|
||||
label: &str,
|
||||
field: &mut Option<f32>,
|
||||
inherited: f32,
|
||||
) -> bool {
|
||||
let mut changed = false;
|
||||
property_row(ui, label, |ui| {
|
||||
let mut overriding = field.is_some();
|
||||
if ui.checkbox(&mut overriding, "Override").changed() {
|
||||
*field = if overriding { Some(inherited) } else { None };
|
||||
changed = true;
|
||||
}
|
||||
});
|
||||
if let Some(value) = field.as_mut() {
|
||||
property_row(ui, "Value", |ui| {
|
||||
if ui.add(egui::Slider::new(value, 0.0..=20.0)).changed() {
|
||||
changed = true;
|
||||
}
|
||||
if ui.small_button("Reset to project").clicked() {
|
||||
*value = inherited;
|
||||
changed = true;
|
||||
}
|
||||
});
|
||||
} else {
|
||||
property_row(ui, "Inherited", |ui| {
|
||||
ui.label(format!("{inherited:.2}"));
|
||||
});
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
fn override_fog_ui(
|
||||
ui: &mut egui::Ui,
|
||||
overrides: &mut PostProcessVolumeOverrides,
|
||||
project: &settings::RenderingSettings,
|
||||
) -> bool {
|
||||
let mut changed = false;
|
||||
property_row(ui, "Fog density", |ui| {
|
||||
let mut overriding = overrides.fog_density.is_some();
|
||||
if ui.checkbox(&mut overriding, "Override").changed() {
|
||||
overrides.fog_density = if overriding {
|
||||
Some(project.fog_density)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
changed = true;
|
||||
}
|
||||
});
|
||||
if let Some(density) = overrides.fog_density.as_mut() {
|
||||
property_row(ui, "Density", |ui| {
|
||||
if ui
|
||||
.add(egui::Slider::new(density, 0.0..=0.01).logarithmic(true))
|
||||
.changed()
|
||||
{
|
||||
changed = true;
|
||||
}
|
||||
});
|
||||
} else {
|
||||
property_row(ui, "Inherited", |ui| {
|
||||
ui.label(format!("{:.4}", project.fog_density));
|
||||
});
|
||||
}
|
||||
|
||||
property_row(ui, "Fog color", |ui| {
|
||||
let mut overriding = overrides.fog_color.is_some();
|
||||
if ui.checkbox(&mut overriding, "Override").changed() {
|
||||
overrides.fog_color = if overriding {
|
||||
Some(ColorDesc::srgb(
|
||||
project.fog_color[0],
|
||||
project.fog_color[1],
|
||||
project.fog_color[2],
|
||||
))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
changed = true;
|
||||
}
|
||||
});
|
||||
if let Some(color) = overrides.fog_color.as_mut() {
|
||||
property_row(ui, "Color", |ui| {
|
||||
let mut rgb = [color.r, color.g, color.b];
|
||||
if ui.color_edit_button_rgb(&mut rgb).changed() {
|
||||
color.r = rgb[0];
|
||||
color.g = rgb[1];
|
||||
color.b = rgb[2];
|
||||
changed = true;
|
||||
}
|
||||
});
|
||||
} else {
|
||||
property_row(ui, "Inherited", |ui| {
|
||||
ui.label(format!(
|
||||
"({:.2}, {:.2}, {:.2})",
|
||||
project.fog_color[0], project.fog_color[1], project.fog_color[2]
|
||||
));
|
||||
});
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
fn scan_post_fx_assets() -> Vec<String> {
|
||||
scan_ron_dir("assets/post_fx")
|
||||
}
|
||||
|
||||
fn scan_rendering_profiles() -> Vec<String> {
|
||||
scan_ron_dir("assets/rendering_profiles")
|
||||
}
|
||||
|
||||
fn scan_ron_dir(root: &str) -> Vec<String> {
|
||||
let mut paths = Vec::new();
|
||||
for entry in WalkDir::new(root).into_iter().filter_map(Result::ok) {
|
||||
if entry.file_type().is_file()
|
||||
&& entry.path().extension().and_then(|e| e.to_str()) == Some("ron")
|
||||
{
|
||||
let path = entry.path().to_string_lossy().replace('\\', "/");
|
||||
paths.push(path);
|
||||
}
|
||||
}
|
||||
paths.sort();
|
||||
paths
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
//! Reflect-driven inspector undo bridge (H2) — scoped to `shared` components.
|
||||
|
||||
use bevy::prelude::*;
|
||||
use bevy_egui::egui;
|
||||
|
||||
use shared::LevelObject;
|
||||
|
||||
/// Generic reflect inspector with undo for whitelisted authoring components.
|
||||
pub fn reflect_inspector_ui(_world: &mut World, ui: &mut egui::Ui, entity: Entity) {
|
||||
if _world
|
||||
.get_entity(entity)
|
||||
.is_ok_and(|e| e.contains::<LevelObject>())
|
||||
{
|
||||
ui.small("Reflect undo bridge: use typed inspectors for shared components.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
//! Selection delete/duplicate and camera focus helpers.
|
||||
|
||||
use bevy::prelude::*;
|
||||
use bevy_inspector_egui::bevy_inspector::hierarchy::SelectedEntities;
|
||||
use shared::LevelObject;
|
||||
|
||||
use crate::camera::EditorCamera;
|
||||
use crate::history::{delete_entities_with_history, duplicate_entities_with_history};
|
||||
use crate::selection::SelectedEntity;
|
||||
|
||||
pub fn focus_editor_camera_on_selection(world: &mut World) {
|
||||
let Some(entity) = world.resource::<SelectedEntity>().0 else {
|
||||
return;
|
||||
};
|
||||
let Some(target) = world.get::<GlobalTransform>(entity) else {
|
||||
return;
|
||||
};
|
||||
let center = target.translation();
|
||||
let mut cameras = world.query_filtered::<&mut Transform, With<EditorCamera>>();
|
||||
for mut transform in cameras.iter_mut(world) {
|
||||
let offset = transform.translation - center;
|
||||
let distance = offset.length().max(8.0);
|
||||
transform.translation = center - transform.forward().as_vec3() * distance;
|
||||
transform.look_at(center, Vec3::Y);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn selected_level_entities(world: &World, selected: &SelectedEntities) -> Vec<Entity> {
|
||||
selected
|
||||
.iter()
|
||||
.filter(|entity| {
|
||||
world
|
||||
.get_entity(*entity)
|
||||
.is_ok_and(|entity_ref| entity_ref.contains::<LevelObject>())
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn entity_name(world: &World, entity: Entity) -> String {
|
||||
world
|
||||
.get::<Name>(entity)
|
||||
.map(|name| name.as_str().to_string())
|
||||
.unwrap_or_else(|| format!("{entity:?}"))
|
||||
}
|
||||
|
||||
pub fn is_level_object(world: &World, entity: Entity) -> bool {
|
||||
world
|
||||
.get_entity(entity)
|
||||
.is_ok_and(|entity_ref| entity_ref.contains::<LevelObject>())
|
||||
}
|
||||
|
||||
pub fn delete_selection(world: &mut World, selected: &SelectedEntities) {
|
||||
let entities = selected_level_entities(world, selected);
|
||||
delete_entities_with_history(world, &entities);
|
||||
}
|
||||
|
||||
pub fn duplicate_selection(world: &mut World, selected: &SelectedEntities) {
|
||||
let entities = selected_level_entities(world, selected);
|
||||
duplicate_entities_with_history(world, &entities);
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
//! Fixed bottom status strip.
|
||||
|
||||
use bevy::prelude::*;
|
||||
use bevy_egui::egui;
|
||||
use bevy_inspector_egui::bevy_inspector::hierarchy::SelectedEntities;
|
||||
|
||||
use crate::history::EditorHistory;
|
||||
use crate::scene_io::SceneIo;
|
||||
use crate::state::{EditorMode, PlayPaused};
|
||||
|
||||
use super::theme::{status_bar_frame, TEXT};
|
||||
|
||||
pub fn status_bar_ui(
|
||||
world: &World,
|
||||
ctx: &egui::Context,
|
||||
selected: &SelectedEntities,
|
||||
mode: EditorMode,
|
||||
) {
|
||||
egui::TopBottomPanel::bottom("editor_status_bar")
|
||||
.exact_height(24.0)
|
||||
.frame(status_bar_frame())
|
||||
.show(ctx, |ui| {
|
||||
ui.horizontal_centered(|ui| {
|
||||
ui.spacing_mut().item_spacing.x = 16.0;
|
||||
ui.label(egui::RichText::new(scene_line(world)).color(TEXT));
|
||||
|
||||
let mode_label = match mode {
|
||||
EditorMode::Editing => "Edit".to_string(),
|
||||
EditorMode::Playing => {
|
||||
if world.resource::<PlayPaused>().0 {
|
||||
"Play (paused)".to_string()
|
||||
} else {
|
||||
"Play".to_string()
|
||||
}
|
||||
}
|
||||
};
|
||||
ui.label(egui::RichText::new(mode_label).color(TEXT));
|
||||
|
||||
let count = selected.len();
|
||||
let sel = if count == 0 {
|
||||
"None".to_string()
|
||||
} else if count == 1 {
|
||||
"1 selected".to_string()
|
||||
} else {
|
||||
format!("{count} selected")
|
||||
};
|
||||
ui.label(egui::RichText::new(sel).color(TEXT));
|
||||
|
||||
ui.label(
|
||||
egui::RichText::new(world.resource::<EditorHistory>().status.clone())
|
||||
.color(TEXT),
|
||||
);
|
||||
|
||||
#[cfg(feature = "hot-reload")]
|
||||
if let Some(hot) = world.get_resource::<crate::hot_reload::HotReloadState>() {
|
||||
ui.label(egui::RichText::new(hot.label.clone()).color(TEXT));
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
fn scene_line(world: &World) -> String {
|
||||
let scene_io = world.resource::<SceneIo>();
|
||||
let dirty = if scene_io.dirty { " *" } else { "" };
|
||||
format!("Scene: {}{dirty}", scene_io.active_path_label())
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
//! Unity-inspired dark pro theme for editor egui + egui_dock chrome.
|
||||
|
||||
use bevy_egui::egui::{self, Color32, CornerRadius, FontId, Stroke, Visuals};
|
||||
use egui_dock::{Style as DockStyle, TabInteractionStyle, TabStyle};
|
||||
|
||||
pub const PANEL_BG: Color32 = Color32::from_rgb(32, 33, 36);
|
||||
pub const PANEL_BG_DARK: Color32 = Color32::from_rgb(24, 25, 28);
|
||||
pub const WIDGET_BG: Color32 = Color32::from_rgb(42, 43, 47);
|
||||
pub const ELEVATED_BG: Color32 = Color32::from_rgb(55, 57, 63);
|
||||
pub const ACCENT: Color32 = Color32::from_rgb(56, 121, 184);
|
||||
pub const ACCENT_HOVER: Color32 = Color32::from_rgb(72, 143, 211);
|
||||
pub const SELECTION_BG: Color32 = Color32::from_rgb(46, 103, 158);
|
||||
pub const SELECTION_BG_MUTED: Color32 = Color32::from_rgb(43, 75, 108);
|
||||
pub const TEXT: Color32 = Color32::from_rgb(226, 229, 234);
|
||||
pub const TEXT_SELECTED: Color32 = Color32::from_rgb(250, 253, 255);
|
||||
pub const TEXT_DIM: Color32 = Color32::from_rgb(170, 176, 184);
|
||||
pub const TEXT_MUTED: Color32 = Color32::from_rgb(126, 133, 143);
|
||||
pub const BORDER: Color32 = Color32::from_rgb(69, 72, 78);
|
||||
pub const VIEWPORT_OVERLAY: Color32 = Color32::from_rgba_premultiplied(26, 27, 30, 220);
|
||||
|
||||
pub fn apply_editor_theme(ctx: &egui::Context) {
|
||||
let mut visuals = Visuals::dark();
|
||||
visuals.panel_fill = PANEL_BG;
|
||||
visuals.window_fill = WIDGET_BG;
|
||||
visuals.extreme_bg_color = PANEL_BG_DARK;
|
||||
visuals.faint_bg_color = Color32::from_rgb(38, 40, 44);
|
||||
visuals.code_bg_color = PANEL_BG_DARK;
|
||||
visuals.text_edit_bg_color = Some(PANEL_BG_DARK);
|
||||
visuals.weak_text_color = Some(TEXT_MUTED);
|
||||
visuals.widgets.noninteractive.bg_fill = WIDGET_BG;
|
||||
visuals.widgets.noninteractive.fg_stroke = Stroke::new(1.0, TEXT);
|
||||
visuals.widgets.inactive.bg_fill = WIDGET_BG;
|
||||
visuals.widgets.inactive.weak_bg_fill = Color32::from_rgb(47, 49, 54);
|
||||
visuals.widgets.inactive.bg_stroke = Stroke::new(1.0, BORDER);
|
||||
visuals.widgets.inactive.fg_stroke = Stroke::new(1.0, TEXT);
|
||||
visuals.widgets.hovered.bg_fill = ELEVATED_BG;
|
||||
visuals.widgets.hovered.weak_bg_fill = ELEVATED_BG;
|
||||
visuals.widgets.hovered.bg_stroke = Stroke::new(1.0, ACCENT_HOVER);
|
||||
visuals.widgets.hovered.fg_stroke = Stroke::new(1.0, TEXT_SELECTED);
|
||||
visuals.widgets.active.bg_fill = SELECTION_BG;
|
||||
visuals.widgets.active.weak_bg_fill = SELECTION_BG;
|
||||
visuals.widgets.active.bg_stroke = Stroke::new(1.0, ACCENT_HOVER);
|
||||
visuals.widgets.active.fg_stroke = Stroke::new(1.0, TEXT_SELECTED);
|
||||
visuals.widgets.open.bg_fill = ELEVATED_BG;
|
||||
visuals.widgets.open.weak_bg_fill = ELEVATED_BG;
|
||||
visuals.widgets.open.fg_stroke = Stroke::new(1.0, TEXT_SELECTED);
|
||||
visuals.selection.bg_fill = SELECTION_BG;
|
||||
visuals.selection.stroke = Stroke::new(1.0, TEXT_SELECTED);
|
||||
visuals.hyperlink_color = Color32::from_rgb(132, 186, 247);
|
||||
visuals.warn_fg_color = Color32::from_rgb(255, 200, 80);
|
||||
visuals.error_fg_color = Color32::from_rgb(255, 100, 100);
|
||||
visuals.window_stroke = Stroke::new(1.0, BORDER);
|
||||
visuals.window_corner_radius = CornerRadius::same(4);
|
||||
|
||||
let mut style = (*ctx.style()).clone();
|
||||
style.visuals = visuals;
|
||||
style.spacing.item_spacing = egui::vec2(8.0, 6.0);
|
||||
style.spacing.button_padding = egui::vec2(8.0, 4.0);
|
||||
style.spacing.indent = 16.0;
|
||||
style.text_styles.insert(
|
||||
egui::TextStyle::Body,
|
||||
FontId::new(13.0, egui::FontFamily::Proportional),
|
||||
);
|
||||
style.text_styles.insert(
|
||||
egui::TextStyle::Button,
|
||||
FontId::new(13.0, egui::FontFamily::Proportional),
|
||||
);
|
||||
style.text_styles.insert(
|
||||
egui::TextStyle::Heading,
|
||||
FontId::new(15.0, egui::FontFamily::Proportional),
|
||||
);
|
||||
ctx.set_style(style);
|
||||
}
|
||||
|
||||
pub fn editor_dock_style(ctx: &egui::Context) -> DockStyle {
|
||||
let mut style = DockStyle::from_egui(ctx.style().as_ref());
|
||||
style.dock_area_padding = Some(egui::Margin::same(2));
|
||||
style.main_surface_border_stroke = Stroke::new(1.0, BORDER);
|
||||
style.separator.width = 2.0;
|
||||
style.separator.color_idle = BORDER;
|
||||
style.separator.color_hovered = ELEVATED_BG;
|
||||
style.separator.color_dragged = ACCENT_HOVER;
|
||||
|
||||
style.tab_bar.bg_fill = PANEL_BG_DARK;
|
||||
style.tab_bar.height = 26.0;
|
||||
style.tab_bar.hline_color = BORDER;
|
||||
style.tab_bar.corner_radius = CornerRadius::ZERO;
|
||||
|
||||
let active = TabInteractionStyle {
|
||||
outline_color: BORDER,
|
||||
bg_fill: PANEL_BG,
|
||||
text_color: TEXT,
|
||||
corner_radius: CornerRadius::same(3),
|
||||
};
|
||||
let inactive = TabInteractionStyle {
|
||||
outline_color: Color32::TRANSPARENT,
|
||||
bg_fill: WIDGET_BG,
|
||||
text_color: TEXT_DIM,
|
||||
corner_radius: CornerRadius::same(3),
|
||||
};
|
||||
let hovered = TabInteractionStyle {
|
||||
outline_color: BORDER,
|
||||
bg_fill: ELEVATED_BG,
|
||||
text_color: TEXT,
|
||||
corner_radius: CornerRadius::same(3),
|
||||
};
|
||||
|
||||
style.tab = TabStyle {
|
||||
active: active.clone(),
|
||||
inactive: inactive.clone(),
|
||||
focused: active.clone(),
|
||||
hovered,
|
||||
inactive_with_kb_focus: inactive.clone(),
|
||||
active_with_kb_focus: active.clone(),
|
||||
focused_with_kb_focus: active,
|
||||
..style.tab
|
||||
};
|
||||
|
||||
style
|
||||
}
|
||||
|
||||
pub fn panel_heading(text: &str) -> egui::RichText {
|
||||
egui::RichText::new(text).strong().color(TEXT)
|
||||
}
|
||||
|
||||
pub fn status_bar_frame() -> egui::Frame {
|
||||
egui::Frame::new()
|
||||
.fill(Color32::from_rgb(0, 122, 204))
|
||||
.inner_margin(egui::Margin::symmetric(8, 2))
|
||||
}
|
||||
|
||||
pub fn viewport_toolbar_frame() -> egui::Frame {
|
||||
egui::Frame::new()
|
||||
.fill(VIEWPORT_OVERLAY)
|
||||
.corner_radius(CornerRadius::same(4))
|
||||
.inner_margin(egui::Margin::same(4))
|
||||
.stroke(Stroke::new(1.0, BORDER))
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
//! Top editor toolbar (below menu bar): spawn/file left, transport center.
|
||||
|
||||
use bevy::prelude::*;
|
||||
use bevy_egui::egui;
|
||||
use egui_phosphor_icons::icons;
|
||||
|
||||
use crate::history::spawn_with_history;
|
||||
use crate::scene_io::{SceneIo, SceneIoRequest};
|
||||
use crate::state::{EditorMode, PlayPaused, PlayPossession};
|
||||
use crate::ui::UiState;
|
||||
use crate::viewport::{editor_spawn_ground_position, snap_translation, ViewportSettings};
|
||||
use shared::PrimitiveShape;
|
||||
|
||||
use super::helpers::{
|
||||
light_snapshot, primitive_snapshot, toggle_play_mode, toggle_play_paused, toggle_possession,
|
||||
};
|
||||
use super::widgets::{icon_button, panel_toolbar_row, toolbar_separator, transport_button_large};
|
||||
|
||||
/// Toolbar strip height (menu bar is separate).
|
||||
const TOOLBAR_HEIGHT: f32 = 56.0;
|
||||
|
||||
pub fn editor_toolbar_panel(world: &mut World, ctx: &egui::Context) {
|
||||
egui::TopBottomPanel::top("editor_toolbar")
|
||||
.exact_height(TOOLBAR_HEIGHT)
|
||||
.show(ctx, |ui| {
|
||||
toolbar_ui(world, ui);
|
||||
});
|
||||
}
|
||||
|
||||
pub fn toolbar_ui(world: &mut World, ui: &mut egui::Ui) {
|
||||
let (toolbar_rect, _) = ui.allocate_exact_size(
|
||||
egui::vec2(ui.available_width(), TOOLBAR_HEIGHT - 4.0),
|
||||
egui::Sense::hover(),
|
||||
);
|
||||
|
||||
let center_y = toolbar_rect.center().y;
|
||||
let left_rect = egui::Rect::from_min_max(
|
||||
egui::pos2(toolbar_rect.left() + 8.0, center_y - 18.0),
|
||||
egui::pos2(toolbar_rect.right(), center_y + 18.0),
|
||||
);
|
||||
let transport_rect = egui::Rect::from_center_size(
|
||||
egui::pos2(toolbar_rect.center().x, center_y),
|
||||
egui::vec2(transport_width(world), 44.0),
|
||||
);
|
||||
|
||||
let mut left_ui = ui.new_child(
|
||||
egui::UiBuilder::new()
|
||||
.id_salt("toolbar_left")
|
||||
.max_rect(left_rect)
|
||||
.layout(egui::Layout::left_to_right(egui::Align::Center)),
|
||||
);
|
||||
left_ui.spacing_mut().item_spacing.x = 6.0;
|
||||
left_toolbar(world, &mut left_ui);
|
||||
|
||||
let mut transport_ui = ui.new_child(
|
||||
egui::UiBuilder::new()
|
||||
.id_salt("toolbar_transport")
|
||||
.max_rect(transport_rect)
|
||||
.layout(egui::Layout::left_to_right(egui::Align::Center)),
|
||||
);
|
||||
transport_ui.spacing_mut().item_spacing.x = 10.0;
|
||||
transport_controls(world, &mut transport_ui);
|
||||
}
|
||||
|
||||
fn transport_width(world: &World) -> f32 {
|
||||
let button_count = match *world.resource::<State<EditorMode>>().get() {
|
||||
EditorMode::Editing => 1.0,
|
||||
EditorMode::Playing => 3.0,
|
||||
};
|
||||
let gap_count = button_count - 1.0;
|
||||
|
||||
button_count * 44.0 + gap_count * 10.0
|
||||
}
|
||||
|
||||
fn left_toolbar(world: &mut World, ui: &mut egui::Ui) {
|
||||
panel_toolbar_row(ui, |ui| {
|
||||
if icon_button(ui, icons::CUBE, "Spawn cube").clicked() {
|
||||
spawn_primitive_at_camera(world, PrimitiveShape::Box, "Cube");
|
||||
}
|
||||
if icon_button(ui, icons::MOUNTAINS, "Spawn ramp").clicked() {
|
||||
spawn_primitive_at_camera(world, PrimitiveShape::Ramp, "Ramp");
|
||||
}
|
||||
if icon_button(ui, icons::SPHERE, "Spawn sphere").clicked() {
|
||||
spawn_primitive_at_camera(world, PrimitiveShape::Sphere, "Sphere");
|
||||
}
|
||||
if icon_button(ui, icons::LIGHTBULB, "Spawn point light").clicked() {
|
||||
let pos = camera_ground_spawn(world);
|
||||
spawn_with_history(world, light_snapshot("Point Light", pos));
|
||||
}
|
||||
|
||||
toolbar_separator(ui);
|
||||
|
||||
if icon_button(ui, icons::FILE, "New scene").clicked() {
|
||||
world.resource_mut::<SceneIo>().request = Some(SceneIoRequest::New);
|
||||
}
|
||||
if icon_button(ui, icons::FOLDER_OPEN, "Open scene").clicked() {
|
||||
world.resource_mut::<SceneIo>().request = Some(SceneIoRequest::Open);
|
||||
}
|
||||
if icon_button(ui, icons::FLOPPY_DISK, "Save scene").clicked() {
|
||||
world.resource_mut::<SceneIo>().request = Some(SceneIoRequest::Save);
|
||||
}
|
||||
if icon_button(ui, icons::COPY, "Save scene as").clicked() {
|
||||
world.resource_mut::<SceneIo>().request = Some(SceneIoRequest::SaveAs);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn transport_controls(world: &mut World, ui: &mut egui::Ui) {
|
||||
let mode = *world.resource::<State<EditorMode>>().get();
|
||||
match mode {
|
||||
EditorMode::Editing => {
|
||||
if transport_button_large(ui, icons::PLAY, "Play (F5)", true).clicked() {
|
||||
toggle_play_mode(world);
|
||||
}
|
||||
}
|
||||
EditorMode::Playing => {
|
||||
let paused = world.resource::<PlayPaused>().0;
|
||||
let pause_icon = if paused { icons::PLAY } else { icons::PAUSE };
|
||||
let pause_tip = if paused {
|
||||
"Resume simulation (F6)"
|
||||
} else {
|
||||
"Pause simulation (F6)"
|
||||
};
|
||||
if transport_button_large(ui, pause_icon, pause_tip, false).clicked() {
|
||||
toggle_play_paused(world);
|
||||
}
|
||||
if transport_button_large(ui, icons::STOP, "Stop and return to Edit (F5)", false)
|
||||
.clicked()
|
||||
{
|
||||
toggle_play_mode(world);
|
||||
}
|
||||
|
||||
let possession = *world.resource::<PlayPossession>();
|
||||
let (eject_icon, eject_tip) = match possession {
|
||||
PlayPossession::Possessed => (icons::SIGN_OUT, "Eject from player (F8)"),
|
||||
PlayPossession::Ejected => (icons::USER, "Possess player (F8)"),
|
||||
};
|
||||
if transport_button_large(ui, eject_icon, eject_tip, false).clicked() {
|
||||
toggle_possession(world);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn camera_ground_spawn(world: &mut World) -> Vec3 {
|
||||
let rect = world.resource::<UiState>().viewport_rect;
|
||||
let settings = world.resource::<ViewportSettings>().clone();
|
||||
let pos = editor_spawn_ground_position(world, rect);
|
||||
snap_translation(pos, &settings)
|
||||
}
|
||||
|
||||
fn spawn_primitive_at_camera(world: &mut World, shape: PrimitiveShape, name: &str) {
|
||||
let pos = camera_ground_spawn(world);
|
||||
spawn_with_history(world, primitive_snapshot(name, shape, pos));
|
||||
}
|
||||
@@ -0,0 +1,530 @@
|
||||
//! Unified viewport overlay chrome (toolbars, badges, HUD).
|
||||
|
||||
use bevy::prelude::*;
|
||||
use bevy_egui::{egui, EguiTextureHandle, EguiUserTextures};
|
||||
use bevy_inspector_egui::bevy_inspector::hierarchy::SelectedEntities;
|
||||
use egui_phosphor_icons::icons;
|
||||
|
||||
use crate::assets::EditorAssets;
|
||||
use crate::gizmos::{EditorGizmoMode, EditorGizmoSpace};
|
||||
use crate::render_target::ViewportRenderTarget;
|
||||
use crate::selection::ViewportClick;
|
||||
use crate::state::PlayPossession;
|
||||
use crate::viewport::{
|
||||
snap_translation, viewport_ground_position, EditorViewportMode, ViewportDisplayMode,
|
||||
ViewportSettings,
|
||||
};
|
||||
|
||||
use super::helpers::{
|
||||
focus_editor_camera_on_selection, viewport_recall_bookmark, viewport_save_bookmark,
|
||||
};
|
||||
use super::theme::viewport_toolbar_frame;
|
||||
use super::widgets::{icon_button_small, panel_toolbar_row, tool_button};
|
||||
|
||||
#[derive(Resource, Default)]
|
||||
pub struct ViewportUiState {
|
||||
pub options_open: bool,
|
||||
pub shortcuts_open: bool,
|
||||
}
|
||||
|
||||
const VIEWPORT_TOOLTIP: &str = "RMB + WASD/QE: fly | MMB: pan | Scroll: dolly\nW/E/R: gizmo | X: world/local | F: focus | G: game view | Ctrl+G: grid\nTab: cycle overlapping picks | Play/Pause/Stop: main toolbar (F5 / F6)";
|
||||
|
||||
pub fn viewport_tab_ui(
|
||||
world: &mut World,
|
||||
ui: &mut egui::Ui,
|
||||
viewport_rect: &mut egui::Rect,
|
||||
pointer_in_viewport: &mut bool,
|
||||
viewport_pointer_pos: &mut Option<egui::Pos2>,
|
||||
selected_entities: &SelectedEntities,
|
||||
playing: bool,
|
||||
_cursor_grabbed: bool,
|
||||
) {
|
||||
let rect = ui.available_rect_before_wrap();
|
||||
*viewport_rect = rect;
|
||||
|
||||
if rect.width() <= 1.0 || rect.height() <= 1.0 {
|
||||
*pointer_in_viewport = false;
|
||||
*viewport_pointer_pos = None;
|
||||
return;
|
||||
}
|
||||
|
||||
let clean_game_view = world.resource::<ViewportDisplayMode>().clean_game_view;
|
||||
let response = ui.allocate_rect(rect, egui::Sense::HOVER);
|
||||
*viewport_pointer_pos = response
|
||||
.interact_pointer_pos()
|
||||
.or_else(|| response.hover_pos())
|
||||
.filter(|pos| rect.contains(*pos));
|
||||
*pointer_in_viewport = viewport_pointer_pos.is_some();
|
||||
|
||||
let primary_clicked =
|
||||
ui.input(|input| input.pointer.button_clicked(egui::PointerButton::Primary));
|
||||
if primary_clicked && !clean_game_view {
|
||||
if let Some(pos) = response
|
||||
.interact_pointer_pos()
|
||||
.or_else(|| response.hover_pos())
|
||||
.filter(|pos| rect.contains(*pos))
|
||||
{
|
||||
world.resource_mut::<ViewportClick>().0 = Some(pos);
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(target) = world
|
||||
.get_resource::<ViewportRenderTarget>()
|
||||
.and_then(|target| target.0.clone())
|
||||
{
|
||||
let mut textures = world.resource_mut::<EguiUserTextures>();
|
||||
let texture_id = textures
|
||||
.image_id(target.image.id())
|
||||
.unwrap_or_else(|| textures.add_image(EguiTextureHandle::Strong(target.image.clone())));
|
||||
|
||||
let painter = ui.painter();
|
||||
painter.rect_filled(rect, 0.0, egui::Color32::BLACK);
|
||||
painter.image(
|
||||
texture_id,
|
||||
rect,
|
||||
egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)),
|
||||
egui::Color32::WHITE,
|
||||
);
|
||||
} else {
|
||||
ui.allocate_rect(rect, egui::Sense::hover());
|
||||
ui.scope_builder(egui::UiBuilder::new().max_rect(rect), |ui| {
|
||||
ui.centered_and_justified(|ui| {
|
||||
ui.label(egui::RichText::new("Viewport").weak());
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
if clean_game_view {
|
||||
if playing {
|
||||
game_view_overlay(world, ui.ctx(), rect, playing);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
scene_view_overlay_toolbar(world, ui.ctx(), rect);
|
||||
scene_view_mode_badge(world, ui.ctx(), rect);
|
||||
scene_view_gi_badge(world, ui.ctx(), rect);
|
||||
scene_view_volume_hud(world, ui.ctx(), rect);
|
||||
viewport_asset_drop_ui(world, ui, rect, selected_entities);
|
||||
}
|
||||
|
||||
fn scene_view_mode_badge(world: &World, ctx: &egui::Context, scene_rect: egui::Rect) {
|
||||
let Some(mode) = world.get_resource::<EditorViewportMode>() else {
|
||||
return;
|
||||
};
|
||||
let mode = *mode;
|
||||
let (label, color) = match mode {
|
||||
EditorViewportMode::Lit => ("Lit", egui::Color32::from_rgb(120, 200, 120)),
|
||||
EditorViewportMode::Unlit => ("Unlit", egui::Color32::from_rgb(200, 200, 120)),
|
||||
EditorViewportMode::Collider => ("Collider", egui::Color32::from_rgb(220, 140, 80)),
|
||||
};
|
||||
|
||||
egui::Area::new(egui::Id::new("scene_view_mode_badge"))
|
||||
.fixed_pos(scene_rect.right_bottom() + egui::vec2(-72.0, -22.0))
|
||||
.interactable(false)
|
||||
.show(ctx, |ui| {
|
||||
egui::Frame::NONE
|
||||
.fill(egui::Color32::from_black_alpha(160))
|
||||
.inner_margin(egui::Margin::symmetric(8, 4))
|
||||
.show(ui, |ui| {
|
||||
ui.colored_label(color, label);
|
||||
});
|
||||
});
|
||||
|
||||
if mode == EditorViewportMode::Collider {
|
||||
egui::Area::new(egui::Id::new("scene_view_collider_warning"))
|
||||
.fixed_pos(scene_rect.left_bottom() + egui::vec2(8.0, -28.0))
|
||||
.interactable(false)
|
||||
.show(ctx, |ui| {
|
||||
ui.colored_label(
|
||||
egui::Color32::from_rgb(255, 180, 100),
|
||||
"Meshes hidden - switch to Lit (sun icon) for shading",
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn scene_view_gi_badge(world: &World, ctx: &egui::Context, scene_rect: egui::Rect) {
|
||||
let Some(profile) = world.get_resource::<settings::ActiveCameraRenderProfile>() else {
|
||||
return;
|
||||
};
|
||||
let (label, color) = match profile.gi_path {
|
||||
settings::GiPath::Forward => ("Forward", egui::Color32::from_rgb(140, 180, 255)),
|
||||
settings::GiPath::SolariDeferred => ("Solari", egui::Color32::from_rgb(255, 170, 90)),
|
||||
};
|
||||
egui::Area::new(egui::Id::new("scene_view_gi_badge"))
|
||||
.fixed_pos(scene_rect.right_bottom() + egui::vec2(-148.0, -22.0))
|
||||
.interactable(false)
|
||||
.show(ctx, |ui| {
|
||||
egui::Frame::NONE
|
||||
.fill(egui::Color32::from_black_alpha(160))
|
||||
.inner_margin(egui::Margin::symmetric(8, 4))
|
||||
.show(ui, |ui| {
|
||||
ui.colored_label(color, label);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
fn scene_view_volume_hud(world: &World, ctx: &egui::Context, scene_rect: egui::Rect) {
|
||||
let Some(contributions) = world.get_resource::<settings::ActiveVolumeContribution>() else {
|
||||
return;
|
||||
};
|
||||
let Some(primary) = contributions.entries.first() else {
|
||||
return;
|
||||
};
|
||||
egui::Area::new(egui::Id::new("scene_view_volume_hud"))
|
||||
.fixed_pos(scene_rect.left_bottom() + egui::vec2(8.0, -56.0))
|
||||
.interactable(false)
|
||||
.show(ctx, |ui| {
|
||||
egui::Frame::NONE
|
||||
.fill(egui::Color32::from_black_alpha(150))
|
||||
.inner_margin(egui::Margin::symmetric(8, 4))
|
||||
.show(ui, |ui| {
|
||||
ui.label(format!(
|
||||
"Volume: {} ({:.0}%, {} overrides)",
|
||||
primary.label,
|
||||
primary.weight * 100.0,
|
||||
primary.override_count
|
||||
));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
fn scene_view_overlay_toolbar(world: &mut World, ctx: &egui::Context, scene_rect: egui::Rect) {
|
||||
let mut options_open = world.resource::<ViewportUiState>().options_open;
|
||||
let mut shortcuts_open = world.resource::<ViewportUiState>().shortcuts_open;
|
||||
|
||||
egui::Area::new(egui::Id::new("scene_view_toolbar"))
|
||||
.fixed_pos(scene_rect.left_top() + egui::vec2(6.0, 6.0))
|
||||
.interactable(true)
|
||||
.show(ctx, |ui| {
|
||||
viewport_toolbar_frame().show(ui, |ui| {
|
||||
panel_toolbar_row(ui, |ui| {
|
||||
let gizmo_mode = *world.resource::<crate::gizmos::EditorGizmoMode>();
|
||||
if tool_button(
|
||||
ui,
|
||||
icons::ARROWS_OUT_CARDINAL,
|
||||
gizmo_mode == EditorGizmoMode::Translate,
|
||||
"Translate (W)",
|
||||
)
|
||||
.clicked()
|
||||
{
|
||||
super::helpers::set_gizmo_mode(world, EditorGizmoMode::Translate);
|
||||
}
|
||||
if tool_button(
|
||||
ui,
|
||||
icons::ARROWS_CLOCKWISE,
|
||||
gizmo_mode == EditorGizmoMode::Rotate,
|
||||
"Rotate (E)",
|
||||
)
|
||||
.clicked()
|
||||
{
|
||||
super::helpers::set_gizmo_mode(world, EditorGizmoMode::Rotate);
|
||||
}
|
||||
if tool_button(
|
||||
ui,
|
||||
icons::ARROWS_IN_LINE_HORIZONTAL,
|
||||
gizmo_mode == EditorGizmoMode::Scale,
|
||||
"Scale (R)",
|
||||
)
|
||||
.clicked()
|
||||
{
|
||||
super::helpers::set_gizmo_mode(world, EditorGizmoMode::Scale);
|
||||
}
|
||||
|
||||
ui.separator();
|
||||
|
||||
let space = *world.resource::<EditorGizmoSpace>();
|
||||
if tool_button(
|
||||
ui,
|
||||
icons::GLOBE,
|
||||
space == EditorGizmoSpace::World,
|
||||
"World space (X)",
|
||||
)
|
||||
.clicked()
|
||||
{
|
||||
super::helpers::set_gizmo_space(world, EditorGizmoSpace::World);
|
||||
}
|
||||
if tool_button(
|
||||
ui,
|
||||
icons::CUBE,
|
||||
space == EditorGizmoSpace::Local,
|
||||
"Local space (X)",
|
||||
)
|
||||
.clicked()
|
||||
{
|
||||
super::helpers::set_gizmo_space(world, EditorGizmoSpace::Local);
|
||||
}
|
||||
|
||||
ui.separator();
|
||||
|
||||
let viewport_mode = *world.resource::<EditorViewportMode>();
|
||||
if tool_button(
|
||||
ui,
|
||||
icons::SUN,
|
||||
viewport_mode == EditorViewportMode::Lit,
|
||||
"Lit shading (WYSIWYG)",
|
||||
)
|
||||
.clicked()
|
||||
{
|
||||
*world.resource_mut::<EditorViewportMode>() = EditorViewportMode::Lit;
|
||||
}
|
||||
if tool_button(
|
||||
ui,
|
||||
icons::PAINT_BRUSH,
|
||||
viewport_mode == EditorViewportMode::Unlit,
|
||||
"Unlit base color (debug albedo)",
|
||||
)
|
||||
.clicked()
|
||||
{
|
||||
*world.resource_mut::<EditorViewportMode>() = EditorViewportMode::Unlit;
|
||||
}
|
||||
if tool_button(
|
||||
ui,
|
||||
icons::BOUNDING_BOX,
|
||||
viewport_mode == EditorViewportMode::Collider,
|
||||
"Collider view (hide meshes)",
|
||||
)
|
||||
.clicked()
|
||||
{
|
||||
*world.resource_mut::<EditorViewportMode>() = EditorViewportMode::Collider;
|
||||
}
|
||||
|
||||
ui.separator();
|
||||
|
||||
if let Some(mut settings) = world.get_resource_mut::<ViewportSettings>() {
|
||||
let grid = settings.show_grid;
|
||||
if tool_button(ui, icons::GRID_FOUR, grid, "Toggle grid (Ctrl+G)").clicked()
|
||||
{
|
||||
settings.show_grid = !settings.show_grid;
|
||||
}
|
||||
let snap = settings.snap_translate;
|
||||
if tool_button(ui, icons::MAGNET, snap, "Snap translation").clicked() {
|
||||
settings.snap_translate = !settings.snap_translate;
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(mut visualizers) =
|
||||
world.get_resource_mut::<crate::visualizers::EditorVisualizationSettings>()
|
||||
{
|
||||
let enabled = visualizers.enabled;
|
||||
if tool_button(ui, icons::EYE, enabled, "Toggle scene visualizers")
|
||||
.clicked()
|
||||
{
|
||||
visualizers.enabled = !visualizers.enabled;
|
||||
}
|
||||
}
|
||||
|
||||
let clean_game_view = world.resource::<ViewportDisplayMode>().clean_game_view;
|
||||
if tool_button(
|
||||
ui,
|
||||
icons::GAME_CONTROLLER,
|
||||
clean_game_view,
|
||||
"Game view overlay (G)",
|
||||
)
|
||||
.clicked()
|
||||
{
|
||||
world.resource_mut::<ViewportDisplayMode>().clean_game_view =
|
||||
!clean_game_view;
|
||||
}
|
||||
|
||||
if icon_button_small(ui, icons::CROSSHAIR, "Focus selection (F)").clicked() {
|
||||
focus_editor_camera_on_selection(world);
|
||||
}
|
||||
|
||||
if icon_button_small(ui, icons::GEAR, "Viewport options").clicked() {
|
||||
options_open = !options_open;
|
||||
}
|
||||
if icon_button_small(ui, icons::QUESTION, VIEWPORT_TOOLTIP).clicked() {
|
||||
shortcuts_open = !shortcuts_open;
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
if options_open {
|
||||
scene_options_popover(world, ctx, scene_rect, &mut options_open);
|
||||
}
|
||||
if shortcuts_open {
|
||||
viewport_shortcuts_window(ctx, &mut shortcuts_open);
|
||||
}
|
||||
|
||||
world.resource_mut::<ViewportUiState>().options_open = options_open;
|
||||
world.resource_mut::<ViewportUiState>().shortcuts_open = shortcuts_open;
|
||||
}
|
||||
|
||||
fn scene_options_popover(
|
||||
world: &mut World,
|
||||
ctx: &egui::Context,
|
||||
scene_rect: egui::Rect,
|
||||
open: &mut bool,
|
||||
) {
|
||||
egui::Area::new(egui::Id::new("scene_view_options"))
|
||||
.fixed_pos(scene_rect.left_top() + egui::vec2(6.0, 44.0))
|
||||
.show(ctx, |ui| {
|
||||
viewport_toolbar_frame().show(ui, |ui| {
|
||||
ui.set_min_width(220.0);
|
||||
ui.heading("Viewport Options");
|
||||
if let Some(mut display) = world.get_resource_mut::<ViewportDisplayMode>() {
|
||||
ui.checkbox(&mut display.clean_game_view, "Game view overlay");
|
||||
ui.small("G toggles game view; Ctrl+G toggles grid");
|
||||
}
|
||||
if let Some(mut settings) = world.get_resource_mut::<ViewportSettings>() {
|
||||
ui.separator();
|
||||
ui.checkbox(&mut settings.show_grid, "Show grid");
|
||||
ui.checkbox(&mut settings.snap_translate, "Snap translation");
|
||||
ui.add(
|
||||
egui::Slider::new(&mut settings.snap_increment, 0.25..=4.0)
|
||||
.text("Snap step"),
|
||||
);
|
||||
}
|
||||
if let Some(mut mode) = world.get_resource_mut::<EditorViewportMode>() {
|
||||
ui.separator();
|
||||
ui.label("Shading");
|
||||
ui.horizontal(|ui| {
|
||||
ui.selectable_value(&mut *mode, EditorViewportMode::Lit, "Lit");
|
||||
ui.selectable_value(&mut *mode, EditorViewportMode::Unlit, "Unlit");
|
||||
ui.selectable_value(&mut *mode, EditorViewportMode::Collider, "Colliders");
|
||||
});
|
||||
}
|
||||
if let Some(mut visualizers) =
|
||||
world.get_resource_mut::<crate::visualizers::EditorVisualizationSettings>()
|
||||
{
|
||||
ui.separator();
|
||||
ui.checkbox(&mut visualizers.enabled, "Show visualizers");
|
||||
ui.add_enabled_ui(visualizers.enabled, |ui| {
|
||||
ui.checkbox(&mut visualizers.show_actor_icons, "Actor root icons");
|
||||
ui.add_enabled_ui(visualizers.show_actor_icons, |ui| {
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.checkbox(&mut visualizers.show_actor_icon_actor, "Actors");
|
||||
ui.checkbox(&mut visualizers.show_actor_icon_mesh, "Meshes");
|
||||
ui.checkbox(&mut visualizers.show_actor_icon_light, "Lights");
|
||||
ui.checkbox(&mut visualizers.show_actor_icon_physics, "Physics");
|
||||
ui.checkbox(&mut visualizers.show_actor_icon_gameplay, "Gameplay");
|
||||
ui.checkbox(&mut visualizers.show_actor_icon_volume, "Volumes");
|
||||
ui.checkbox(
|
||||
&mut visualizers.show_actor_icon_prefab_model,
|
||||
"Prefabs/models",
|
||||
);
|
||||
ui.checkbox(&mut visualizers.show_actor_icon_debug, "Warnings");
|
||||
});
|
||||
});
|
||||
ui.separator();
|
||||
ui.checkbox(&mut visualizers.show_colliders, "Colliders");
|
||||
ui.checkbox(&mut visualizers.show_lights, "Lights");
|
||||
ui.checkbox(&mut visualizers.show_spawns, "Player spawns");
|
||||
ui.checkbox(
|
||||
&mut visualizers.show_prefab_model_anchors,
|
||||
"Prefab/model anchors",
|
||||
);
|
||||
ui.checkbox(&mut visualizers.show_runtime, "Runtime player/cameras");
|
||||
ui.checkbox(&mut visualizers.pickable_proxies, "Selectable proxies");
|
||||
});
|
||||
}
|
||||
ui.horizontal(|ui| {
|
||||
if ui.button("Save bookmark").clicked() {
|
||||
viewport_save_bookmark(world);
|
||||
}
|
||||
if ui.button("Recall bookmark").clicked() {
|
||||
viewport_recall_bookmark(world);
|
||||
}
|
||||
});
|
||||
ui.small("Ctrl+Shift+1 save | Ctrl+Shift+2 recall");
|
||||
if ui.button("Close").clicked() {
|
||||
*open = false;
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
fn viewport_shortcuts_window(ctx: &egui::Context, open: &mut bool) {
|
||||
egui::Window::new("Viewport Shortcuts")
|
||||
.open(open)
|
||||
.default_width(320.0)
|
||||
.show(ctx, |ui| {
|
||||
ui.label("Viewport navigation");
|
||||
ui.small("RMB + WASD/QE - fly camera");
|
||||
ui.small("MMB drag - pan");
|
||||
ui.small("Scroll - dolly");
|
||||
ui.separator();
|
||||
ui.label("Tools");
|
||||
ui.small("W / E / R - translate / rotate / scale gizmo");
|
||||
ui.small("X - toggle world / local space");
|
||||
ui.small("G - toggle game view overlay");
|
||||
ui.small("Ctrl+G - toggle grid");
|
||||
ui.small("F - focus selection");
|
||||
ui.small("Tab - cycle overlapping selection at click");
|
||||
ui.small("F5 - play / stop (main toolbar)");
|
||||
ui.small("F6 - pause / resume (while playing)");
|
||||
ui.small("F8 - possess / eject (while playing)");
|
||||
ui.small("Esc - deselect / free cursor");
|
||||
});
|
||||
}
|
||||
|
||||
fn game_view_overlay(world: &World, ctx: &egui::Context, rect: egui::Rect, playing: bool) {
|
||||
egui::Area::new(egui::Id::new("game_view_hud"))
|
||||
.fixed_pos(rect.left_top() + egui::vec2(6.0, 6.0))
|
||||
.interactable(false)
|
||||
.show(ctx, |ui| {
|
||||
viewport_toolbar_frame().show(ui, |ui| {
|
||||
if !playing {
|
||||
ui.label(egui::RichText::new("Game View").strong());
|
||||
ui.small("Press F5 or Play to run here.");
|
||||
return;
|
||||
}
|
||||
|
||||
ui.label(egui::RichText::new("Playing").strong());
|
||||
let possession = *world.resource::<PlayPossession>();
|
||||
let possess_label = match possession {
|
||||
PlayPossession::Possessed => "Possessed",
|
||||
PlayPossession::Ejected => "Ejected (Scene camera)",
|
||||
};
|
||||
ui.small(possess_label);
|
||||
ui.small("F5 stop | F6 pause | F8 possess/eject | Esc free cursor");
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
fn viewport_asset_drop_ui(
|
||||
world: &mut World,
|
||||
ui: &mut egui::Ui,
|
||||
viewport_rect: egui::Rect,
|
||||
selected: &SelectedEntities,
|
||||
) {
|
||||
let pointer_released = ui.input(|input| input.pointer.any_released());
|
||||
if !pointer_released {
|
||||
return;
|
||||
}
|
||||
|
||||
let pointer_pos = ui.input(|input| input.pointer.hover_pos());
|
||||
if !pointer_pos.is_some_and(|pos| viewport_rect.contains(pos)) {
|
||||
world.resource_mut::<EditorAssets>().clear_drag();
|
||||
return;
|
||||
}
|
||||
|
||||
let asset = {
|
||||
let assets = world.resource::<EditorAssets>();
|
||||
assets.dragging_asset().cloned()
|
||||
};
|
||||
world.resource_mut::<EditorAssets>().clear_drag();
|
||||
|
||||
let Some(asset) = asset else {
|
||||
return;
|
||||
};
|
||||
match asset.kind {
|
||||
crate::assets::EditorAssetKind::Texture => {
|
||||
crate::ui::helpers::apply_texture_to_selection(world, &asset, selected);
|
||||
return;
|
||||
}
|
||||
crate::assets::EditorAssetKind::Material => {
|
||||
crate::ui::helpers::apply_material_asset_to_selection(world, &asset, selected);
|
||||
return;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
//! Reusable editor widgets: icon buttons, tool toggles, menu labels.
|
||||
|
||||
use bevy_egui::egui::{self, Button, FontId, RichText, Ui, WidgetText};
|
||||
use egui_phosphor_icons::Icon;
|
||||
|
||||
use super::theme::{ACCENT, ACCENT_HOVER, ELEVATED_BG};
|
||||
|
||||
const PHOSPHOR: &str = "phosphor-regular";
|
||||
|
||||
pub fn phosphor_icon(icon: Icon, size: f32) -> RichText {
|
||||
phosphor_icon_text(icon.as_str(), size)
|
||||
}
|
||||
|
||||
pub fn phosphor_icon_text(icon: &str, size: f32) -> RichText {
|
||||
RichText::new(icon).font(FontId::new(size, egui::FontFamily::Name(PHOSPHOR.into())))
|
||||
}
|
||||
|
||||
/// Large transport control (Play / Pause / Stop / Eject) — icon only, tooltip for label.
|
||||
pub fn transport_button_large(
|
||||
ui: &mut Ui,
|
||||
icon: Icon,
|
||||
tooltip: &str,
|
||||
accent: bool,
|
||||
) -> egui::Response {
|
||||
const SIZE: f32 = 44.0;
|
||||
const ICON_PX: f32 = 22.0;
|
||||
|
||||
let fill = if accent {
|
||||
ACCENT
|
||||
} else {
|
||||
ELEVATED_BG.linear_multiply(0.85)
|
||||
};
|
||||
ui.add(
|
||||
Button::new(phosphor_icon(icon, ICON_PX))
|
||||
.fill(fill)
|
||||
.stroke(egui::Stroke::new(
|
||||
1.0,
|
||||
if accent {
|
||||
ACCENT_HOVER
|
||||
} else {
|
||||
super::theme::BORDER
|
||||
},
|
||||
))
|
||||
.min_size(egui::vec2(SIZE, SIZE))
|
||||
.corner_radius(5.0),
|
||||
)
|
||||
.on_hover_text(tooltip)
|
||||
}
|
||||
|
||||
pub fn icon_button(ui: &mut Ui, icon: Icon, tooltip: &str) -> egui::Response {
|
||||
ui.add(
|
||||
Button::new(phosphor_icon(icon, 18.0))
|
||||
.frame(false)
|
||||
.min_size(egui::vec2(32.0, 32.0)),
|
||||
)
|
||||
.on_hover_text(tooltip)
|
||||
}
|
||||
|
||||
pub fn icon_button_small(ui: &mut Ui, icon: Icon, tooltip: &str) -> egui::Response {
|
||||
ui.add(
|
||||
Button::new(phosphor_icon(icon, 16.0))
|
||||
.frame(false)
|
||||
.min_size(egui::vec2(22.0, 22.0)),
|
||||
)
|
||||
.on_hover_text(tooltip)
|
||||
}
|
||||
|
||||
pub fn tool_button(ui: &mut Ui, icon: Icon, selected: bool, tooltip: &str) -> egui::Response {
|
||||
let fill = if selected {
|
||||
ACCENT
|
||||
} else {
|
||||
ELEVATED_BG.linear_multiply(0.6)
|
||||
};
|
||||
ui.add(
|
||||
Button::new(phosphor_icon(icon, 16.0))
|
||||
.fill(fill)
|
||||
.stroke(egui::Stroke::new(
|
||||
1.0,
|
||||
if selected {
|
||||
ACCENT
|
||||
} else {
|
||||
super::theme::BORDER
|
||||
},
|
||||
))
|
||||
.min_size(egui::vec2(26.0, 26.0))
|
||||
.corner_radius(3.0),
|
||||
)
|
||||
.on_hover_text(tooltip)
|
||||
}
|
||||
|
||||
pub fn menu_item(
|
||||
ui: &mut Ui,
|
||||
label: &str,
|
||||
shortcut: Option<&str>,
|
||||
enabled: bool,
|
||||
) -> egui::Response {
|
||||
let text: WidgetText = if let Some(key) = shortcut {
|
||||
RichText::new(format!("{label}\t{key}")).into()
|
||||
} else {
|
||||
label.into()
|
||||
};
|
||||
ui.add_enabled(enabled, egui::Button::new(text))
|
||||
}
|
||||
|
||||
pub fn toolbar_separator(ui: &mut Ui) {
|
||||
ui.add_space(4.0);
|
||||
ui.separator();
|
||||
ui.add_space(4.0);
|
||||
}
|
||||
|
||||
pub fn panel_toolbar_row<R>(ui: &mut Ui, add_contents: impl FnOnce(&mut Ui) -> R) -> R {
|
||||
ui.horizontal(|ui| {
|
||||
ui.spacing_mut().item_spacing.x = 4.0;
|
||||
add_contents(ui)
|
||||
})
|
||||
.inner
|
||||
}
|
||||
Reference in new issue
Block a user