This commit is contained in:
commit
f29712d158
259 files changed
+52069
No files matched your search
@@ -0,0 +1,5 @@
|
||||
//! Scene I/O, schema validation, and viewport render-target setup.
|
||||
|
||||
pub mod scene_io;
|
||||
pub mod scene_schema;
|
||||
pub mod scene_view;
|
||||
@@ -0,0 +1,628 @@
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use bevy::ecs::entity::EntityHashMap;
|
||||
use bevy::ecs::system::SystemState;
|
||||
use bevy::prelude::*;
|
||||
use bevy::scene::serde::SceneDeserializer;
|
||||
use bevy::scene::DynamicScene;
|
||||
use bevy::scene::DynamicSceneBuilder;
|
||||
use bevy::window::PrimaryWindow;
|
||||
use scene::{migrate_scene_text, stamp_schema_version, strip_schema_version, validate_level_text};
|
||||
use serde::de::DeserializeSeed;
|
||||
use shared::{
|
||||
flush_level_object_hydration, infer_actor_kind, strip_hydrated_entity, validate_actor, ActorId,
|
||||
ActorKind, ActorName, ActorValidationError, ColliderDesc, EditorVisibility,
|
||||
HierarchySiblingIndex, InspectorOrder, LevelObject, LightDesc, MaterialDesc, MaterialOverride,
|
||||
ModelRef, ObjectiveMarker, PhysicsBody, PlayerSpawn, PostProcessVolumeDesc, PrefabInstance,
|
||||
PrefabRef, Primitive, RigidBodyDesc, StaticMeshRenderer, TeamSpawn, TriggerVolume, WeaponSpawn,
|
||||
};
|
||||
|
||||
use crate::assets::{import_external_assets, EditorAssets};
|
||||
use crate::history::{clear_level_objects, snapshot_entity, EditorHistory};
|
||||
use crate::selection::SelectedEntity;
|
||||
use crate::ui::hierarchy_ops::{
|
||||
backfill_missing_editor_visibility, backfill_missing_sibling_indices,
|
||||
};
|
||||
use crate::ui::UiState;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum SceneIoRequest {
|
||||
New,
|
||||
Open,
|
||||
Save,
|
||||
SaveAs,
|
||||
ImportAssets,
|
||||
ExportSelection,
|
||||
SaveSelectionAsPrefab,
|
||||
OpenRecent(usize),
|
||||
}
|
||||
|
||||
#[derive(Resource, Debug)]
|
||||
pub struct SceneIo {
|
||||
pub active_path: Option<PathBuf>,
|
||||
pub recent_paths: Vec<PathBuf>,
|
||||
pub request: Option<SceneIoRequest>,
|
||||
pub status: String,
|
||||
pub dirty: bool,
|
||||
/// When set, the next I/O request needs unsaved-changes confirmation.
|
||||
pub pending_request: Option<SceneIoRequest>,
|
||||
}
|
||||
|
||||
impl Default for SceneIo {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
active_path: Some(PathBuf::from("assets/levels/editor_scene.scn.ron")),
|
||||
recent_paths: Vec::new(),
|
||||
request: None,
|
||||
status: "Ready".to_string(),
|
||||
dirty: false,
|
||||
pending_request: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl SceneIo {
|
||||
pub fn mark_dirty(&mut self) {
|
||||
self.dirty = true;
|
||||
}
|
||||
|
||||
pub fn mark_clean(&mut self) {
|
||||
self.dirty = false;
|
||||
}
|
||||
|
||||
pub fn active_path_label(&self) -> String {
|
||||
self.active_path
|
||||
.as_ref()
|
||||
.map(|path| path.display().to_string())
|
||||
.unwrap_or_else(|| "Unsaved scene".to_string())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Component)]
|
||||
struct LoadedSceneRoot;
|
||||
|
||||
pub struct SceneIoPlugin;
|
||||
|
||||
impl Plugin for SceneIoPlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
app.init_resource::<SceneIo>()
|
||||
.add_systems(
|
||||
Update,
|
||||
(process_scene_io_requests, update_window_title).chain(),
|
||||
)
|
||||
.add_systems(PostStartup, load_startup_scene);
|
||||
}
|
||||
}
|
||||
|
||||
fn load_startup_scene(world: &mut World) {
|
||||
let active_path = world.resource::<SceneIo>().active_path.clone();
|
||||
let default_path = PathBuf::from(
|
||||
world
|
||||
.resource::<settings::ProjectSettings>()
|
||||
.default_level
|
||||
.clone(),
|
||||
);
|
||||
let path = active_path.unwrap_or(default_path);
|
||||
|
||||
match load_level(world, &path) {
|
||||
Ok(()) => {
|
||||
world.resource_mut::<SceneIo>().active_path = Some(path.clone());
|
||||
world.resource_mut::<SceneIo>().mark_clean();
|
||||
remember_path(world, path.clone());
|
||||
world.resource_mut::<EditorHistory>().clear();
|
||||
world.resource_mut::<SceneIo>().status = format!("Loaded {}", path.display());
|
||||
}
|
||||
Err(err) => {
|
||||
world.resource_mut::<SceneIo>().status =
|
||||
format!("Startup scene load failed: {err}; using generated starter arena");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn process_scene_io_requests(world: &mut World) {
|
||||
let request = {
|
||||
let mut io = world.resource_mut::<SceneIo>();
|
||||
if let Some(pending) = io.pending_request.take() {
|
||||
pending
|
||||
} else {
|
||||
match io.request.take() {
|
||||
Some(req) if io.dirty && needs_dirty_confirm(&req) => {
|
||||
io.pending_request = Some(req);
|
||||
return;
|
||||
}
|
||||
Some(req) => req,
|
||||
None => return,
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if world.resource::<SceneIo>().dirty && needs_dirty_confirm(&request) {
|
||||
match confirm_discard_or_save() {
|
||||
DirtyConfirm::Save => {
|
||||
let save_status = save_active_or_prompt(world);
|
||||
if save_status.starts_with("Save failed") || save_status.ends_with("cancelled") {
|
||||
world.resource_mut::<SceneIo>().status = save_status;
|
||||
return;
|
||||
}
|
||||
}
|
||||
DirtyConfirm::Discard => {}
|
||||
DirtyConfirm::Cancel => {
|
||||
world.resource_mut::<SceneIo>().status = "Operation cancelled".to_string();
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let status = match request {
|
||||
SceneIoRequest::New => {
|
||||
clear_loaded_scene_roots(world);
|
||||
clear_level_objects(world);
|
||||
world.resource_mut::<SceneIo>().active_path = None;
|
||||
world.resource_mut::<SceneIo>().mark_clean();
|
||||
world.resource_mut::<EditorHistory>().clear();
|
||||
"Created a new empty level".to_string()
|
||||
}
|
||||
SceneIoRequest::Save => save_active_or_prompt(world),
|
||||
SceneIoRequest::SaveAs => save_with_dialog(world),
|
||||
SceneIoRequest::Open => open_with_dialog(world),
|
||||
SceneIoRequest::ImportAssets => import_with_dialog(world),
|
||||
SceneIoRequest::ExportSelection => export_selection_with_dialog(world),
|
||||
SceneIoRequest::SaveSelectionAsPrefab => save_selection_as_prefab(world),
|
||||
SceneIoRequest::OpenRecent(index) => open_recent(world, index),
|
||||
};
|
||||
|
||||
world.resource_mut::<SceneIo>().status = status;
|
||||
}
|
||||
|
||||
enum DirtyConfirm {
|
||||
Save,
|
||||
Discard,
|
||||
Cancel,
|
||||
}
|
||||
|
||||
fn needs_dirty_confirm(request: &SceneIoRequest) -> bool {
|
||||
matches!(
|
||||
request,
|
||||
SceneIoRequest::New | SceneIoRequest::Open | SceneIoRequest::OpenRecent(_)
|
||||
)
|
||||
}
|
||||
|
||||
fn confirm_discard_or_save() -> DirtyConfirm {
|
||||
use rfd::{MessageButtons, MessageDialog, MessageLevel};
|
||||
match MessageDialog::new()
|
||||
.set_title("Unsaved Changes")
|
||||
.set_description("The scene has unsaved changes. Save before continuing?")
|
||||
.set_level(MessageLevel::Warning)
|
||||
.set_buttons(MessageButtons::YesNoCancel)
|
||||
.show()
|
||||
{
|
||||
rfd::MessageDialogResult::Yes => DirtyConfirm::Save,
|
||||
rfd::MessageDialogResult::No => DirtyConfirm::Discard,
|
||||
_ => DirtyConfirm::Cancel,
|
||||
}
|
||||
}
|
||||
|
||||
fn open_recent(world: &mut World, index: usize) -> String {
|
||||
let path = world.resource::<SceneIo>().recent_paths.get(index).cloned();
|
||||
let Some(path) = path else {
|
||||
return "Recent scene not found".to_string();
|
||||
};
|
||||
match load_level(world, &path) {
|
||||
Ok(()) => {
|
||||
world.resource_mut::<SceneIo>().active_path = Some(path.clone());
|
||||
world.resource_mut::<SceneIo>().mark_clean();
|
||||
remember_path(world, path.clone());
|
||||
world.resource_mut::<EditorHistory>().clear();
|
||||
format!("Loading {}", path.display())
|
||||
}
|
||||
Err(err) => format!("Open failed: {err}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn save_selection_as_prefab(world: &mut World) -> String {
|
||||
let selection: Vec<Entity> = world
|
||||
.get_resource::<UiState>()
|
||||
.map(|ui| {
|
||||
ui.selected_entities
|
||||
.iter()
|
||||
.filter(|entity| {
|
||||
world
|
||||
.get_entity(*entity)
|
||||
.is_ok_and(|e| e.contains::<LevelObject>())
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
if selection.is_empty() {
|
||||
return "Select level objects to save as prefab".to_string();
|
||||
}
|
||||
|
||||
let Some(path) = rfd::FileDialog::new()
|
||||
.set_directory("assets/prefabs")
|
||||
.add_filter("Bevy prefab", &["scn.ron", "ron"])
|
||||
.set_file_name("prefab.scn.ron")
|
||||
.save_file()
|
||||
else {
|
||||
return "Save prefab cancelled".to_string();
|
||||
};
|
||||
|
||||
match save_entities(world, &path, selection) {
|
||||
Ok(count) => {
|
||||
world.resource_mut::<EditorAssets>().refresh();
|
||||
format!(
|
||||
"Saved prefab with {count} root entity(s) to {}",
|
||||
path.display()
|
||||
)
|
||||
}
|
||||
Err(err) => format!("Save prefab failed: {err}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Save helper for play-mode and other cross-module callers.
|
||||
pub fn save_active_or_prompt_world(world: &mut World) -> String {
|
||||
save_active_or_prompt(world)
|
||||
}
|
||||
|
||||
fn save_active_or_prompt(world: &mut World) -> String {
|
||||
let path = world.resource::<SceneIo>().active_path.clone();
|
||||
match path {
|
||||
Some(path) => match save_level(world, &path) {
|
||||
Ok(count) => {
|
||||
world.resource_mut::<SceneIo>().mark_clean();
|
||||
remember_path(world, path.clone());
|
||||
format!("Saved {count} level entities to {}", path.display())
|
||||
}
|
||||
Err(err) => format!("Save failed: {err}"),
|
||||
},
|
||||
None => save_with_dialog(world),
|
||||
}
|
||||
}
|
||||
|
||||
fn save_with_dialog(world: &mut World) -> String {
|
||||
let Some(path) = rfd::FileDialog::new()
|
||||
.set_directory("assets/levels")
|
||||
.add_filter("Bevy scene", &["scn.ron", "ron"])
|
||||
.set_file_name("editor_scene.scn.ron")
|
||||
.save_file()
|
||||
else {
|
||||
return "Save cancelled".to_string();
|
||||
};
|
||||
|
||||
match save_level(world, &path) {
|
||||
Ok(count) => {
|
||||
world.resource_mut::<SceneIo>().active_path = Some(path.clone());
|
||||
world.resource_mut::<SceneIo>().mark_clean();
|
||||
remember_path(world, path.clone());
|
||||
format!("Saved {count} level entities to {}", path.display())
|
||||
}
|
||||
Err(err) => format!("Save failed: {err}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn open_with_dialog(world: &mut World) -> String {
|
||||
let Some(path) = rfd::FileDialog::new()
|
||||
.set_directory("assets/levels")
|
||||
.add_filter("Bevy scene", &["scn.ron", "ron"])
|
||||
.pick_file()
|
||||
else {
|
||||
return "Open cancelled".to_string();
|
||||
};
|
||||
|
||||
match load_level(world, &path) {
|
||||
Ok(()) => {
|
||||
world.resource_mut::<SceneIo>().active_path = Some(path.clone());
|
||||
world.resource_mut::<SceneIo>().mark_clean();
|
||||
remember_path(world, path.clone());
|
||||
world.resource_mut::<EditorHistory>().clear();
|
||||
format!("Loading {}", path.display())
|
||||
}
|
||||
Err(err) => format!("Open failed: {err}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn import_with_dialog(world: &mut World) -> String {
|
||||
let Some(paths) = rfd::FileDialog::new()
|
||||
.add_filter(
|
||||
"Editor assets",
|
||||
&["gltf", "glb", "fbx", "png", "jpg", "jpeg", "webp", "ktx2"],
|
||||
)
|
||||
.pick_files()
|
||||
else {
|
||||
return "Import cancelled".to_string();
|
||||
};
|
||||
|
||||
match import_external_assets(&paths) {
|
||||
Ok(count) => {
|
||||
world.resource_mut::<EditorAssets>().refresh();
|
||||
format!("Imported {count} asset(s)")
|
||||
}
|
||||
Err(err) => format!("Import failed: {err}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn export_selection_with_dialog(world: &mut World) -> String {
|
||||
let Some(entity) = world.resource::<SelectedEntity>().0 else {
|
||||
return "Nothing selected to export".to_string();
|
||||
};
|
||||
if snapshot_entity(world, entity).is_none() {
|
||||
return "Selected entity is not an authored level object".to_string();
|
||||
}
|
||||
|
||||
let Some(path) = rfd::FileDialog::new()
|
||||
.set_directory("assets/levels")
|
||||
.add_filter("Bevy prefab", &["scn.ron", "ron"])
|
||||
.set_file_name("selection.scn.ron")
|
||||
.save_file()
|
||||
else {
|
||||
return "Export cancelled".to_string();
|
||||
};
|
||||
|
||||
match save_entities(world, &path, vec![entity]) {
|
||||
Ok(count) => format!("Exported {count} selected entity to {}", path.display()),
|
||||
Err(err) => format!("Export failed: {err}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn clear_loaded_scene_roots(world: &mut World) {
|
||||
let mut query = world.query_filtered::<Entity, With<LoadedSceneRoot>>();
|
||||
let entities: Vec<Entity> = query.iter(world).collect();
|
||||
for entity in entities {
|
||||
if let Ok(entity_mut) = world.get_entity_mut(entity) {
|
||||
entity_mut.despawn();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn save_level(world: &mut World, path: &Path) -> Result<usize, String> {
|
||||
let mut query = world
|
||||
.try_query_filtered::<Entity, With<LevelObject>>()
|
||||
.ok_or_else(|| "could not create LevelObject query".to_string())?;
|
||||
let entities: Vec<Entity> = query.iter(world).collect();
|
||||
save_entities(world, path, entities)
|
||||
}
|
||||
|
||||
fn format_actor_validation(err: ActorValidationError) -> String {
|
||||
match err {
|
||||
ActorValidationError::MissingActorKind => {
|
||||
"Save failed: level object missing ActorKind (re-open scene to migrate)".into()
|
||||
}
|
||||
ActorValidationError::MissingTransform => {
|
||||
"Save failed: level object missing Transform".into()
|
||||
}
|
||||
ActorValidationError::StaticMeshMissingPrimitive => {
|
||||
"Save failed: StaticMesh actor requires Primitive or StaticMeshRenderer with a mesh slot"
|
||||
.into()
|
||||
}
|
||||
ActorValidationError::StaticMeshHasLight => {
|
||||
"Save failed: StaticMesh actor cannot have LightDesc".into()
|
||||
}
|
||||
ActorValidationError::StaticMeshHasModelRef => {
|
||||
"Save failed: StaticMesh actor cannot have ModelRef".into()
|
||||
}
|
||||
ActorValidationError::ImportedModelMissingModelRef => {
|
||||
"Save failed: ImportedModel actor requires ModelRef".into()
|
||||
}
|
||||
ActorValidationError::ImportedModelHasPrimitive => {
|
||||
"Save failed: ImportedModel actor cannot have Primitive".into()
|
||||
}
|
||||
ActorValidationError::ImportedModelHasStaticMeshRenderer => {
|
||||
"Save failed: ImportedModel actor cannot have StaticMeshRenderer".into()
|
||||
}
|
||||
ActorValidationError::LightMissingLightDesc => {
|
||||
"Save failed: Light actor requires LightDesc".into()
|
||||
}
|
||||
ActorValidationError::LightHasPrimitive => {
|
||||
"Save failed: Light actor cannot have Primitive".into()
|
||||
}
|
||||
ActorValidationError::LightHasModelRef => {
|
||||
"Save failed: Light actor cannot have ModelRef".into()
|
||||
}
|
||||
ActorValidationError::LightHasStaticMeshRenderer => {
|
||||
"Save failed: Light actor cannot have StaticMeshRenderer".into()
|
||||
}
|
||||
ActorValidationError::PostProcessVolumeMissingDesc => {
|
||||
"Save failed: PostProcessVolume actor requires PostProcessVolumeDesc".into()
|
||||
}
|
||||
ActorValidationError::PostProcessVolumeInvalidHalfExtents => {
|
||||
"Save failed: post-process volume half_extents must be positive".into()
|
||||
}
|
||||
ActorValidationError::PostProcessVolumeInvalidBlendDistance => {
|
||||
"Save failed: post-process volume blend_distance must be non-negative".into()
|
||||
}
|
||||
ActorValidationError::PostProcessVolumeInvalidOverrideScalar => {
|
||||
"Save failed: post-process volume override contains invalid scalar".into()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn save_entities(world: &mut World, path: &Path, entities: Vec<Entity>) -> Result<usize, String> {
|
||||
let count = entities.len();
|
||||
|
||||
for entity in &entities {
|
||||
let entity_ref = world.entity(*entity);
|
||||
if let Err(err) = validate_actor(entity_ref) {
|
||||
return Err(format_actor_validation(err));
|
||||
}
|
||||
}
|
||||
|
||||
for entity in &entities {
|
||||
if let Ok(mut entity_mut) = world.get_entity_mut(*entity) {
|
||||
strip_hydrated_entity(&mut entity_mut);
|
||||
}
|
||||
}
|
||||
|
||||
let scene = DynamicSceneBuilder::from_world(world)
|
||||
.deny_all()
|
||||
.allow_component::<Name>()
|
||||
.allow_component::<Transform>()
|
||||
.allow_component::<ChildOf>()
|
||||
.allow_component::<LevelObject>()
|
||||
.allow_component::<ActorId>()
|
||||
.allow_component::<ActorName>()
|
||||
.allow_component::<ActorKind>()
|
||||
.allow_component::<InspectorOrder>()
|
||||
.allow_component::<Primitive>()
|
||||
.allow_component::<StaticMeshRenderer>()
|
||||
.allow_component::<MaterialDesc>()
|
||||
.allow_component::<MaterialOverride>()
|
||||
.allow_component::<RigidBodyDesc>()
|
||||
.allow_component::<ColliderDesc>()
|
||||
.allow_component::<PhysicsBody>()
|
||||
.allow_component::<LightDesc>()
|
||||
.allow_component::<PlayerSpawn>()
|
||||
.allow_component::<ModelRef>()
|
||||
.allow_component::<PrefabRef>()
|
||||
.allow_component::<PrefabInstance>()
|
||||
.allow_component::<WeaponSpawn>()
|
||||
.allow_component::<TriggerVolume>()
|
||||
.allow_component::<PostProcessVolumeDesc>()
|
||||
.allow_component::<TeamSpawn>()
|
||||
.allow_component::<ObjectiveMarker>()
|
||||
.allow_component::<HierarchySiblingIndex>()
|
||||
.allow_component::<EditorVisibility>()
|
||||
.extract_entities(entities.into_iter())
|
||||
.remove_empty_entities()
|
||||
.build();
|
||||
|
||||
let ron = {
|
||||
let registry = world.resource::<AppTypeRegistry>().read();
|
||||
scene
|
||||
.serialize(®istry)
|
||||
.map_err(|err| format!("could not serialize scene: {err}"))?
|
||||
};
|
||||
|
||||
if let Some(parent) = path.parent() {
|
||||
std::fs::create_dir_all(parent)
|
||||
.map_err(|err| format!("could not create {}: {err}", parent.display()))?;
|
||||
}
|
||||
let stamped = stamp_schema_version(&ron)?;
|
||||
std::fs::write(path, stamped)
|
||||
.map_err(|err| format!("could not write {}: {err}", path.display()))?;
|
||||
finalize_scene_load(world);
|
||||
|
||||
Ok(count)
|
||||
}
|
||||
|
||||
fn load_level(world: &mut World, path: &Path) -> Result<(), String> {
|
||||
if !path.exists() {
|
||||
return Err(format!("{} does not exist yet", path.display()));
|
||||
}
|
||||
|
||||
let text = std::fs::read_to_string(path)
|
||||
.map_err(|err| format!("could not read {}: {err}", path.display()))?;
|
||||
validate_level_text(&text)?;
|
||||
let normalized = migrate_scene_text(&text)?;
|
||||
let bevy_ron = strip_schema_version(&normalized)?;
|
||||
|
||||
clear_loaded_scene_roots(world);
|
||||
clear_level_objects(world);
|
||||
|
||||
let dynamic_scene: DynamicScene = {
|
||||
let registry = world.resource::<AppTypeRegistry>().read();
|
||||
let scene_deserializer = SceneDeserializer {
|
||||
type_registry: ®istry,
|
||||
};
|
||||
let mut deserializer =
|
||||
ron::de::Deserializer::from_str(&bevy_ron).map_err(|err| err.to_string())?;
|
||||
scene_deserializer
|
||||
.deserialize(&mut deserializer)
|
||||
.map_err(|err| format!("could not deserialize scene: {err}"))?
|
||||
};
|
||||
|
||||
dynamic_scene
|
||||
.write_to_world(world, &mut EntityHashMap::default())
|
||||
.map_err(|err| format!("could not spawn scene: {err}"))?;
|
||||
|
||||
backfill_missing_actor_kinds(world);
|
||||
backfill_missing_sibling_indices(world);
|
||||
backfill_missing_editor_visibility(world);
|
||||
finalize_scene_load(world);
|
||||
|
||||
if world.contains_resource::<crate::scene_schema::SceneSchemaState>() {
|
||||
world
|
||||
.resource_mut::<crate::scene_schema::SceneSchemaState>()
|
||||
.last_validated = scene::CURRENT_SCENE_SCHEMA_VERSION;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn finalize_scene_load(world: &mut World) {
|
||||
flush_level_object_hydration(world);
|
||||
|
||||
let rendering = world
|
||||
.resource::<settings::ProjectSettings>()
|
||||
.rendering
|
||||
.clone();
|
||||
world.insert_resource(GlobalAmbientLight {
|
||||
color: Color::srgb(
|
||||
rendering.ambient_color[0],
|
||||
rendering.ambient_color[1],
|
||||
rendering.ambient_color[2],
|
||||
),
|
||||
brightness: rendering.ambient_brightness,
|
||||
..default()
|
||||
});
|
||||
|
||||
let mut state: SystemState<(
|
||||
Res<settings::ProjectSettings>,
|
||||
Query<(&LightDesc, Option<&InspectorOrder>), With<LevelObject>>,
|
||||
Query<(&mut DirectionalLight, &mut Visibility), With<shared::ProjectSun>>,
|
||||
)> = SystemState::new(world);
|
||||
|
||||
{
|
||||
let (settings, scene_suns, project_suns) = state.get_mut(world);
|
||||
game_hot::sync_project_sun_from_settings(settings, scene_suns, project_suns);
|
||||
}
|
||||
state.apply(world);
|
||||
}
|
||||
|
||||
fn backfill_missing_actor_kinds(world: &mut World) {
|
||||
let mut query = world.query_filtered::<Entity, With<LevelObject>>();
|
||||
let entities: Vec<Entity> = query.iter(world).collect();
|
||||
for entity in entities {
|
||||
let Ok(entity_ref) = world.get_entity(entity) else {
|
||||
continue;
|
||||
};
|
||||
if entity_ref.get::<ActorKind>().is_some() {
|
||||
continue;
|
||||
}
|
||||
if let Some(kind) = infer_actor_kind(entity_ref) {
|
||||
world.entity_mut(entity).insert(kind);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn remember_path(world: &mut World, path: PathBuf) {
|
||||
let mut io = world.resource_mut::<SceneIo>();
|
||||
io.recent_paths.retain(|recent| recent != &path);
|
||||
io.recent_paths.insert(0, path.clone());
|
||||
io.recent_paths.truncate(8);
|
||||
|
||||
if world.contains_resource::<crate::project_io::UserPreferences>() {
|
||||
let path_label = path.display().to_string();
|
||||
let mut prefs = world.resource_mut::<crate::project_io::UserPreferences>();
|
||||
crate::project_io::push_recent(&mut prefs.recent_levels, path_label, 8);
|
||||
if let Err(error) = crate::project_io::write_user_preferences(&prefs) {
|
||||
warn!("Failed to save editor preferences: {error}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn update_window_title(
|
||||
io: Res<SceneIo>,
|
||||
workspace: Res<crate::project_io::ProjectWorkspace>,
|
||||
settings: Res<settings::ProjectSettings>,
|
||||
settings_io: Res<settings::ProjectSettingsIo>,
|
||||
mut window: Single<&mut Window, With<PrimaryWindow>>,
|
||||
) {
|
||||
if !io.is_changed()
|
||||
&& !workspace.is_changed()
|
||||
&& !settings.is_changed()
|
||||
&& !settings_io.is_changed()
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
window.title = crate::project_io::window_title(&io, &workspace, &settings);
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
//! Scene format versioning plugin (editor); logic lives in the `scene` crate.
|
||||
|
||||
use bevy::prelude::*;
|
||||
pub use scene::{
|
||||
migrate_scene_text, stamp_schema_version, strip_schema_version, validate_level_file,
|
||||
validate_level_text, SceneSchemaHeader, CURRENT_SCENE_SCHEMA_VERSION,
|
||||
};
|
||||
|
||||
pub struct SceneSchemaPlugin;
|
||||
|
||||
impl Plugin for SceneSchemaPlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
app.init_resource::<SceneSchemaState>();
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Resource, Default)]
|
||||
pub struct SceneSchemaState {
|
||||
pub last_validated: u32,
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
//! Primary editor viewport render-to-texture target and editor camera binding.
|
||||
|
||||
use bevy::camera::RenderTarget;
|
||||
use bevy::prelude::*;
|
||||
use bevy::window::{PrimaryWindow, WindowRef};
|
||||
|
||||
use crate::camera::EditorCamera;
|
||||
use crate::render_target::{ensure_hdr_panel_target, ViewportRenderTarget, ViewportTarget};
|
||||
use crate::state::{EditorMode, PlayPossession};
|
||||
use crate::ui::UiState;
|
||||
use crate::viewport::panel_physical_size;
|
||||
|
||||
pub struct SceneViewPlugin;
|
||||
|
||||
impl Plugin for SceneViewPlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
app.init_resource::<ViewportRenderTarget>().add_systems(
|
||||
PostUpdate,
|
||||
(
|
||||
ensure_viewport_render_target,
|
||||
sync_editor_camera_viewport_target,
|
||||
)
|
||||
.chain()
|
||||
.after(crate::ui::show_ui_system),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn ensure_viewport_render_target(
|
||||
ui_state: Res<UiState>,
|
||||
window: Single<&Window, With<PrimaryWindow>>,
|
||||
mut images: ResMut<Assets<Image>>,
|
||||
mut target: ResMut<ViewportRenderTarget>,
|
||||
mut last_size: Local<Option<UVec2>>,
|
||||
) {
|
||||
let Some(physical_size) = panel_physical_size(&window, ui_state.viewport_rect) else {
|
||||
return;
|
||||
};
|
||||
|
||||
if let Some(handle) = ensure_hdr_panel_target(physical_size, &mut last_size, &mut images) {
|
||||
target.0 = Some(ViewportTarget { image: handle });
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn sync_editor_camera_viewport_target(
|
||||
mode: Res<State<EditorMode>>,
|
||||
possession: Res<PlayPossession>,
|
||||
target: Res<ViewportRenderTarget>,
|
||||
mut cameras: Query<(Entity, &mut Camera), With<EditorCamera>>,
|
||||
mut commands: Commands,
|
||||
) {
|
||||
let scene_active = matches!(*mode.get(), EditorMode::Editing)
|
||||
|| (*mode.get() == EditorMode::Playing && *possession == PlayPossession::Ejected);
|
||||
|
||||
for (entity, mut camera) in &mut cameras {
|
||||
if scene_active {
|
||||
let Some(viewport_target) = target.0.as_ref() else {
|
||||
camera.viewport = None;
|
||||
camera.is_active = false;
|
||||
continue;
|
||||
};
|
||||
// Render the full offscreen target. A panel-sized
|
||||
// viewport on `RenderTarget::Image` can exceed the texture for a frame after
|
||||
// resize (wgpu: scissor rect not contained in render target).
|
||||
camera.viewport = None;
|
||||
camera.is_active = true;
|
||||
commands
|
||||
.entity(entity)
|
||||
.insert(RenderTarget::Image(viewport_target.image.clone().into()));
|
||||
} else {
|
||||
camera.viewport = None;
|
||||
camera.is_active = false;
|
||||
commands
|
||||
.entity(entity)
|
||||
.insert(RenderTarget::Window(WindowRef::Primary));
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user