Skip to content

Commit 548e2c5

Browse files
authored
refactor: remove RuntimeContainer & RuntimeSettings, add plugin runtime to static world local settings (#471)
1 parent 5dd665a commit 548e2c5

File tree

10 files changed

+39
-176
lines changed

10 files changed

+39
-176
lines changed

crates/bevy_mod_scripting_core/src/bindings/script_system.rs

Lines changed: 1 addition & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,6 @@ use crate::{
1616
event::CallbackLabel,
1717
extractors::get_all_access_ids,
1818
handler::ScriptingHandler,
19-
runtime::RuntimeContainer,
2019
script::{ScriptAttachment, ScriptContext},
2120
};
2221
use ::{
@@ -201,7 +200,6 @@ impl ScriptSystemBuilder {
201200

202201
struct DynamicHandlerContext<'w, P: IntoScriptPluginParams> {
203202
script_context: &'w ScriptContext<P>,
204-
runtime_container: &'w RuntimeContainer<P>,
205203
}
206204

207205
#[profiling::all_functions]
@@ -213,15 +211,10 @@ impl<'w, P: IntoScriptPluginParams> DynamicHandlerContext<'w, P> {
213211
pub fn init_param(world: &mut World, system: &mut FilteredAccessSet<ComponentId>) {
214212
let mut access = FilteredAccess::<ComponentId>::matches_nothing();
215213

216-
let runtime_container_res_id = world
217-
.resource_id::<RuntimeContainer<P>>()
218-
.expect("RuntimeContainer resource not found");
219-
220214
let script_context_res_id = world
221215
.resource_id::<ScriptContext<P>>()
222216
.expect("Scripts resource not found");
223217

224-
access.add_resource_read(runtime_container_res_id);
225218
access.add_resource_read(script_context_res_id);
226219

227220
system.add(access);
@@ -235,9 +228,6 @@ impl<'w, P: IntoScriptPluginParams> DynamicHandlerContext<'w, P> {
235228
unsafe {
236229
Self {
237230
script_context: system.get_resource().expect("Scripts resource not found"),
238-
runtime_container: system
239-
.get_resource()
240-
.expect("RuntimeContainer resource not found"),
241231
}
242232
}
243233
}
@@ -257,7 +247,7 @@ impl<'w, P: IntoScriptPluginParams> DynamicHandlerContext<'w, P> {
257247
};
258248

259249
// call the script
260-
let runtime = &self.runtime_container.runtime;
250+
let runtime = P::readonly_configuration(guard.id()).runtime;
261251

262252
let mut context = context.lock();
263253

crates/bevy_mod_scripting_core/src/commands.rs

Lines changed: 5 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -149,32 +149,19 @@ impl<P: IntoScriptPluginParams> CreateOrUpdateScript<P> {
149149
content: &[u8],
150150
context: &mut P::C,
151151
guard: WorldGuard,
152-
handler_ctxt: &HandlerContext<P>,
153152
) -> Result<(), ScriptError> {
154153
debug!("{}: reloading context {}", P::LANGUAGE, attachment);
155154
// reload context
156-
P::reload(
157-
attachment,
158-
content,
159-
context,
160-
guard.clone(),
161-
&handler_ctxt.runtime_container.runtime,
162-
)
155+
P::reload(attachment, content, context, guard.clone())
163156
}
164157

165158
fn load_context(
166159
attachment: &ScriptAttachment,
167160
content: &[u8],
168161
guard: WorldGuard,
169-
handler_ctxt: &HandlerContext<P>,
170162
) -> Result<P::C, ScriptError> {
171163
debug!("{}: loading context {}", P::LANGUAGE, attachment);
172-
let context = P::load(
173-
attachment,
174-
content,
175-
guard.clone(),
176-
&handler_ctxt.runtime_container.runtime,
177-
)?;
164+
let context = P::load(attachment, content, guard.clone())?;
178165
Ok(context)
179166
}
180167

@@ -272,16 +259,10 @@ impl<P: IntoScriptPluginParams> CreateOrUpdateScript<P> {
272259
Some(context) => {
273260
let mut context = context.lock();
274261

275-
Self::reload_context(
276-
&attachment,
277-
content,
278-
&mut context,
279-
guard.clone(),
280-
handler_ctxt,
281-
)
282-
.map(|_| None)
262+
Self::reload_context(&attachment, content, &mut context, guard.clone())
263+
.map(|_| None)
283264
}
284-
None => Self::load_context(&attachment, content, guard.clone(), handler_ctxt).map(Some),
265+
None => Self::load_context(&attachment, content, guard.clone()).map(Some),
285266
};
286267

287268
match result_context_to_insert {

crates/bevy_mod_scripting_core/src/config.rs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,14 +14,16 @@ use crate::{
1414
/// Configs contained here should be
1515
///
1616
/// *global meaning stored in thread-locals, i.e. not annoyingly global, but pretty global.
17-
#[derive(Debug, Default)]
17+
#[derive(Debug)]
1818
pub struct ScriptingPluginConfiguration<P: IntoScriptPluginParams + ?Sized> {
1919
/// callbacks executed before a handler callback is executed every time
2020
pub pre_handling_callbacks: &'static [ContextPreHandlingInitializer<P>],
2121
/// callbacks executed once after creating a context but before executing it for the first time
2222
pub context_initialization_callbacks: &'static [ContextInitializer<P>],
2323
/// Whether to emit responses from the core callbacks like `on_script_loaded`.
2424
pub emit_responses: bool,
25+
/// The configured runtime for the plugin
26+
pub runtime: &'static P::R,
2527
}
2628

2729
impl<P: IntoScriptPluginParams + ?Sized> Clone for ScriptingPluginConfiguration<P> {

crates/bevy_mod_scripting_core/src/context.rs

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,6 @@ pub trait ScriptingLoader<P: IntoScriptPluginParams> {
5050
attachment: &ScriptAttachment,
5151
content: &[u8],
5252
world: WorldGuard,
53-
runtime: &P::R,
5453
) -> Result<P::C, ScriptError>;
5554

5655
/// Reloads a script context using the provided reloader function
@@ -59,7 +58,6 @@ pub trait ScriptingLoader<P: IntoScriptPluginParams> {
5958
content: &[u8],
6059
previous_context: &mut P::C,
6160
world: WorldGuard,
62-
runtime: &P::R,
6361
) -> Result<(), ScriptError>;
6462
}
6563

@@ -68,7 +66,6 @@ impl<P: IntoScriptPluginParams> ScriptingLoader<P> for P {
6866
attachment: &ScriptAttachment,
6967
content: &[u8],
7068
world: WorldGuard,
71-
runtime: &P::R,
7269
) -> Result<P::C, ScriptError> {
7370
WorldGuard::with_existing_static_guard(world.clone(), |world| {
7471
let world_id = world.id();
@@ -78,7 +75,7 @@ impl<P: IntoScriptPluginParams> ScriptingLoader<P> for P {
7875
content,
7976
P::readonly_configuration(world_id).context_initialization_callbacks,
8077
P::readonly_configuration(world_id).pre_handling_callbacks,
81-
runtime,
78+
P::readonly_configuration(world_id).runtime,
8279
)
8380
})
8481
}
@@ -88,7 +85,6 @@ impl<P: IntoScriptPluginParams> ScriptingLoader<P> for P {
8885
content: &[u8],
8986
previous_context: &mut P::C,
9087
world: WorldGuard,
91-
runtime: &P::R,
9288
) -> Result<(), ScriptError> {
9389
WorldGuard::with_existing_static_guard(world, |world| {
9490
let world_id = world.id();
@@ -99,7 +95,7 @@ impl<P: IntoScriptPluginParams> ScriptingLoader<P> for P {
9995
previous_context,
10096
P::readonly_configuration(world_id).context_initialization_callbacks,
10197
P::readonly_configuration(world_id).pre_handling_callbacks,
102-
runtime,
98+
P::readonly_configuration(world_id).runtime,
10399
)
104100
})
105101
}

crates/bevy_mod_scripting_core/src/extractors.rs

Lines changed: 1 addition & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,6 @@ use crate::{
2424
error::{InteropError, ScriptError},
2525
event::{CallbackLabel, IntoCallbackLabel},
2626
handler::ScriptingHandler,
27-
runtime::RuntimeContainer,
2827
script::{ScriptAttachment, ScriptContext, StaticScripts},
2928
};
3029

@@ -48,8 +47,6 @@ pub fn with_handler_system_state<
4847

4948
/// Context for systems which handle events for scripts
5049
pub struct HandlerContext<P: IntoScriptPluginParams> {
51-
/// The runtime container
52-
pub(crate) runtime_container: RuntimeContainer<P>,
5350
/// List of static scripts
5451
pub(crate) static_scripts: StaticScripts,
5552
/// Script context
@@ -61,7 +58,6 @@ impl<P: IntoScriptPluginParams> HandlerContext<P> {
6158
/// Every call to this function must be paired with a call to [`Self::release`].
6259
pub fn yoink(world: &mut World) -> Self {
6360
Self {
64-
runtime_container: world.remove_resource().unwrap_or_default(),
6561
static_scripts: world.remove_resource().unwrap_or_default(),
6662
script_context: world.remove_resource().unwrap_or_default(),
6763
}
@@ -71,24 +67,10 @@ impl<P: IntoScriptPluginParams> HandlerContext<P> {
7167
/// Only call this if you have previously yoinked the handler context from the world.
7268
pub fn release(self, world: &mut World) {
7369
// insert the handler context back into the world
74-
world.insert_resource(self.runtime_container);
7570
world.insert_resource(self.static_scripts);
7671
world.insert_resource(self.script_context);
7772
}
7873

79-
/// Splits the handler context into its individual components.
80-
///
81-
/// Useful if you are needing multiple resources from the handler context.
82-
/// Otherwise the borrow checker will prevent you from borrowing the handler context mutably multiple times.
83-
pub fn destructure(&mut self) -> (&mut RuntimeContainer<P>, &mut StaticScripts) {
84-
(&mut self.runtime_container, &mut self.static_scripts)
85-
}
86-
87-
/// Get the runtime container
88-
pub fn runtime_container(&mut self) -> &mut RuntimeContainer<P> {
89-
&mut self.runtime_container
90-
}
91-
9274
/// Get the static scripts
9375
pub fn static_scripts(&mut self) -> &mut StaticScripts {
9476
&mut self.static_scripts
@@ -122,7 +104,7 @@ impl<P: IntoScriptPluginParams> HandlerContext<P> {
122104
};
123105

124106
// call the script
125-
let runtime = &self.runtime_container.runtime;
107+
let runtime = P::readonly_configuration(guard.id()).runtime;
126108

127109
let mut context = context.lock();
128110

crates/bevy_mod_scripting_core/src/lib.rs

Lines changed: 17 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -12,15 +12,15 @@ use asset::{
1212
Language, ScriptAsset, ScriptAssetLoader, configure_asset_systems,
1313
configure_asset_systems_for_plugin,
1414
};
15-
use bevy_app::{App, Plugin, PostStartup, PostUpdate};
15+
use bevy_app::{App, Plugin, PostUpdate};
1616
use bevy_asset::{AssetApp, Handle};
17+
use bevy_ecs::schedule::IntoScheduleConfigs;
1718
use bevy_ecs::{
1819
reflect::{AppTypeRegistry, ReflectComponent},
1920
resource::Resource,
2021
schedule::SystemSet,
21-
system::{Command, In},
22+
system::Command,
2223
};
23-
use bevy_ecs::{schedule::IntoScheduleConfigs, system::IntoSystem};
2424
use bevy_log::error;
2525
use bevy_platform::collections::HashMap;
2626
use bindings::{
@@ -30,10 +30,9 @@ use bindings::{
3030
};
3131
use commands::{AddStaticScript, RemoveStaticScript};
3232
use context::{Context, ContextInitializer, ContextPreHandlingInitializer};
33-
use error::ScriptError;
3433
use event::{ScriptCallbackEvent, ScriptCallbackResponseEvent, ScriptEvent};
3534
use handler::HandlerFn;
36-
use runtime::{Runtime, RuntimeContainer, RuntimeInitializer, RuntimeSettings, initialize_runtime};
35+
use runtime::{Runtime, RuntimeInitializer};
3736
use script::{ContextPolicy, ScriptComponent, ScriptContext, StaticScripts};
3837
use std::ops::{Deref, DerefMut};
3938

@@ -97,8 +96,8 @@ pub trait IntoScriptPluginParams: 'static + GetPluginThreadConfig<Self> {
9796

9897
/// Bevy plugin enabling scripting within the bevy mod scripting framework
9998
pub struct ScriptingPlugin<P: IntoScriptPluginParams> {
100-
/// Settings for the runtime
101-
pub runtime_settings: RuntimeSettings<P>,
99+
/// Functions configuring the runtime after it is created
100+
pub runtime_initializers: Vec<RuntimeInitializer<P>>,
102101

103102
/// The strategy used to assign contexts to scripts
104103
pub context_policy: ContextPolicy,
@@ -137,7 +136,7 @@ where
137136
impl<P: IntoScriptPluginParams> Default for ScriptingPlugin<P> {
138137
fn default() -> Self {
139138
Self {
140-
runtime_settings: Default::default(),
139+
runtime_initializers: Default::default(),
141140
context_policy: ContextPolicy::default(),
142141
language: Default::default(),
143142
context_initializers: Default::default(),
@@ -150,16 +149,20 @@ impl<P: IntoScriptPluginParams> Default for ScriptingPlugin<P> {
150149
#[profiling::all_functions]
151150
impl<P: IntoScriptPluginParams> Plugin for ScriptingPlugin<P> {
152151
fn build(&self, app: &mut App) {
153-
app.insert_resource(self.runtime_settings.clone())
154-
.insert_resource::<RuntimeContainer<P>>(RuntimeContainer {
155-
runtime: P::build_runtime(),
156-
});
157-
158152
// initialize thread local configs
153+
154+
let runtime = P::build_runtime();
155+
for initializer in &self.runtime_initializers {
156+
if let Err(e) = initializer(&runtime) {
157+
error!("Error initializing runtime: {:?}. Continuing.", e);
158+
}
159+
}
160+
159161
let config = ScriptingPluginConfiguration::<P> {
160162
pre_handling_callbacks: Vec::leak(self.context_pre_handling_initializers.clone()),
161163
context_initialization_callbacks: Vec::leak(self.context_initializers.clone()),
162164
emit_responses: self.emit_responses,
165+
runtime: Box::leak(Box::new(runtime)),
163166
};
164167

165168
P::set_thread_config(app.world().id(), config);
@@ -196,7 +199,7 @@ impl<P: IntoScriptPluginParams> ScriptingPlugin<P> {
196199
///
197200
/// Initializers will be run after the runtime is created, but before any contexts are loaded.
198201
pub fn add_runtime_initializer(&mut self, initializer: RuntimeInitializer<P>) -> &mut Self {
199-
self.runtime_settings.initializers.push(initializer);
202+
self.runtime_initializers.push(initializer);
200203
self
201204
}
202205
}
@@ -325,16 +328,6 @@ impl Plugin for BMSScriptingInfrastructurePlugin {
325328

326329
/// Systems registered per-language
327330
fn register_script_plugin_systems<P: IntoScriptPluginParams>(app: &mut App) {
328-
app.add_systems(
329-
PostStartup,
330-
(initialize_runtime::<P>.pipe(|e: In<Result<(), ScriptError>>| {
331-
if let Err(e) = e.0 {
332-
error!("Error initializing runtime: {:?}", e);
333-
}
334-
}))
335-
.in_set(ScriptingSystemSet::RuntimeInitialization),
336-
);
337-
338331
app.add_plugins(configure_asset_systems_for_plugin::<P>);
339332
}
340333

@@ -346,32 +339,6 @@ fn register_types(app: &mut App) {
346339
app.register_type::<ScriptComponent>();
347340
}
348341

349-
/// Trait for adding a runtime initializer to an app
350-
pub trait AddRuntimeInitializer {
351-
/// Adds a runtime initializer to the app
352-
fn add_runtime_initializer<P: IntoScriptPluginParams>(
353-
&mut self,
354-
initializer: RuntimeInitializer<P>,
355-
) -> &mut Self;
356-
}
357-
358-
impl AddRuntimeInitializer for App {
359-
fn add_runtime_initializer<P: IntoScriptPluginParams>(
360-
&mut self,
361-
initializer: RuntimeInitializer<P>,
362-
) -> &mut Self {
363-
if !self.world_mut().contains_resource::<RuntimeSettings<P>>() {
364-
self.world_mut().init_resource::<RuntimeSettings<P>>();
365-
}
366-
self.world_mut()
367-
.resource_mut::<RuntimeSettings<P>>()
368-
.as_mut()
369-
.initializers
370-
.push(initializer);
371-
self
372-
}
373-
}
374-
375342
/// Trait for adding static scripts to an app
376343
pub trait ManageStaticScripts {
377344
/// Registers a script id as a static script.

0 commit comments

Comments
 (0)