fibers #2
6 changed files with 59 additions and 38 deletions
|
|
@ -1,2 +1,5 @@
|
||||||
puts get_player_name.await
|
a = get_player_name
|
||||||
|
b = a
|
||||||
|
puts a.await
|
||||||
|
puts b.await
|
||||||
quit
|
quit
|
||||||
|
|
|
||||||
|
|
@ -10,18 +10,18 @@ pub struct CallbackSystem<R: Runtime> {
|
||||||
pub(crate) arg_types: Vec<TypeId>,
|
pub(crate) arg_types: Vec<TypeId>,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) struct FunctionCallEvent<C: Send, V: Send> {
|
pub(crate) struct FunctionCallEvent<C: Send, V: Send, F: Send> {
|
||||||
pub(crate) params: Vec<V>,
|
pub(crate) params: Vec<V>,
|
||||||
pub(crate) promise: Promise<C, V>,
|
pub(crate) promise: Promise<C, V, F>,
|
||||||
}
|
}
|
||||||
|
|
||||||
type Calls<C, V> = Arc<Mutex<Vec<FunctionCallEvent<C, V>>>>;
|
type Calls<C, V, F> = Arc<Mutex<Vec<FunctionCallEvent<C, V, F>>>>;
|
||||||
|
|
||||||
/// A struct representing a Bevy system that can be called from a script.
|
/// A struct representing a Bevy system that can be called from a script.
|
||||||
pub(crate) struct Callback<R: Runtime> {
|
pub(crate) struct Callback<R: Runtime> {
|
||||||
pub(crate) name: String,
|
pub(crate) name: String,
|
||||||
pub(crate) system: Arc<Mutex<CallbackSystem<R>>>,
|
pub(crate) system: Arc<Mutex<CallbackSystem<R>>>,
|
||||||
pub(crate) calls: Calls<R::CallContext, R::Value>,
|
pub(crate) calls: Calls<R::CallContext, R::Value, R::Value>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<R: Runtime> Clone for Callback<R> {
|
impl<R: Runtime> Clone for Callback<R> {
|
||||||
|
|
@ -37,7 +37,7 @@ impl<R: Runtime> Clone for Callback<R> {
|
||||||
impl<R: Runtime> CallbackSystem<R> {
|
impl<R: Runtime> CallbackSystem<R> {
|
||||||
pub(crate) fn call(
|
pub(crate) fn call(
|
||||||
&mut self,
|
&mut self,
|
||||||
call: &FunctionCallEvent<R::CallContext, R::Value>,
|
call: &FunctionCallEvent<R::CallContext, R::Value, R::Value>,
|
||||||
world: &mut World,
|
world: &mut World,
|
||||||
) -> R::Value {
|
) -> R::Value {
|
||||||
self.system.run(call.params.clone(), world)
|
self.system.run(call.params.clone(), world)
|
||||||
|
|
|
||||||
|
|
@ -345,7 +345,8 @@ pub trait Runtime: Resource + Default {
|
||||||
f: impl Fn(
|
f: impl Fn(
|
||||||
Self::CallContext,
|
Self::CallContext,
|
||||||
Vec<Self::Value>,
|
Vec<Self::Value>,
|
||||||
) -> Result<Promise<Self::CallContext, Self::Value>, ScriptingError>
|
)
|
||||||
|
-> Result<Promise<Self::CallContext, Self::Value, Self::Value>, ScriptingError>
|
||||||
+ Send
|
+ Send
|
||||||
+ Sync
|
+ Sync
|
||||||
+ 'static,
|
+ 'static,
|
||||||
|
|
|
||||||
|
|
@ -1,27 +1,31 @@
|
||||||
use std::sync::{Arc, Mutex};
|
use std::sync::{Arc, Mutex};
|
||||||
|
|
||||||
|
use magnus::Fiber;
|
||||||
|
|
||||||
use crate::{Runtime, ScriptingError};
|
use crate::{Runtime, ScriptingError};
|
||||||
|
|
||||||
/// A struct that represents a function that will get called when the Promise is resolved.
|
/// A struct that represents a function that will get called when the Promise is resolved.
|
||||||
pub(crate) struct PromiseCallback<C: Send, V: Send> {
|
pub(crate) struct PromiseCallback<C: Send, V: Send, F: Send> {
|
||||||
callback: V,
|
callback: V,
|
||||||
following_promise: Arc<Mutex<PromiseInner<C, V>>>,
|
following_promise: Arc<Mutex<PromiseInner<C, V, F>>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Internal representation of a Promise.
|
/// Internal representation of a Promise.
|
||||||
pub(crate) struct PromiseInner<C: Send, V: Send> {
|
pub(crate) struct PromiseInner<C: Send, V: Send, F: Send> {
|
||||||
pub(crate) callbacks: Vec<PromiseCallback<C, V>>,
|
pub(crate) callbacks: Vec<PromiseCallback<C, V, F>>,
|
||||||
#[allow(deprecated)]
|
#[allow(deprecated)]
|
||||||
pub(crate) context: C,
|
pub(crate) context: C,
|
||||||
|
pub(crate) resolved_value: Option<V>,
|
||||||
|
pub(crate) fibers: Vec<F>, // TODO: should htis be vec or option
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A struct that represents a Promise.
|
/// A struct that represents a Promise.
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct Promise<C: Send, V: Send> {
|
pub struct Promise<C: Send, V: Send, F: Send> {
|
||||||
pub(crate) inner: Arc<Mutex<PromiseInner<C, V>>>,
|
pub(crate) inner: Arc<Mutex<PromiseInner<C, V, F>>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<C: Send, V: Send + Clone> PromiseInner<C, V> {
|
impl<C: Send, V: Send + Clone, F: Send + Clone> PromiseInner<C, V, F> {
|
||||||
/// Resolve the Promise. This will call all the callbacks that were added to the Promise.
|
/// Resolve the Promise. This will call all the callbacks that were added to the Promise.
|
||||||
fn resolve<R>(&mut self, runtime: &mut R, val: R::Value) -> Result<(), ScriptingError>
|
fn resolve<R>(&mut self, runtime: &mut R, val: R::Value) -> Result<(), ScriptingError>
|
||||||
where
|
where
|
||||||
|
|
@ -41,7 +45,7 @@ impl<C: Send, V: Send + Clone> PromiseInner<C, V> {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<C: Clone + Send + 'static, V: Send + Clone> Promise<C, V> {
|
impl<C: Clone + Send + 'static, V: Send + Clone, F: Send + Clone> Promise<C, V, F> {
|
||||||
/// Acquire [Mutex] for writing the promise and resolve it. Call will be forwarded to [PromiseInner::resolve].
|
/// Acquire [Mutex] for writing the promise and resolve it. Call will be forwarded to [PromiseInner::resolve].
|
||||||
pub(crate) fn resolve<R>(
|
pub(crate) fn resolve<R>(
|
||||||
&mut self,
|
&mut self,
|
||||||
|
|
@ -52,11 +56,25 @@ impl<C: Clone + Send + 'static, V: Send + Clone> Promise<C, V> {
|
||||||
R: Runtime<Value = V, CallContext = C>,
|
R: Runtime<Value = V, CallContext = C>,
|
||||||
{
|
{
|
||||||
if let Ok(mut inner) = self.inner.lock() {
|
if let Ok(mut inner) = self.inner.lock() {
|
||||||
|
inner.resolved_value = Some(val.clone());
|
||||||
inner.resolve(runtime, val)?;
|
inner.resolve(runtime, val)?;
|
||||||
|
for fiber in inner.fibers.drain(..) {
|
||||||
|
println!("resume");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Register a fiber that will be resumed when the [Promise] is resolved.
|
||||||
|
#[cfg(any(feature = "rhai", feature = "lua", feature = "ruby"))]
|
||||||
|
pub(crate) fn await_promise(&mut self, fiber: F) {
|
||||||
|
let mut inner = self
|
||||||
|
.inner
|
||||||
|
.lock()
|
||||||
|
.expect("Failed to lock inner promise mutex");
|
||||||
|
inner.fibers.push(fiber);
|
||||||
|
}
|
||||||
|
|
||||||
/// Register a callback that will be called when the [Promise] is resolved.
|
/// Register a callback that will be called when the [Promise] is resolved.
|
||||||
#[cfg(any(feature = "rhai", feature = "lua", feature = "ruby"))]
|
#[cfg(any(feature = "rhai", feature = "lua", feature = "ruby"))]
|
||||||
pub(crate) fn then(&mut self, callback: V) -> Self {
|
pub(crate) fn then(&mut self, callback: V) -> Self {
|
||||||
|
|
@ -65,8 +83,10 @@ impl<C: Clone + Send + 'static, V: Send + Clone> Promise<C, V> {
|
||||||
.lock()
|
.lock()
|
||||||
.expect("Failed to lock inner promise mutex");
|
.expect("Failed to lock inner promise mutex");
|
||||||
let following_inner = Arc::new(Mutex::new(PromiseInner {
|
let following_inner = Arc::new(Mutex::new(PromiseInner {
|
||||||
|
fibers: vec![],
|
||||||
callbacks: vec![],
|
callbacks: vec![],
|
||||||
context: inner.context.clone(),
|
context: inner.context.clone(),
|
||||||
|
resolved_value: None,
|
||||||
}));
|
}));
|
||||||
|
|
||||||
inner.callbacks.push(PromiseCallback {
|
inner.callbacks.push(PromiseCallback {
|
||||||
|
|
|
||||||
|
|
@ -129,9 +129,9 @@ impl Drop for RubyThread {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl DataTypeFunctions for Promise<(), RubyValue> {}
|
impl DataTypeFunctions for Promise<(), RubyValue, RubyValue> {}
|
||||||
|
|
||||||
unsafe impl TypedData for Promise<(), RubyValue> {
|
unsafe impl TypedData for Promise<(), RubyValue, RubyValue> {
|
||||||
fn class(ruby: &Ruby) -> magnus::RClass {
|
fn class(ruby: &Ruby) -> magnus::RClass {
|
||||||
static CLASS: Lazy<RClass> = Lazy::new(|ruby| {
|
static CLASS: Lazy<RClass> = Lazy::new(|ruby| {
|
||||||
let class = ruby
|
let class = ruby
|
||||||
|
|
@ -147,12 +147,12 @@ unsafe impl TypedData for Promise<(), RubyValue> {
|
||||||
|
|
||||||
fn data_type() -> &'static magnus::DataType {
|
fn data_type() -> &'static magnus::DataType {
|
||||||
static DATA_TYPE: DataType =
|
static DATA_TYPE: DataType =
|
||||||
data_type_builder!(Promise<(), RubyValue>, "Bevy::Promise").build();
|
data_type_builder!(Promise<(), RubyValue, RubyValue>, "Bevy::Promise").build();
|
||||||
&DATA_TYPE
|
&DATA_TYPE
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl TryConvert for Promise<(), RubyValue> {
|
impl TryConvert for Promise<(), RubyValue, RubyValue> {
|
||||||
fn try_convert(val: magnus::Value) -> Result<Self, magnus::Error> {
|
fn try_convert(val: magnus::Value) -> Result<Self, magnus::Error> {
|
||||||
let result: Result<&Self, _> = TryConvert::try_convert(val);
|
let result: Result<&Self, _> = TryConvert::try_convert(val);
|
||||||
result.cloned()
|
result.cloned()
|
||||||
|
|
@ -160,7 +160,7 @@ impl TryConvert for Promise<(), RubyValue> {
|
||||||
}
|
}
|
||||||
|
|
||||||
fn then(r_self: magnus::Value) -> magnus::Value {
|
fn then(r_self: magnus::Value) -> magnus::Value {
|
||||||
let promise: &Promise<(), RubyValue> =
|
let promise: &Promise<(), RubyValue, RubyValue> =
|
||||||
TryConvert::try_convert(r_self).expect("Couldn't convert self to Promise");
|
TryConvert::try_convert(r_self).expect("Couldn't convert self to Promise");
|
||||||
let ruby =
|
let ruby =
|
||||||
Ruby::get().expect("Failed to get a handle to Ruby API when registering Promise callback");
|
Ruby::get().expect("Failed to get a handle to Ruby API when registering Promise callback");
|
||||||
|
|
@ -179,21 +179,15 @@ fn then(r_self: magnus::Value) -> magnus::Value {
|
||||||
}
|
}
|
||||||
|
|
||||||
fn await_promise(r_self: magnus::Value) -> magnus::Value {
|
fn await_promise(r_self: magnus::Value) -> magnus::Value {
|
||||||
let promise: &Promise<(), RubyValue> =
|
let promise: &Promise<(), RubyValue, RubyValue> =
|
||||||
TryConvert::try_convert(r_self).expect("Couldn't convert self to Promise");
|
TryConvert::try_convert(r_self).expect("Couldn't convert self to Promise");
|
||||||
let ruby =
|
let ruby =
|
||||||
Ruby::get().expect("Failed to get a handle to Ruby API when registering Promise callback");
|
Ruby::get().expect("Failed to get a handle to Ruby API when registering Promise callback");
|
||||||
let fiber = Opaque::from(ruby.fiber_current());
|
let fiber = Opaque::from(ruby.fiber_current().as_value());
|
||||||
promise
|
if let Some(value) = &promise.inner.try_lock().unwrap().resolved_value {
|
||||||
.clone()
|
panic!();
|
||||||
.then(RubyValue::new(
|
}
|
||||||
ruby.proc_from_fn(move |ruby, args, _| {
|
promise.clone().await_promise(RubyValue(fiber)).into_value();
|
||||||
let fiber = ruby.get_inner(fiber);
|
|
||||||
fiber.resume::<_, magnus::Value>(args).unwrap();
|
|
||||||
})
|
|
||||||
.as_value(),
|
|
||||||
))
|
|
||||||
.into_value();
|
|
||||||
ruby.fiber_yield::<_, magnus::Value>(()).unwrap()
|
ruby.fiber_yield::<_, magnus::Value>(()).unwrap()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -457,7 +451,7 @@ impl Runtime for RubyRuntime {
|
||||||
Self::CallContext,
|
Self::CallContext,
|
||||||
Vec<Self::Value>,
|
Vec<Self::Value>,
|
||||||
) -> Result<
|
) -> Result<
|
||||||
crate::promise::Promise<Self::CallContext, Self::Value>,
|
crate::promise::Promise<Self::CallContext, Self::Value, Self::Value>,
|
||||||
crate::ScriptingError,
|
crate::ScriptingError,
|
||||||
> + Send
|
> + Send
|
||||||
+ Sync
|
+ Sync
|
||||||
|
|
@ -467,9 +461,10 @@ impl Runtime for RubyRuntime {
|
||||||
dyn Fn(
|
dyn Fn(
|
||||||
(),
|
(),
|
||||||
Vec<RubyValue>,
|
Vec<RubyValue>,
|
||||||
)
|
) -> Result<
|
||||||
-> Result<crate::promise::Promise<(), RubyValue>, crate::ScriptingError>
|
crate::promise::Promise<(), RubyValue, RubyValue>,
|
||||||
+ Send,
|
crate::ScriptingError,
|
||||||
|
> + Send,
|
||||||
>;
|
>;
|
||||||
static RUBY_CALLBACKS: LazyLock<Mutex<HashMap<String, CallbackClosure>>> =
|
static RUBY_CALLBACKS: LazyLock<Mutex<HashMap<String, CallbackClosure>>> =
|
||||||
LazyLock::new(|| Mutex::new(HashMap::new()));
|
LazyLock::new(|| Mutex::new(HashMap::new()));
|
||||||
|
|
|
||||||
|
|
@ -89,6 +89,8 @@ pub(crate) fn init_callbacks<R: Runtime>(world: &mut World) -> Result<(), Script
|
||||||
move |context, params| {
|
move |context, params| {
|
||||||
let promise = Promise {
|
let promise = Promise {
|
||||||
inner: Arc::new(Mutex::new(PromiseInner {
|
inner: Arc::new(Mutex::new(PromiseInner {
|
||||||
|
resolved_value: None,
|
||||||
|
fibers: vec![],
|
||||||
callbacks: vec![],
|
callbacks: vec![],
|
||||||
context,
|
context,
|
||||||
})),
|
})),
|
||||||
|
|
@ -100,7 +102,7 @@ pub(crate) fn init_callbacks<R: Runtime>(world: &mut World) -> Result<(), Script
|
||||||
.expect("Failed to lock callback calls mutex");
|
.expect("Failed to lock callback calls mutex");
|
||||||
|
|
||||||
calls.push(FunctionCallEvent {
|
calls.push(FunctionCallEvent {
|
||||||
promise: promise.clone(),
|
promise: promise.clone(), // TODO: dont clone?
|
||||||
params,
|
params,
|
||||||
});
|
});
|
||||||
Ok(promise)
|
Ok(promise)
|
||||||
|
|
@ -142,7 +144,7 @@ pub(crate) fn process_calls<R: Runtime>(world: &mut World) -> Result<(), Scripti
|
||||||
.lock()
|
.lock()
|
||||||
.expect("Failed to lock callback calls mutex")
|
.expect("Failed to lock callback calls mutex")
|
||||||
.drain(..)
|
.drain(..)
|
||||||
.collect::<Vec<FunctionCallEvent<R::CallContext, R::Value>>>();
|
.collect::<Vec<FunctionCallEvent<R::CallContext, R::Value, R::Value>>>();
|
||||||
for mut call in calls {
|
for mut call in calls {
|
||||||
tracing::trace!("process_calls: calling '{}'", callback.name);
|
tracing::trace!("process_calls: calling '{}'", callback.name);
|
||||||
let mut system = callback
|
let mut system = callback
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue