bevy_yoleck/lib.rs
1//! # Your Own Level Editor Creation Kit
2//!
3//! Yoleck is a crate for having a game built with the Bevy game engine act as its own level
4//! editor.
5//!
6//! Yoleck uses Plain Old Rust Structs to store the data, and uses Serde to store them in files.
7//! The user code defines _populate systems_ for creating Bevy entities (populating their
8//! components) from these structs and _edit systems_ to edit these structs with egui.
9//!
10//! The synchronization between the structs and the files is bidirectional, and so is the
11//! synchronization between the structs and the egui widgets, but the synchronization from the
12//! structs to the entities is unidirectional - changes in the entities are not reflected in the
13//! structs:
14//!
15//! ```none
16//! ┌────────┐ Populate ┏━━━━━━━━━┓ Edit ┌───────┐
17//! │Bevy │ Systems ┃Yoleck ┃ Systems │egui │
18//! │Entities│◄────────────┃Component┃◄═══════════►│Widgets│
19//! └────────┘ ┃Structs ┃ └───────┘
20//! ┗━━━━━━━━━┛
21//! ▲
22//! ║
23//! ║ Serde
24//! ║
25//! ▼
26//! ┌─────┐
27//! │.yol │
28//! │Files│
29//! └─────┘
30//! ```
31//!
32//! To support integrate Yoleck, a game needs to:
33//!
34//! * Define the component structs, and make sure they implement:
35//! ```text
36//! #[derive(Default, Clone, PartialEq, Component, Serialize, Deserialize, YoleckComponent)]
37//! ```
38//! * For each entity type that can be created in the level editor, use
39//! [`add_yoleck_entity_type`](YoleckExtForApp::add_yoleck_entity_type) to add a
40//! [`YoleckEntityType`]. Use [`YoleckEntityType::with`] to register the
41//! [`YoleckComponent`](crate::specs_registration::YoleckComponent)s for that entity type.
42//! * Register edit systems with
43//! [`add_yoleck_edit_system`](YoleckExtForApp::add_yoleck_edit_system).
44//! * Register populate systems on [`YoleckSchedule::Populate`]
45//! * If the application starts in editor mode:
46//! * Add the `EguiPlugin` plugin.
47//! * Add the [`YoleckPluginForEditor`] plugin.
48//! * Use [`YoleckSyncWithEditorState`](crate::editor::YoleckSyncWithEditorState) to synchronize
49//! the game's state with the [`YoleckEditorState`] (optional but highly recommended)
50//! * If the application starts in game mode:
51//! * Add the [`YoleckPluginForGame`] plugin.
52//! * **DO NOT** add the `EguiPlugin` unless you need it yourself. Since Yoleck will not be using
53//! it, registering the plugin may cause issues.
54//! * Use the [`YoleckLevelIndex`] asset to determine the list of available levels (optional)
55//! * Spawn an entity with the [`YoleckLoadLevel`](entity_management::YoleckLoadLevel) component
56//! to load the level. Note that the level can be unloaded by despawning that entity or by
57//! removing the [`YoleckKeepLevel`] component that will automatically be added to it.
58//!
59//! To support picking and moving entities in the viewport with the mouse, check out the
60//! [`vpeol_2d`] and [`vpeol_3d`] modules. After adding the appropriate feature flag
61//! (`vpeol_2d`/`vpeol_3d`), import their types from
62//! [`bevy_yoleck::vpeol::prelude::*`](crate::vpeol::prelude).
63//!
64//! # Example
65//!
66//! ```no_run
67//! use bevy::prelude::*;
68//! use bevy_yoleck::bevy_egui::EguiPlugin;
69//! use bevy_yoleck::prelude::*;
70//! use serde::{Deserialize, Serialize};
71//! # use bevy_yoleck::egui;
72//!
73//! fn main() {
74//! let is_editor = std::env::args().any(|arg| arg == "--editor");
75//!
76//! let mut app = App::new();
77//! app.add_plugins(DefaultPlugins);
78//! if is_editor {
79//! // Doesn't matter in this example, but a proper game would have systems that can work
80//! // on the entity in `GameState::Game`, so while the level is edited we want to be in
81//! // `GameState::Editor` - which can be treated as a pause state. When the editor wants
82//! // to playtest the level we want to move to `GameState::Game` so that they can play it.
83//! app.add_plugins(EguiPlugin::default());
84//! app.add_plugins(YoleckSyncWithEditorState {
85//! when_editor: GameState::Editor,
86//! when_game: GameState::Game,
87//! });
88//! app.add_plugins(YoleckPluginForEditor);
89//! } else {
90//! app.add_plugins(YoleckPluginForGame);
91//! app.init_state::<GameState>();
92//! // In editor mode Yoleck takes care of level loading. In game mode the game needs to
93//! // tell yoleck which levels to load and when.
94//! app.add_systems(Update, load_first_level.run_if(in_state(GameState::Loading)));
95//! }
96//! app.add_systems(Startup, setup_camera);
97//!
98//! app.add_yoleck_entity_type({
99//! YoleckEntityType::new("Rectangle")
100//! .with::<Rectangle>()
101//! .apply_scene_on_init(|| bsn! {
102//! // Place here a Bevy scene with components that do not need to know the values
103//! // of the Yoleck components. Components that depend on that value should go in
104//! // populate systems.
105//! })
106//! });
107//! app.add_yoleck_edit_system(edit_rectangle);
108//! app.add_systems(YoleckSchedule::Populate, populate_rectangle);
109//!
110//! app.run();
111//! }
112//!
113//! #[derive(States, Default, Debug, Clone, PartialEq, Eq, Hash)]
114//! enum GameState {
115//! #[default]
116//! Loading,
117//! Game,
118//! Editor,
119//! }
120//!
121//! fn setup_camera(mut commands: Commands) {
122//! commands.spawn(Camera2d::default());
123//! }
124//!
125//! #[derive(Clone, PartialEq, Serialize, Deserialize, Component, YoleckComponent)]
126//! struct Rectangle {
127//! width: f32,
128//! height: f32,
129//! }
130//!
131//! impl Default for Rectangle {
132//! fn default() -> Self {
133//! Self {
134//! width: 50.0,
135//! height: 50.0,
136//! }
137//! }
138//! }
139//!
140//! fn populate_rectangle(mut populate: YoleckPopulate<&Rectangle>) {
141//! populate.populate(|_ctx, mut cmd, rectangle| {
142//! cmd.insert(Sprite {
143//! color: bevy::color::palettes::css::RED.into(),
144//! custom_size: Some(Vec2::new(rectangle.width, rectangle.height)),
145//! ..Default::default()
146//! });
147//! });
148//! }
149//!
150//! fn edit_rectangle(mut ui: ResMut<YoleckUi>, mut edit: YoleckEdit<&mut Rectangle>) {
151//! let Ok(mut rectangle) = edit.single_mut() else { return };
152//! ui.add(egui::Slider::new(&mut rectangle.width, 50.0..=500.0).prefix("Width: "));
153//! ui.add(egui::Slider::new(&mut rectangle.height, 50.0..=500.0).prefix("Height: "));
154//! }
155//!
156//! fn load_first_level(
157//! mut level_index_handle: Local<Option<Handle<YoleckLevelIndex>>>,
158//! asset_server: Res<AssetServer>,
159//! level_index_assets: Res<Assets<YoleckLevelIndex>>,
160//! mut commands: Commands,
161//! mut game_state: ResMut<NextState<GameState>>,
162//! ) {
163//! // Keep the handle in local resource, so that Bevy will not unload the level index asset
164//! // between frames.
165//! let level_index_handle = level_index_handle
166//! .get_or_insert_with(|| asset_server.load("levels/index.yoli"))
167//! .clone();
168//! let Some(level_index) = level_index_assets.get(&level_index_handle) else {
169//! // During the first invocation of this system, the level index asset is not going to be
170//! // loaded just yet. Since this system is going to run on every frame during the Loading
171//! // state, it just has to keep trying until it starts in a frame where it is loaded.
172//! return;
173//! };
174//! // A proper game would have a proper level progression system, but here we are just
175//! // taking the first level and loading it.
176//! let level_handle: Handle<YoleckRawLevel> =
177//! asset_server.load(&format!("levels/{}", level_index[0].filename));
178//! commands.spawn(YoleckLoadLevel(level_handle));
179//! game_state.set(GameState::Game);
180//! }
181//! ```
182
183pub mod auto_edit;
184mod console;
185mod editing;
186mod editor;
187mod editor_panels;
188mod editor_window;
189mod entity_management;
190pub mod entity_ref;
191mod entity_upgrading;
192mod entity_uuid;
193mod errors;
194pub mod exclusive_systems;
195pub mod knobs;
196mod level_files_manager;
197pub mod level_files_upgrading;
198mod level_index;
199mod picking_helpers;
200mod populating;
201mod specs_registration;
202mod util;
203#[cfg(feature = "vpeol")]
204pub mod vpeol;
205#[cfg(feature = "vpeol_2d")]
206pub mod vpeol_2d;
207#[cfg(feature = "vpeol_3d")]
208pub mod vpeol_3d;
209
210use std::any::{Any, TypeId};
211use std::path::Path;
212use std::sync::Arc;
213
214use bevy::ecs::schedule::ScheduleLabel;
215use bevy::ecs::system::{EntityCommands, SystemId};
216use bevy::platform::collections::HashMap;
217use bevy::prelude::*;
218use bevy_egui::EguiPrimaryContextPass;
219
220pub mod prelude {
221 pub use crate::auto_edit::{YoleckAutoEdit, YoleckAutoEditExt};
222 pub use crate::editing::{YoleckEdit, YoleckUi};
223 pub use crate::editor::{YoleckEditorState, YoleckPassedData, YoleckSyncWithEditorState};
224 pub use crate::entity_management::{YoleckKeepLevel, YoleckLoadLevel, YoleckRawLevel};
225 pub use crate::entity_ref::{YoleckEntityRef, YoleckEntityRefAccessor};
226 pub use crate::entity_upgrading::YoleckEntityUpgradingPlugin;
227 pub use crate::entity_uuid::{YoleckEntityUuid, YoleckUuidRegistry};
228 pub use crate::knobs::YoleckKnobs;
229 pub use crate::level_index::{YoleckLevelIndex, YoleckLevelIndexEntry};
230 pub use crate::populating::{YoleckMarking, YoleckPopulate};
231 pub use crate::specs_registration::{YoleckComponent, YoleckEntityType};
232 pub use crate::{
233 YoleckBelongsToLevel, YoleckExtForApp, YoleckLevelInEditor, YoleckLevelInPlaytest,
234 YoleckLevelJustLoaded, YoleckPluginForEditor, YoleckPluginForGame, YoleckSchedule,
235 };
236 pub use bevy_yoleck_macros::{YoleckAutoEdit, YoleckComponent};
237}
238
239pub use self::console::{YoleckConsoleLogHistory, YoleckConsoleState, console_layer_factory};
240pub use self::editing::YoleckEditMarker;
241pub use self::editor::YoleckDirective;
242pub use self::editor::YoleckEditorEvent;
243use self::editor::YoleckEditorState;
244pub use self::editor_panels::{
245 YoleckEditorBottomPanelSections, YoleckEditorBottomPanelTab, YoleckEditorLeftPanelSections,
246 YoleckEditorRightPanelSections, YoleckEditorTopPanelSections, YoleckPanelUi,
247};
248pub use self::editor_window::YoleckEditorViewportRect;
249pub use self::picking_helpers::*;
250
251use self::entity_management::{EntitiesToPopulate, YoleckRawLevel};
252use self::entity_upgrading::YoleckEntityUpgrading;
253use self::exclusive_systems::YoleckExclusiveSystemsPlugin;
254use self::knobs::YoleckKnobsCache;
255pub use self::level_files_manager::YoleckEditorLevelsDirectoryPath;
256pub use self::level_index::YoleckEditableLevels;
257use self::level_index::YoleckLevelIndex;
258pub use self::populating::{YoleckPopulateContext, YoleckSystemMarker};
259use self::prelude::{YoleckKeepLevel, YoleckUuidRegistry};
260use self::specs_registration::{YoleckComponentHandler, YoleckEntityType};
261use self::util::EditSpecificResources;
262pub use bevy_egui;
263pub use bevy_egui::egui;
264
265struct YoleckPluginBase;
266pub struct YoleckPluginForGame;
267pub struct YoleckPluginForEditor;
268
269#[derive(Debug, Clone, PartialEq, Eq, Hash, SystemSet)]
270enum YoleckSystems {
271 ProcessRawEntities,
272 RunPopulateSchedule,
273}
274
275#[derive(Debug, Clone, PartialEq, Eq, Hash, SystemSet)]
276pub(crate) struct YoleckRunEditSystems;
277
278impl Plugin for YoleckPluginBase {
279 fn build(&self, app: &mut App) {
280 app.init_resource::<YoleckEntityConstructionSpecs>();
281 app.insert_resource(YoleckUuidRegistry(Default::default()));
282 app.register_asset_loader(entity_management::YoleckLevelAssetLoader);
283 app.init_asset::<YoleckRawLevel>();
284 app.register_asset_loader(level_index::YoleckLevelIndexLoader);
285 app.init_asset::<YoleckLevelIndex>();
286
287 app.configure_sets(
288 Update,
289 (
290 YoleckSystems::ProcessRawEntities,
291 YoleckSystems::RunPopulateSchedule,
292 )
293 .chain(),
294 );
295
296 app.add_systems(
297 Update,
298 (
299 entity_management::yoleck_process_raw_entries,
300 ApplyDeferred,
301 (
302 entity_management::yoleck_run_post_load_resolutions_schedule,
303 entity_management::yoleck_run_level_loaded_schedule.run_if(
304 |freshly_loaded_level_entities: Query<
305 (),
306 (With<YoleckLevelJustLoaded>, Without<YoleckLevelInEditor>),
307 >| { !freshly_loaded_level_entities.is_empty() },
308 ),
309 entity_management::yoleck_remove_just_loaded_marker_from_levels,
310 ApplyDeferred,
311 )
312 .chain()
313 .run_if(
314 |freshly_loaded_level_entities: Query<(), With<YoleckLevelJustLoaded>>| {
315 !freshly_loaded_level_entities.is_empty()
316 },
317 ),
318 )
319 .chain()
320 .in_set(YoleckSystems::ProcessRawEntities),
321 );
322 app.insert_resource(EntitiesToPopulate(Default::default()));
323 app.add_systems(
324 Update,
325 (
326 entity_management::yoleck_prepare_populate_schedule,
327 entity_management::yoleck_run_populate_schedule.run_if(
328 |entities_to_populate: Res<EntitiesToPopulate>| {
329 !entities_to_populate.0.is_empty()
330 },
331 ),
332 )
333 .chain()
334 .in_set(YoleckSystems::RunPopulateSchedule),
335 );
336 app.add_systems(
337 Update,
338 ((
339 entity_management::process_unloading_command,
340 entity_management::process_loading_command,
341 ApplyDeferred,
342 )
343 .chain()
344 .before(YoleckSystems::ProcessRawEntities),),
345 );
346 app.add_schedule(Schedule::new(YoleckSchedule::Populate));
347 app.add_schedule(Schedule::new(YoleckInternalSchedule::PostLoadResolutions));
348 app.add_schedule(Schedule::new(YoleckSchedule::LevelLoaded));
349 app.add_schedule(Schedule::new(YoleckSchedule::OverrideCommonComponents));
350 }
351}
352
353impl Plugin for YoleckPluginForGame {
354 fn build(&self, app: &mut App) {
355 app.init_state::<YoleckEditorState>();
356 app.add_systems(
357 Startup,
358 |mut state: ResMut<NextState<YoleckEditorState>>| {
359 state.set(YoleckEditorState::GameActive);
360 },
361 );
362 app.add_plugins(YoleckPluginBase);
363 }
364}
365
366impl Plugin for YoleckPluginForEditor {
367 fn build(&self, app: &mut App) {
368 app.init_state::<YoleckEditorState>();
369 app.add_message::<YoleckEditorEvent>();
370 app.add_plugins(YoleckPluginBase);
371 app.add_plugins(YoleckExclusiveSystemsPlugin);
372 app.init_resource::<YoleckEditSystems>();
373 app.insert_resource(YoleckKnobsCache::default());
374 let level_being_edited = app
375 .world_mut()
376 .spawn((YoleckLevelInEditor, YoleckKeepLevel))
377 .id();
378 app.insert_resource(YoleckState {
379 level_being_edited,
380 level_needs_saving: false,
381 });
382 app.insert_resource(YoleckEditorLevelsDirectoryPath(
383 Path::new(".").join("assets").join("levels"),
384 ));
385 app.init_resource::<YoleckEditorLeftPanelSections>();
386 app.init_resource::<YoleckEditorRightPanelSections>();
387 app.init_resource::<YoleckEditorTopPanelSections>();
388 app.init_resource::<YoleckEditorBottomPanelSections>();
389 app.init_resource::<YoleckEditorViewportRect>();
390 app.init_resource::<YoleckConsoleState>();
391 app.init_resource::<YoleckConsoleLogHistory>();
392 app.init_resource::<YoleckPlaytestLevel>();
393 app.insert_resource(EditSpecificResources::new().with(YoleckEditableLevels {
394 levels: Default::default(),
395 }));
396 app.add_message::<YoleckDirective>();
397 app.configure_sets(
398 Update,
399 YoleckRunEditSystems.after(YoleckSystems::ProcessRawEntities),
400 );
401 app.add_systems(
402 EguiPrimaryContextPass,
403 editor_window::yoleck_editor_window.in_set(YoleckRunEditSystems),
404 );
405
406 app.add_schedule(Schedule::new(
407 YoleckInternalSchedule::UpdateManagedDataFromComponents,
408 ));
409 }
410}
411
412pub trait YoleckExtForApp {
413 /// Add a type of entity that can be edited in Yoleck's level editor.
414 ///
415 /// ```no_run
416 /// # use bevy::prelude::*;
417 /// # use bevy_yoleck::prelude::*;
418 /// # use serde::{Deserialize, Serialize};
419 /// # #[derive(Default, Clone, PartialEq, Serialize, Deserialize, Component, YoleckComponent)]
420 /// # struct Component1;
421 /// # type Component2 = Component1;
422 /// # type Component3 = Component1;
423 /// # let mut app = App::new();
424 /// app.add_yoleck_entity_type({
425 /// YoleckEntityType::new("MyEntityType")
426 /// .with::<Component1>()
427 /// .with::<Component2>()
428 /// .with::<Component3>()
429 /// });
430 /// ```
431 fn add_yoleck_entity_type(&mut self, entity_type: YoleckEntityType);
432
433 /// Add a system for editing Yoleck components in the level editor.
434 ///
435 /// ```no_run
436 /// # use bevy::prelude::*;
437 /// # use bevy_yoleck::prelude::*;
438 /// # use serde::{Deserialize, Serialize};
439 /// # #[derive(Default, Clone, PartialEq, Serialize, Deserialize, Component, YoleckComponent)]
440 /// # struct Component1;
441 /// # let mut app = App::new();
442 ///
443 /// app.add_yoleck_edit_system(edit_component1);
444 ///
445 /// fn edit_component1(mut ui: ResMut<YoleckUi>, mut edit: YoleckEdit<&mut Component1>) {
446 /// let Ok(component1) = edit.single_mut() else { return };
447 /// // Edit `component1` with the `ui`
448 /// }
449 /// ```
450 ///
451 /// See [`YoleckEdit`](crate::editing::YoleckEdit).
452 fn add_yoleck_edit_system<P>(&mut self, system: impl 'static + IntoSystem<(), (), P>);
453
454 /// Register a function that upgrades entities from a previous version of the app format.
455 ///
456 /// This should only be called _after_ adding
457 /// [`YoleckEntityUpgradingPlugin`](crate::entity_upgrading::YoleckEntityUpgradingPlugin). See
458 /// that plugin's docs for more info.
459 fn add_yoleck_entity_upgrade(
460 &mut self,
461 to_version: usize,
462 upgrade_dlg: impl 'static
463 + Send
464 + Sync
465 + Fn(&str, &mut serde_json::Map<String, serde_json::Value>),
466 );
467
468 /// Register a function that upgrades entities of a specific type from a previous version of
469 /// the app format.
470 fn add_yoleck_entity_upgrade_for(
471 &mut self,
472 to_version: usize,
473 for_type_name: impl ToString,
474 upgrade_dlg: impl 'static + Send + Sync + Fn(&mut serde_json::Map<String, serde_json::Value>),
475 ) {
476 let for_type_name = for_type_name.to_string();
477 self.add_yoleck_entity_upgrade(to_version, move |type_name, data| {
478 if type_name == for_type_name {
479 upgrade_dlg(data);
480 }
481 });
482 }
483}
484
485impl YoleckExtForApp for App {
486 fn add_yoleck_entity_type(&mut self, entity_type: YoleckEntityType) {
487 let construction_specs = self
488 .world_mut()
489 .get_resource_or_insert_with(YoleckEntityConstructionSpecs::default);
490
491 let mut component_type_ids = Vec::with_capacity(entity_type.components.len());
492 let mut component_handlers_to_register = Vec::new();
493 for handler in entity_type.components.into_iter() {
494 component_type_ids.push(handler.component_type());
495 if !construction_specs
496 .component_handlers
497 .contains_key(&handler.component_type())
498 {
499 component_handlers_to_register.push(handler);
500 }
501 }
502
503 for handler in component_handlers_to_register.iter() {
504 handler.build_in_bevy_app(self);
505 }
506
507 let new_entry = YoleckEntityTypeInfo {
508 name: entity_type.name.clone(),
509 components: component_type_ids,
510 on_init: entity_type.on_init,
511 has_uuid: entity_type.has_uuid,
512 };
513
514 let mut construction_specs = self
515 .world_mut()
516 .get_resource_mut::<YoleckEntityConstructionSpecs>()
517 .expect("YoleckEntityConstructionSpecs was inserted earlier in this function");
518
519 let new_index = construction_specs.entity_types.len();
520 construction_specs
521 .entity_types_index
522 .insert(entity_type.name, new_index);
523 construction_specs.entity_types.push(new_entry);
524 for handler in component_handlers_to_register {
525 // Can handlers can register systems? If so, this needs to be broken into two phases...
526 construction_specs
527 .component_handlers
528 .insert(handler.component_type(), handler);
529 }
530 }
531
532 fn add_yoleck_edit_system<P>(&mut self, system: impl 'static + IntoSystem<(), (), P>) {
533 let system_id = self.world_mut().register_system(system);
534 let mut edit_systems = self
535 .world_mut()
536 .get_resource_or_insert_with(YoleckEditSystems::default);
537 edit_systems.edit_systems.push(system_id);
538 }
539
540 fn add_yoleck_entity_upgrade(
541 &mut self,
542 to_version: usize,
543 upgrade_dlg: impl 'static
544 + Send
545 + Sync
546 + Fn(&str, &mut serde_json::Map<String, serde_json::Value>),
547 ) {
548 let mut entity_upgrading = self.world_mut().get_resource_mut::<YoleckEntityUpgrading>()
549 .expect("add_yoleck_entity_upgrade can only be called after the YoleckEntityUpgrading plugin was added");
550 if entity_upgrading.app_format_version < to_version {
551 panic!(
552 "Cannot create an upgrade system to version {} when YoleckEntityUpgrading set the version to {}",
553 to_version, entity_upgrading.app_format_version
554 );
555 }
556 entity_upgrading
557 .upgrade_functions
558 .entry(to_version)
559 .or_default()
560 .push(Box::new(upgrade_dlg));
561 }
562}
563
564type BoxedArc = Arc<dyn Send + Sync + Any>;
565type BoxedAny = Box<dyn Send + Sync + Any>;
566
567/// A component that describes how Yoleck manages an entity under its control.
568#[derive(Component)]
569pub struct YoleckManaged {
570 /// A name to display near the entity in the entities list.
571 ///
572 /// This is for level editors' convenience only - it will not be used in the games.
573 pub name: String,
574
575 /// The type of the Yoleck entity, as registered with
576 /// [`add_yoleck_entity_type`](YoleckExtForApp::add_yoleck_entity_type).
577 ///
578 /// This defines the Yoleck components that can be edited for the entity.
579 pub type_name: String,
580
581 lifecycle_status: YoleckEntityLifecycleStatus,
582
583 pub(crate) components_data: HashMap<TypeId, BoxedAny>,
584}
585
586/// A marker for entities that belongs to the Yoleck level and should be despawned with it.
587///
588/// Yoleck already adds this automatically to entities created from the editor. The game itself
589/// should add this to entities created during gameplay, like bullets or spawned enemeis, so that
590/// they'll be despawned when a playtest is finished or restarted.
591///
592/// When removing a [`YoleckKeepLevel`] from entity (or removing the entire entity), Yoleck will
593/// automatically despawn all the entities that have this component and point to that level.
594///
595/// There is no need to add this to child entities of entities that already has this marker,
596/// because Bevy will already despawn them when despawning their parent.
597#[derive(Component, Debug, Clone, FromTemplate)]
598pub struct YoleckBelongsToLevel {
599 /// The entity which was used with [`YoleckLoadLevel`](entity_management::YoleckLoadLevel) to
600 /// load the level that this entity belongs to.
601 pub level: Entity,
602}
603
604pub enum YoleckEntityLifecycleStatus {
605 Synchronized,
606 JustCreated,
607 JustChanged,
608}
609
610#[derive(Default, Resource)]
611struct YoleckEditSystems {
612 edit_systems: Vec<SystemId>,
613}
614
615impl YoleckEditSystems {
616 pub(crate) fn run_systems(&mut self, world: &mut World) {
617 for system_id in self.edit_systems.iter() {
618 world
619 .run_system(*system_id)
620 .expect("edit systems handled by Yoleck - system should been properly handled");
621 }
622 }
623}
624
625pub(crate) struct YoleckEntityTypeInfo {
626 pub name: String,
627 pub components: Vec<TypeId>,
628 #[allow(clippy::type_complexity)]
629 pub(crate) on_init:
630 Vec<Box<dyn 'static + Sync + Send + Fn(YoleckEditorState, &mut EntityCommands)>>,
631 pub has_uuid: bool,
632}
633
634#[derive(Default, Resource)]
635pub(crate) struct YoleckEntityConstructionSpecs {
636 pub entity_types: Vec<YoleckEntityTypeInfo>,
637 pub entity_types_index: HashMap<String, usize>,
638 pub component_handlers: HashMap<TypeId, Box<dyn YoleckComponentHandler>>,
639}
640
641impl YoleckEntityConstructionSpecs {
642 pub fn get_entity_type_info(&self, entity_type: &str) -> Option<&YoleckEntityTypeInfo> {
643 Some(&self.entity_types[*self.entity_types_index.get(entity_type)?])
644 }
645}
646
647/// Fields of the Yoleck editor.
648#[derive(Resource)]
649pub(crate) struct YoleckState {
650 level_being_edited: Entity,
651 level_needs_saving: bool,
652}
653
654/// The level currently being playtested, if any.
655#[derive(Default, Resource)]
656pub struct YoleckPlaytestLevel(pub Option<YoleckRawLevel>);
657
658#[derive(ScheduleLabel, Debug, Clone, PartialEq, Eq, Hash)]
659pub(crate) enum YoleckInternalSchedule {
660 UpdateManagedDataFromComponents,
661 /// Before [`LevelLoaded`][YoleckSchedule::LevelLoaded] to resolve things like entity
662 /// references.
663 PostLoadResolutions,
664}
665
666/// Schedules for user code to do the actual entity/level population after Yoleck spawns the level
667/// "skeleton".
668#[derive(ScheduleLabel, Debug, Clone, PartialEq, Eq, Hash)]
669pub enum YoleckSchedule {
670 /// This is where user defined populate systems should reside.
671 ///
672 /// Note that populate systems, rather than directly trying to query the entities to be
673 /// populated, should use [`YoleckPopulate`](crate::prelude::YoleckPopulate):
674 ///
675 /// ```no_run
676 /// # use bevy::prelude::*;
677 /// # use bevy_yoleck::prelude::*;
678 /// # use serde::{Deserialize, Serialize};
679 /// # #[derive(Default, Clone, PartialEq, Serialize, Deserialize, Component, YoleckComponent)]
680 /// # struct Component1;
681 /// # let mut app = App::new();
682 ///
683 /// app.add_systems(YoleckSchedule::Populate, populate_component1);
684 ///
685 /// fn populate_component1(mut populate: YoleckPopulate<&Component1>) {
686 /// populate.populate(|_ctx, mut cmd, component1| {
687 /// // Add Bevy components derived from `component1` to `cmd`.
688 /// });
689 /// }
690 /// ```
691 Populate,
692 /// Right after all the level entities are loaded, but before any populate systems manage to
693 /// run.
694 LevelLoaded,
695 /// Since many bundles add their own transform and visibility components, systems that override
696 /// them explicitly need to go here.
697 OverrideCommonComponents,
698}
699
700/// Automatically added to level entities that are being edited in the level editor.
701#[derive(Component)]
702pub struct YoleckLevelInEditor;
703
704/// Automatically added to level entities that are being play-tested in the level editor.
705///
706/// Note that this only gets added to the levels that are launched from the editor UI. If game
707/// systems load new levels during the play-test, this component will not be added to them.
708#[derive(Component)]
709pub struct YoleckLevelInPlaytest;
710
711/// During the [`YoleckSchedule::LevelLoaded`] schedule, this component marks the level entities
712/// that were just loaded and triggered that schedule.
713///
714/// Note that this component will be removed after that schedule finishes running - it should not
715/// be relied on in systems outside that schedule.
716#[derive(Component)]
717pub struct YoleckLevelJustLoaded;