
*This PR description is an edited copy of #5007, written by @alice-i-cecile.* # Objective Follow-up to https://github.com/bevyengine/bevy/pull/2254. The `Resource` trait currently has a blanket implementation for all types that meet its bounds. While ergonomic, this results in several drawbacks: * it is possible to make confusing, silent mistakes such as inserting a function pointer (Foo) rather than a value (Foo::Bar) as a resource * it is challenging to discover if a type is intended to be used as a resource * we cannot later add customization options (see the [RFC](https://github.com/bevyengine/rfcs/blob/main/rfcs/27-derive-component.md) for the equivalent choice for Component). * dependencies can use the same Rust type as a resource in invisibly conflicting ways * raw Rust types used as resources cannot preserve privacy appropriately, as anyone able to access that type can read and write to internal values * we cannot capture a definitive list of possible resources to display to users in an editor ## Notes to reviewers * Review this commit-by-commit; there's effectively no back-tracking and there's a lot of churn in some of these commits. *ira: My commits are not as well organized :')* * I've relaxed the bound on Local to Send + Sync + 'static: I don't think these concerns apply there, so this can keep things simple. Storing e.g. a u32 in a Local is fine, because there's a variable name attached explaining what it does. * I think this is a bad place for the Resource trait to live, but I've left it in place to make reviewing easier. IMO that's best tackled with https://github.com/bevyengine/bevy/issues/4981. ## Changelog `Resource` is no longer automatically implemented for all matching types. Instead, use the new `#[derive(Resource)]` macro. ## Migration Guide Add `#[derive(Resource)]` to all types you are using as a resource. If you are using a third party type as a resource, wrap it in a tuple struct to bypass orphan rules. Consider deriving `Deref` and `DerefMut` to improve ergonomics. `ClearColor` no longer implements `Component`. Using `ClearColor` as a component in 0.8 did nothing. Use the `ClearColorConfig` in the `Camera3d` and `Camera2d` components instead. Co-authored-by: Alice <alice.i.cecile@gmail.com> Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com> Co-authored-by: devil-ira <justthecooldude@gmail.com> Co-authored-by: Carter Anderson <mcanders1@gmail.com>
150 lines
5.1 KiB
Rust
150 lines
5.1 KiB
Rust
//! Support for hot reloading internal assets.
|
|
//!
|
|
//! Internal assets (e.g. shaders) are bundled directly into an application and can't be hot
|
|
//! reloaded using the conventional API.
|
|
use bevy_app::{App, Plugin};
|
|
use bevy_ecs::{
|
|
event::Events,
|
|
schedule::SystemLabel,
|
|
system::{NonSendMut, Res, ResMut, Resource, SystemState},
|
|
};
|
|
use bevy_tasks::{IoTaskPool, TaskPoolBuilder};
|
|
use bevy_utils::HashMap;
|
|
use std::{
|
|
ops::{Deref, DerefMut},
|
|
path::Path,
|
|
};
|
|
|
|
use crate::{
|
|
Asset, AssetEvent, AssetPlugin, AssetServer, AssetServerSettings, Assets, FileAssetIo, Handle,
|
|
HandleUntyped,
|
|
};
|
|
|
|
/// A helper [`App`] used for hot reloading internal assets, which are compiled-in to Bevy plugins.
|
|
pub struct DebugAssetApp(App);
|
|
|
|
impl Deref for DebugAssetApp {
|
|
type Target = App;
|
|
|
|
fn deref(&self) -> &Self::Target {
|
|
&self.0
|
|
}
|
|
}
|
|
|
|
impl DerefMut for DebugAssetApp {
|
|
fn deref_mut(&mut self) -> &mut Self::Target {
|
|
&mut self.0
|
|
}
|
|
}
|
|
|
|
/// A label describing the system that runs [`DebugAssetApp`].
|
|
#[derive(SystemLabel, Debug, Clone, PartialEq, Eq, Hash)]
|
|
pub struct DebugAssetAppRun;
|
|
|
|
/// Facilitates the creation of a "debug asset app", whose sole responsibility is hot reloading
|
|
/// assets that are "internal" / compiled-in to Bevy Plugins.
|
|
///
|
|
/// Pair with the [`load_internal_asset`](crate::load_internal_asset) macro to load hot-reloadable
|
|
/// assets. The `debug_asset_server` feature flag must also be enabled for hot reloading to work.
|
|
/// Currently only hot reloads assets stored in the `crates` folder.
|
|
#[derive(Default)]
|
|
pub struct DebugAssetServerPlugin;
|
|
|
|
/// A collection that maps internal assets in a [`DebugAssetApp`]'s asset server to their mirrors in
|
|
/// the main [`App`].
|
|
#[derive(Resource)]
|
|
pub struct HandleMap<T: Asset> {
|
|
/// The collection of asset handles.
|
|
pub handles: HashMap<Handle<T>, Handle<T>>,
|
|
}
|
|
|
|
impl<T: Asset> Default for HandleMap<T> {
|
|
fn default() -> Self {
|
|
Self {
|
|
handles: Default::default(),
|
|
}
|
|
}
|
|
}
|
|
|
|
impl Plugin for DebugAssetServerPlugin {
|
|
fn build(&self, app: &mut bevy_app::App) {
|
|
IoTaskPool::init(|| {
|
|
TaskPoolBuilder::default()
|
|
.num_threads(2)
|
|
.thread_name("Debug Asset Server IO Task Pool".to_string())
|
|
.build()
|
|
});
|
|
let mut debug_asset_app = App::new();
|
|
debug_asset_app
|
|
.insert_resource(AssetServerSettings {
|
|
asset_folder: "crates".to_string(),
|
|
watch_for_changes: true,
|
|
})
|
|
.add_plugin(AssetPlugin);
|
|
app.insert_non_send_resource(DebugAssetApp(debug_asset_app));
|
|
app.add_system(run_debug_asset_app);
|
|
}
|
|
}
|
|
|
|
fn run_debug_asset_app(mut debug_asset_app: NonSendMut<DebugAssetApp>) {
|
|
debug_asset_app.0.update();
|
|
}
|
|
|
|
pub(crate) fn sync_debug_assets<T: Asset + Clone>(
|
|
mut debug_asset_app: NonSendMut<DebugAssetApp>,
|
|
mut assets: ResMut<Assets<T>>,
|
|
) {
|
|
let world = &mut debug_asset_app.0.world;
|
|
let mut state = SystemState::<(
|
|
Res<Events<AssetEvent<T>>>,
|
|
Res<HandleMap<T>>,
|
|
Res<Assets<T>>,
|
|
)>::new(world);
|
|
let (changed_shaders, handle_map, debug_assets) = state.get_mut(world);
|
|
for changed in changed_shaders.iter_current_update_events() {
|
|
let debug_handle = match changed {
|
|
AssetEvent::Created { handle } | AssetEvent::Modified { handle } => handle,
|
|
AssetEvent::Removed { .. } => continue,
|
|
};
|
|
if let Some(handle) = handle_map.handles.get(debug_handle) {
|
|
if let Some(debug_asset) = debug_assets.get(debug_handle) {
|
|
assets.set_untracked(handle, debug_asset.clone());
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Uses the return type of the given loader to register the given handle with the appropriate type
|
|
/// and load the asset with the given `path` and parent `file_path`.
|
|
///
|
|
/// If this feels a bit odd ... that's because it is. This was built to improve the UX of the
|
|
/// `load_internal_asset` macro.
|
|
pub fn register_handle_with_loader<A: Asset>(
|
|
_loader: fn(&'static str) -> A,
|
|
app: &mut DebugAssetApp,
|
|
handle: HandleUntyped,
|
|
file_path: &str,
|
|
path: &'static str,
|
|
) {
|
|
let mut state = SystemState::<(ResMut<HandleMap<A>>, Res<AssetServer>)>::new(&mut app.world);
|
|
let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").unwrap();
|
|
let manifest_dir_path = Path::new(&manifest_dir);
|
|
let (mut handle_map, asset_server) = state.get_mut(&mut app.world);
|
|
let asset_io = asset_server
|
|
.asset_io()
|
|
.downcast_ref::<FileAssetIo>()
|
|
.expect("The debug AssetServer only works with FileAssetIo-backed AssetServers");
|
|
let absolute_file_path = manifest_dir_path.join(
|
|
Path::new(file_path)
|
|
.parent()
|
|
.expect("file path must have a parent"),
|
|
);
|
|
let asset_folder_relative_path = absolute_file_path
|
|
.strip_prefix(asset_io.root_path())
|
|
.expect("The AssetIo root path should be a prefix of the absolute file path");
|
|
handle_map.handles.insert(
|
|
asset_server.load(asset_folder_relative_path.join(path)),
|
|
handle.clone_weak().typed::<A>(),
|
|
);
|
|
}
|