Skip to content

Commit

Permalink
move world pointers to thread locals
Browse files Browse the repository at this point in the history
  • Loading branch information
makspll committed Jan 11, 2025
1 parent 2491f54 commit 5fb0776
Show file tree
Hide file tree
Showing 11 changed files with 191 additions and 275 deletions.
46 changes: 46 additions & 0 deletions crates/bevy_mod_scripting_core/src/bindings/world.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ use bevy::{
};
use std::{
any::TypeId,
cell::RefCell,
fmt::Debug,
sync::{Arc, Weak},
time::Duration,
Expand Down Expand Up @@ -946,6 +947,51 @@ impl WorldAccessGuard<'_> {
}
}

/// Utility type for accessing the world in a callback
pub trait WorldContainer {
type Error: Debug;
/// Sets the world to the given value
fn set_world(&mut self, world: WorldCallbackAccess) -> Result<(), Self::Error>;

/// Gets the world, use [`WorldContainer::try_get_world`] if you want to handle errors with retrieving the world
/// # Panics
/// - if the world has not been set
/// - if the world has been dropped
fn get_world(&self) -> WorldGuard<'static> {
self.try_get_world().expect("World not set, or expired")
}

/// Tries to get the world
fn try_get_world(&self) -> Result<Arc<WorldAccessGuard<'static>>, Self::Error>;
}

/// A world container that stores the world in a thread local
pub struct ThreadWorldContainer;

thread_local! {
static WORLD_CALLBACK_ACCESS: RefCell<Option<WorldCallbackAccess>> = const { RefCell::new(None) };
}

impl WorldContainer for ThreadWorldContainer {
type Error = InteropError;

fn set_world(&mut self, world: WorldCallbackAccess) -> Result<(), Self::Error> {
WORLD_CALLBACK_ACCESS.with(|w| {
w.replace(Some(world));
});
Ok(())
}

fn try_get_world(&self) -> Result<Arc<WorldAccessGuard<'static>>, Self::Error> {
WORLD_CALLBACK_ACCESS.with(|w| {
w.borrow()
.as_ref()
.map(|w| w.try_read())
.ok_or_else(InteropError::missing_world)
})?
}
}

// #[cfg(test)]
// mod test {
// use crate::bindings::ScriptTypeRegistration;
Expand Down
1 change: 0 additions & 1 deletion crates/bevy_mod_scripting_core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@ pub mod reflection_extensions;
pub mod runtime;
pub mod script;
pub mod systems;
pub mod world;

/// Types which act like scripting plugins, by selecting a context and runtime
/// Each individual combination of context and runtime has specific infrastructure built for it and does not interact with other scripting plugins
Expand Down
158 changes: 0 additions & 158 deletions crates/bevy_mod_scripting_core/src/world.rs

This file was deleted.

Loading

0 comments on commit 5fb0776

Please sign in to comment.