Skip to content

Commit 3430b92

Browse files
committed
hack: It compiles.
1 parent 4d11149 commit 3430b92

File tree

7 files changed

+132
-118
lines changed

7 files changed

+132
-118
lines changed

crates/bevy_mod_scripting_core/src/asset.rs

Lines changed: 83 additions & 81 deletions
Original file line numberDiff line numberDiff line change
@@ -53,8 +53,8 @@ impl std::fmt::Display for Language {
5353
pub struct ScriptAsset {
5454
/// The body of the script
5555
pub content: Box<[u8]>,
56-
/// The virtual filesystem path of the asset, used to map to the script Id for asset backed scripts
57-
pub asset_path: AssetPath<'static>,
56+
/// The language of the script
57+
pub language: Language,
5858
}
5959

6060
#[derive(Event, Debug, Clone)]
@@ -97,7 +97,7 @@ impl AssetLoader for ScriptAssetLoader {
9797
}
9898
let asset = ScriptAsset {
9999
content: content.into_boxed_slice(),
100-
asset_path: load_context.asset_path().to_owned(),
100+
language: Language::Lua,
101101
};
102102
Ok(asset)
103103
}
@@ -107,60 +107,61 @@ impl AssetLoader for ScriptAssetLoader {
107107
}
108108
}
109109

110-
#[derive(Clone, Resource)]
111-
/// Settings to do with script assets and how they are handled
112-
pub struct ScriptAssetSettings {
113-
/// Strategy for mapping asset paths to script ids, by default this is the identity function
114-
pub script_id_mapper: AssetPathToScriptIdMapper,
115-
/// Mapping from extension to script language
116-
pub extension_to_language_map: HashMap<&'static str, Language>,
117-
118-
/// The currently supported asset extensions
119-
/// Should be updated by each scripting plugin to include the extensions it supports.
120-
///
121-
/// Will be used to populate the script asset loader with the supported extensions
122-
pub supported_extensions: &'static [&'static str],
123-
}
124-
125-
#[profiling::all_functions]
126-
impl ScriptAssetSettings {
127-
/// Selects the language for a given asset path
128-
pub fn select_script_language(&self, path: &AssetPath) -> Language {
129-
let extension = path
130-
.path()
131-
.extension()
132-
.and_then(|ext| ext.to_str())
133-
.unwrap_or_default();
134-
self.extension_to_language_map
135-
.get(extension)
136-
.cloned()
137-
.unwrap_or_default()
138-
}
139-
}
140-
141-
impl Default for ScriptAssetSettings {
142-
fn default() -> Self {
143-
Self {
144-
script_id_mapper: AssetPathToScriptIdMapper {
145-
map: (|path: &AssetPath| path.path().to_string_lossy().into_owned().into()),
146-
},
147-
extension_to_language_map: HashMap::from_iter(vec![
148-
("lua", Language::Lua),
149-
("luau", Language::Lua),
150-
("rhai", Language::Rhai),
151-
("rn", Language::Rune),
152-
]),
153-
supported_extensions: &["lua", "luau", "rhai", "rn"],
154-
}
155-
}
156-
}
157-
158-
/// Strategy for mapping asset paths to script ids, by default this is the identity function
159-
#[derive(Clone, Copy)]
160-
pub struct AssetPathToScriptIdMapper {
161-
/// The mapping function
162-
pub map: fn(&AssetPath) -> ScriptId,
163-
}
110+
// #[derive(Clone, Resource)]
111+
// /// Settings to do with script assets and how they are handled
112+
// pub struct ScriptAssetSettings {
113+
// /// Strategy for mapping asset paths to script ids, by default this is the identity function
114+
// pub script_id_mapper: AssetPathToScriptIdMapper,
115+
// /// Mapping from extension to script language
116+
// pub extension_to_language_map: HashMap<&'static str, Language>,
117+
118+
// /// The currently supported asset extensions
119+
// /// Should be updated by each scripting plugin to include the extensions it supports.
120+
// ///
121+
// /// Will be used to populate the script asset loader with the supported extensions
122+
// pub supported_extensions: &'static [&'static str],
123+
// }
124+
125+
// #[profiling::all_functions]
126+
// impl ScriptAssetSettings {
127+
// /// Selects the language for a given asset path
128+
// pub fn select_script_language(&self, path: &AssetPath) -> Language {
129+
// let extension = path
130+
// .path()
131+
// .extension()
132+
// .and_then(|ext| ext.to_str())
133+
// .unwrap_or_default();
134+
// self.extension_to_language_map
135+
// .get(extension)
136+
// .cloned()
137+
// .unwrap_or_default()
138+
// }
139+
// }
140+
141+
// impl Default for ScriptAssetSettings {
142+
// fn default() -> Self {
143+
// Self {
144+
// script_id_mapper: AssetPathToScriptIdMapper {
145+
// // map: (|path: &AssetPath| path.path().to_string_lossy().into_owned().into()),
146+
// map: (|path: &AssetPath| path.id()),
147+
// },
148+
// extension_to_language_map: HashMap::from_iter(vec![
149+
// ("lua", Language::Lua),
150+
// ("luau", Language::Lua),
151+
// ("rhai", Language::Rhai),
152+
// ("rn", Language::Rune),
153+
// ]),
154+
// supported_extensions: &["lua", "luau", "rhai", "rn"],
155+
// }
156+
// }
157+
// }
158+
159+
// /// Strategy for mapping asset paths to script ids, by default this is the identity function
160+
// #[derive(Clone, Copy)]
161+
// pub struct AssetPathToScriptIdMapper {
162+
// /// The mapping function
163+
// pub map: fn(&AssetPath) -> ScriptId,
164+
// }
164165

165166
/// A cache of asset id's to their script id's. Necessary since when we drop an asset we won't have the ability to get the path from the asset.
166167
#[derive(Default, Debug, Resource)]
@@ -174,8 +175,8 @@ pub struct ScriptMetadataStore {
174175
pub struct ScriptMetadata {
175176
/// The asset id of the script
176177
pub asset_id: AssetId<ScriptAsset>,
177-
/// The script id of the script
178-
pub script_id: ScriptId,
178+
// The script id of the script
179+
// pub script_id: ScriptId,
179180
/// The language of the script
180181
pub language: Language,
181182
}
@@ -211,7 +212,7 @@ pub(crate) fn dispatch_script_asset_events(
211212
mut script_asset_events: EventWriter<ScriptAssetEvent>,
212213
assets: Res<Assets<ScriptAsset>>,
213214
mut metadata_store: ResMut<ScriptMetadataStore>,
214-
settings: Res<ScriptAssetSettings>,
215+
// settings: Res<ScriptAssetSettings>,
215216
) {
216217
for event in events.read() {
217218
match event {
@@ -220,23 +221,24 @@ pub(crate) fn dispatch_script_asset_events(
220221
if !metadata_store.contains(*id) {
221222
let asset = assets.get(*id);
222223
if let Some(asset) = asset {
223-
let path = &asset.asset_path;
224-
let converter = settings.script_id_mapper.map;
225-
let script_id = converter(path);
226-
227-
let language = settings.select_script_language(path);
228-
if language == Language::Unknown {
229-
let extension = path
230-
.path()
231-
.extension()
232-
.and_then(|ext| ext.to_str())
233-
.unwrap_or_default();
234-
warn!("A script {:?} was added but its language is unknown. Consider adding the {:?} extension to the `ScriptAssetSettings`.", &script_id, extension);
224+
// let path = &asset.asset_path;
225+
// let converter = settings.script_id_mapper.map;
226+
// let script_id = converter(path);
227+
228+
// let language = settings.select_script_language(path);
229+
let language = &asset.language;
230+
if *language == Language::Unknown {
231+
// let extension = path
232+
// .path()
233+
// .extension()
234+
// .and_then(|ext| ext.to_str())
235+
// .unwrap_or_default();
236+
// warn!("A script {:?} was added but its language is unknown. Consider adding the {:?} extension to the `ScriptAssetSettings`.", &script_id, extension);
235237
}
236238
let metadata = ScriptMetadata {
237239
asset_id: *id,
238-
script_id,
239-
language,
240+
// script_id,
241+
language: language.clone(),
240242
};
241243
debug!("Script loaded, populating metadata: {:?}:", metadata);
242244
script_asset_events.send(ScriptAssetEvent::Added(metadata.clone()));
@@ -309,26 +311,26 @@ pub(crate) fn sync_script_data<P: IntoScriptPluginParams>(
309311
ScriptAssetEvent::Added(_) | ScriptAssetEvent::Modified(_) => {
310312
if metadata.language != P::LANGUAGE {
311313
trace!(
312-
"{}: Script asset with id: {} is for a different langauge than this sync system. Skipping.",
314+
"{}: Script asset {} is for a different langauge than this sync system. Skipping.",
313315
P::LANGUAGE,
314-
metadata.script_id
316+
metadata.asset_id
315317
);
316318
continue;
317319
}
318320

319-
info!("{}: Loading Script: {:?}", P::LANGUAGE, metadata.script_id,);
321+
info!("{}: Loading Script: {:?}", P::LANGUAGE, metadata.asset_id,);
320322

321323
if let Some(asset) = script_assets.get(metadata.asset_id) {
322324
commands.queue(CreateOrUpdateScript::<P>::new(
323-
metadata.script_id.clone(),
325+
metadata.asset_id.clone(),
324326
asset.content.clone(),
325327
Some(script_assets.reserve_handle().clone_weak()),
326328
));
327329
}
328330
}
329331
ScriptAssetEvent::Removed(_) => {
330-
info!("{}: Deleting Script: {:?}", P::LANGUAGE, metadata.script_id,);
331-
commands.queue(DeleteScript::<P>::new(metadata.script_id.clone()));
332+
info!("{}: Deleting Script: {:?}", P::LANGUAGE, metadata.asset_id,);
333+
commands.queue(DeleteScript::<P>::new(metadata.asset_id.clone()));
332334
}
333335
};
334336
}
@@ -356,7 +358,7 @@ pub(crate) fn configure_asset_systems(app: &mut App) -> &mut App {
356358
),
357359
)
358360
.init_resource::<ScriptMetadataStore>()
359-
.init_resource::<ScriptAssetSettings>()
361+
// .init_resource::<ScriptAssetSettings>()
360362
.add_event::<ScriptAssetEvent>();
361363

362364
app

crates/bevy_mod_scripting_core/src/bindings/globals/core.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ impl Plugin for CoreScriptGlobalsPlugin {
5353
app.init_resource::<AppScriptGlobalsRegistry>();
5454
}
5555
fn finish(&self, app: &mut bevy::app::App) {
56-
profiling::function_scope!("app finish");
56+
// profiling::function_scope!("app finish");
5757

5858
if self.register_static_references {
5959
register_static_core_globals(app.world_mut(), self.filter);
@@ -121,7 +121,7 @@ impl CoreGlobals {
121121
>,
122122
InteropError,
123123
> {
124-
profiling::function_scope!("registering core globals");
124+
// profiling::function_scope!("registering core globals");
125125
let type_registry = guard.type_registry();
126126
let type_registry = type_registry.read();
127127
let mut type_cache = HashMap::<String, _>::default();

crates/bevy_mod_scripting_core/src/bindings/script_system.rs

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ use crate::{
2121
IntoScriptPluginParams,
2222
};
2323
use bevy::{
24+
prelude::AssetServer,
2425
ecs::{
2526
archetype::{ArchetypeComponentId, ArchetypeGeneration},
2627
component::{ComponentId, Tick},
@@ -78,12 +79,14 @@ enum ScriptSystemParamDescriptor {
7879
EntityQuery(ScriptQueryBuilder),
7980
}
8081

82+
type ScriptPath = Cow<'static, str>;
83+
8184
/// A builder for systems living in scripts
8285
#[derive(Reflect, Clone)]
8386
#[reflect(opaque)]
8487
pub struct ScriptSystemBuilder {
8588
pub(crate) name: CallbackLabel,
86-
pub(crate) script_id: ScriptId,
89+
pub(crate) script_id: ScriptPath,
8790
before: Vec<ReflectSystem>,
8891
after: Vec<ReflectSystem>,
8992
system_params: Vec<ScriptSystemParamDescriptor>,
@@ -93,7 +96,7 @@ pub struct ScriptSystemBuilder {
9396
#[profiling::all_functions]
9497
impl ScriptSystemBuilder {
9598
/// Creates a new script system builder
96-
pub fn new(name: CallbackLabel, script_id: ScriptId) -> Self {
99+
pub fn new(name: CallbackLabel, script_id: ScriptPath) -> Self {
97100
Self {
98101
before: vec![],
99102
after: vec![],
@@ -339,7 +342,7 @@ pub struct DynamicScriptSystem<P: IntoScriptPluginParams> {
339342
/// cause a conflict
340343
pub(crate) archetype_component_access: Access<ArchetypeComponentId>,
341344
pub(crate) last_run: Tick,
342-
target_script: ScriptId,
345+
target_script: ScriptPath,
343346
archetype_generation: ArchetypeGeneration,
344347
system_param_descriptors: Vec<ScriptSystemParamDescriptor>,
345348
state: Option<ScriptSystemState>,
@@ -420,6 +423,11 @@ impl<P: IntoScriptPluginParams> System for DynamicScriptSystem<P> {
420423
};
421424

422425
let mut payload = Vec::with_capacity(state.system_params.len());
426+
let script_id = {
427+
let asset_server = world.world().resource::<AssetServer>();
428+
let handle = asset_server.load(&*self.target_script);
429+
handle.id()
430+
};
423431
let guard = if self.exclusive {
424432
// safety: we are an exclusive system, therefore the cell allows us to do this
425433
let world = unsafe { world.world_mut() };
@@ -489,7 +497,8 @@ impl<P: IntoScriptPluginParams> System for DynamicScriptSystem<P> {
489497

490498
let result = handler_ctxt.call_dynamic_label(
491499
&state.callback_label,
492-
&self.target_script,
500+
// &self.target_script,
501+
&script_id,
493502
Entity::from_raw(0),
494503
payload,
495504
guard.clone(),

crates/bevy_mod_scripting_core/src/commands.rs

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
//! Commands for creating, updating and deleting scripts
22
33
use crate::{
4+
AssetId,
45
asset::ScriptAsset,
56
bindings::{ScriptValue, WorldGuard},
67
context::ContextBuilder,
@@ -21,14 +22,14 @@ use std::{marker::PhantomData, sync::Arc};
2122
/// Deletes a script with the given ID
2223
pub struct DeleteScript<P: IntoScriptPluginParams> {
2324
/// The ID of the script to delete
24-
pub id: ScriptId,
25+
pub id: AssetId<ScriptAsset>,
2526
/// hack to make this Send, C does not need to be Send since it is not stored in the command
2627
pub _ph: PhantomData<fn(P::C, P::R)>,
2728
}
2829

2930
impl<P: IntoScriptPluginParams> DeleteScript<P> {
3031
/// Creates a new DeleteScript command with the given ID
31-
pub fn new(id: ScriptId) -> Self {
32+
pub fn new(id: AssetId<ScriptAsset>) -> Self {
3233
Self {
3334
id,
3435
_ph: PhantomData,
@@ -249,7 +250,7 @@ impl<P: IntoScriptPluginParams> Command for CreateOrUpdateScript<P> {
249250
/// Runs a callback on the script with the given ID if it exists
250251
pub struct RunScriptCallback<P: IntoScriptPluginParams> {
251252
/// The ID of the script to run the callback on
252-
pub id: ScriptId,
253+
pub id: AssetId<ScriptAsset>,
253254
/// The entity to use for the callback
254255
pub entity: Entity,
255256
/// The callback to run
@@ -267,7 +268,7 @@ pub struct RunScriptCallback<P: IntoScriptPluginParams> {
267268
impl<P: IntoScriptPluginParams> RunScriptCallback<P> {
268269
/// Creates a new RunCallbackCommand with the given ID, callback and arguments
269270
pub fn new(
270-
id: ScriptId,
271+
id: AssetId<ScriptAsset>,
271272
entity: Entity,
272273
callback: CallbackLabel,
273274
args: Vec<ScriptValue>,

0 commit comments

Comments
 (0)