Skip to content

Commit

Permalink
Merge branch 'main' of https://github.com/mintlu8/bevy_defer
Browse files Browse the repository at this point in the history
  • Loading branch information
mintlu8 committed May 11, 2024
2 parents 254d349 + 7c00f34 commit 4fdb5af
Show file tree
Hide file tree
Showing 9 changed files with 144 additions and 117 deletions.
2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,8 @@ bevy_ui = { version = "0.13.1", optional = true }
bevy_scene = { version = "0.13.1", optional = true }
async-oneshot = "0.5.9"
scoped-tls-hkt = "0.1.4"
event-listener = "5.3.0"
event-listener-strategy = "0.5.2"

[dev-dependencies]
bevy = { version = "0.13.0" }
Expand Down
13 changes: 9 additions & 4 deletions examples/ui.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@ use bevy::prelude::*;
use bevy_defer::ext::picking::{
react_to_ui, ClickCancelled, Clicked, LostFocus, ObtainedFocus, Pressed, UIInteractionChange,
};
use bevy_defer::reactors::StateMachine;
use bevy_defer::signals::Signal;
use bevy_defer::AsyncAccess;
use bevy_defer::{async_system, async_systems::AsyncSystems, signals::Signals, AsyncPlugin};
use bevy_tasks::futures_lite::StreamExt;
use bevy_ui::RelativeCursorPosition;

fn main() {
Expand Down Expand Up @@ -123,10 +125,13 @@ fn setup(mut commands: Commands) {
),
Signals::from_receiver::<UIInteractionChange>(state),
AsyncSystems::from_single(async_system!(
|click: Receiver<UIInteractionChange>, this: AsyncComponent<Text>| {
let variant = format!("{:?}", click.await.to);
this.set(move |text| text.sections[0].value = variant)
.unwrap();
|click: StateMachine<Interaction>, this: AsyncComponent<Text>| {
let mut stream = click.into_stream();
while let Some(item) = stream.next().await {
let variant = format!("{:?}", item.to);
this.set(move |text| text.sections[0].value = variant)
.unwrap();
}
}
)),
));
Expand Down
1 change: 0 additions & 1 deletion picking/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ bevy_defer = { version = "0.11.0", path = ".." }
bevy_ecs = "0.13.2"
bevy_math = "0.13.2"
bevy_mod_picking = { version = "0.18.2", default-features = false, features = ["selection"] }
ref-cast = "1.0.22"
rustc-hash = "1.1.0"

[dev-dependencies]
Expand Down
7 changes: 4 additions & 3 deletions src/commands.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use crate::executor::{with_world_mut, with_world_ref, QUERY_QUEUE, REACTORS};
use crate::signals::SignalStream;
use crate::{
access::AsyncEntityMut,
reactors::StateSignal,
Expand All @@ -17,7 +18,7 @@ use bevy_ecs::{
};
use bevy_utils::Duration;
use futures::future::Either;
use futures::{future::ready, Stream};
use futures::future::ready;
use rustc_hash::FxHashMap;
use std::{
any::{Any, TypeId},
Expand Down Expand Up @@ -334,10 +335,10 @@ impl AsyncWorld {
/// Obtain a [`Stream`] that reacts to changes of a [`States`].
///
/// Requires system [`react_to_state`](crate::systems::react_to_state).
pub fn state_stream<S: States + Clone + Default>(&self) -> impl Stream<Item = S> + 'static {
pub fn state_stream<S: States + Clone + Default>(&self) -> SignalStream<S> {
let signal = self.typed_signal::<StateSignal<S>>();
signal.rewind();
signal
signal.into_stream()
}

/// Pause the future for the duration, according to the `Time` resource.
Expand Down
21 changes: 6 additions & 15 deletions src/reactors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,13 @@ use std::{
cell::OnceCell,
convert::Infallible,
marker::PhantomData,
ops::Deref,
sync::Arc,
};

use crate::access::async_event::DoubleBufferedEvent;
use crate::signals::{Receiver, Signal, SignalId, SignalSender, Signals};

/// Signal sending changed value of a [`States`].
/// Signal that sends changed values of a [`States`].
#[derive(Debug, Clone, Copy)]
pub struct StateSignal<T: States + Clone + Default>(PhantomData<T>, Infallible);

Expand All @@ -35,17 +34,9 @@ impl<T: States + Clone + Default> SignalId for StateSignal<T> {
#[derive(Resource, Default, Clone)]
pub struct Reactors(Arc<ReactorsInner>);

impl Deref for Reactors {
type Target = ReactorsInner;

fn deref(&self) -> &Self::Target {
&self.0
}
}

/// Named or typed synchronization primitives of `bevy_defer`.
#[derive(Default)]
pub struct ReactorsInner {
pub(crate) struct ReactorsInner {
typed: Mutex<FxHashMap<TypeId, Box<dyn Any + Send + Sync>>>,
named: Mutex<FxHashMap<(String, TypeId), Box<dyn Any + Send + Sync>>>,
event_buffers: Mutex<FxHashMap<TypeId, Box<dyn Any + Send + Sync>>>,
Expand All @@ -60,11 +51,11 @@ impl std::fmt::Debug for ReactorsInner {
}
}

impl ReactorsInner {
impl Reactors {
/// Obtain a typed signal.
#[allow(clippy::box_default)]
pub fn get_typed<T: SignalId>(&self) -> Signal<T::Data> {
self.typed
self.0.typed
.lock()
.entry(TypeId::of::<T>())
.or_insert(Box::new(Signal::<T::Data>::default()))
Expand All @@ -75,7 +66,7 @@ impl ReactorsInner {

/// Obtain a named signal.
pub fn get_named<T: SignalId>(&self, name: impl Borrow<str> + Into<String>) -> Signal<T::Data> {
let mut lock = self.named.lock();
let mut lock = self.0.named.lock();
if let Some(data) = lock.get(&(name.borrow(), TypeId::of::<T>()) as &dyn NameAndType) {
data.downcast_ref::<Signal<T::Data>>()
.expect("Unexpected signal type.")
Expand All @@ -89,7 +80,7 @@ impl ReactorsInner {

/// Obtain an event buffer by event type.
pub fn get_event<E: Event + Clone>(&self) -> Arc<DoubleBufferedEvent<E>> {
let mut lock = self.event_buffers.lock();
let mut lock = self.0.event_buffers.lock();
if let Some(data) = lock.get(&TypeId::of::<E>()) {
data.downcast_ref::<Arc<DoubleBufferedEvent<E>>>()
.expect("Unexpected event buffer type.")
Expand Down
2 changes: 1 addition & 1 deletion src/signals/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,5 @@ mod signal_inner;
mod signal_utils;

pub use signal_component::Signals;
pub use signal_inner::{Signal, SignalBorrow, SignalInner};
pub use signal_inner::{Signal, SignalBorrow, SignalFuture, SignalStream};
pub use signal_utils::*;
2 changes: 1 addition & 1 deletion src/signals/signal_component.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use bevy_reflect::Reflect;
use rustc_hash::FxHashMap;
use std::any::{Any, TypeId};

/// A composable component that contains signals on an `Entity`.
/// A composable component that contains type-erased signals on an `Entity`.
#[derive(Debug, Component, Default, Reflect)]
pub struct Signals {
#[reflect(ignore)]
Expand Down
Loading

0 comments on commit 4fdb5af

Please sign in to comment.