1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
use crate::AsyncOperation;
use async_channel::{Receiver, Sender};
use bevy_ecs::prelude::*;
use bevy_ecs::system::Command;
use bevy_reflect::prelude::*;
use bevy_reflect::TypeRegistry;
use std::any::TypeId;
use std::marker::PhantomData;

/// A `Resource`-related operation that can be applied to an `AsyncWorld`.
#[derive(Debug)]
#[non_exhaustive]
pub enum ResourceOperation {
	/// Insert the given boxed `Resource` into the `AsyncWorld`.
	Insert(Box<dyn Reflect>),
	/// Remove the `Resource` specified by `TypeId` from the `AsyncWorld`.
	Remove(TypeId),
	/// Wait for the `Resource` specified by the `TypeId` to exist in the `AsyncWorld`. As soon as
	/// the resource exists (or if it already exists), the value of the resource will be sent into
	/// the `Sender`.
	WaitFor(TypeId, Sender<Box<dyn Reflect>>),
}

impl Command for ResourceOperation {
	fn apply(self, world: &mut World) {
		world.resource_scope(|world, registry: Mut<AppTypeRegistry>| {
			let registry = registry.read();
			match self {
				ResourceOperation::Insert(boxed) => {
					let reflect_resource = get_reflect_resource(&registry, boxed.type_id());
					reflect_resource.apply_or_insert(world, boxed.as_reflect());
				}
				ResourceOperation::Remove(type_id) => {
					let reflect_resource = get_reflect_resource(&registry, type_id);
					reflect_resource.remove(world);
				}
				ResourceOperation::WaitFor(type_id, sender) => {
					let reflect_resource = get_reflect_resource(&registry, type_id);
					if let Some(reflect) = reflect_resource.reflect(world) {
						sender
							.try_send(reflect.clone_value())
							.expect("invariant broken");
					} else {
						world.spawn(WaitingFor(type_id, sender));
					}
				}
			}
		});
	}
}

impl From<ResourceOperation> for AsyncOperation {
	fn from(resource_op: ResourceOperation) -> Self {
		Self::Resource(resource_op)
	}
}

fn get_reflect_resource(registry: &TypeRegistry, type_id: TypeId) -> &ReflectResource {
	let type_registration = registry.get(type_id).expect("reflect type not registered");
	type_registration
		.data::<ReflectResource>()
		.expect("reflect type is not a resource")
}

#[derive(Component)]
pub(crate) struct WaitingFor(TypeId, Sender<Box<dyn Reflect>>);

pub(crate) fn wait_for_reflect_resources(
	mut commands: Commands,
	query: Query<(Entity, &WaitingFor)>,
	registry: Res<AppTypeRegistry>,
	world: &World,
) {
	let registry = registry.read();
	for (id, WaitingFor(type_id, sender)) in query.iter() {
		let reflect_resource = get_reflect_resource(&registry, *type_id);
		if let Some(reflect) = reflect_resource.reflect(world) {
			sender
				.try_send(reflect.clone_value())
				.expect("invariant broken");
			commands.entity(id).despawn();
		}
	}
}

/// Represents a `Resource` being retrieved.
#[derive(Debug)]
pub struct AsyncResource<R>(Receiver<Box<dyn Reflect>>, PhantomData<R>);

impl<R: Resource + FromReflect> AsyncResource<R> {
	pub(crate) fn new(receiver: Receiver<Box<dyn Reflect>>) -> Self {
		Self(receiver, PhantomData)
	}

	/// Wait for the `Resource` to exist, and retrieve its value.
	pub async fn wait(self) -> R {
		let boxed_dynamic = self.0.recv().await.expect("invariant broken");
		R::take_from_reflect(boxed_dynamic).expect("invariant broken")
	}
}

#[cfg(test)]
mod tests {
	use crate::{AsyncEcsPlugin, AsyncWorld};
	use bevy::prelude::*;
	use futures_lite::future;

	#[derive(Default, Resource, Reflect)]
	#[reflect(Resource)]
	struct Counter(u8);

	#[test]
	fn insert() {
		let mut app = App::new();
		app.add_plugins((MinimalPlugins, AsyncEcsPlugin));
		app.register_type::<Counter>();

		let async_world = AsyncWorld::from_world(&mut app.world);
		let (sender, receiver) = async_channel::bounded(1);

		std::thread::spawn(move || {
			future::block_on(async move {
				async_world.insert_resource(Counter(4)).await;
				sender.send(()).await.unwrap();
			});
		});

		loop {
			match receiver.try_recv() {
				Ok(_) => break,
				Err(_) => app.update(),
			}
		}
		app.update();

		assert_eq!(4, app.world.resource::<Counter>().0);
	}

	#[test]
	fn remove() {
		let mut app = App::new();
		app.add_plugins((MinimalPlugins, AsyncEcsPlugin));
		app.register_type::<Counter>();

		let async_world = AsyncWorld::from_world(&mut app.world);
		let (sender, receiver) = async_channel::bounded(1);
		app.insert_resource(Counter(7));

		std::thread::spawn(move || {
			future::block_on(async move {
				async_world.remove_resource::<Counter>().await;
				sender.send(()).await.unwrap();
			});
		});

		loop {
			match receiver.try_recv() {
				Ok(_) => break,
				Err(_) => app.update(),
			}
		}
		app.update();

		assert!(app.world.get_resource::<Counter>().is_none());
	}

	#[test]
	fn wait_for() {
		let mut app = App::new();
		app.add_plugins((MinimalPlugins, AsyncEcsPlugin));
		app.register_type::<Counter>();

		let async_world_1 = AsyncWorld::from_world(&mut app.world);
		let async_world_2 = async_world_1.clone();
		let (barrier_tx, barrier_rx) = async_channel::bounded(1);
		let (value_tx, value_rx) = async_channel::bounded(1);

		std::thread::spawn(move || {
			future::block_on(async move {
				let resource = async_world_1.start_waiting_for_resource::<Counter>().await;
				barrier_tx.send(()).await.unwrap();
				let counter = resource.wait().await;
				value_tx.send(counter.0).await.unwrap();
			});
		});

		std::thread::spawn(move || {
			future::block_on(async move {
				barrier_rx.recv().await.unwrap();
				async_world_2.insert_resource(Counter(3)).await;
			});
		});

		let value = loop {
			match value_rx.try_recv() {
				Ok(value) => break value,
				Err(_) => app.update(),
			}
		};
		app.update();

		assert_eq!(3, value);
	}

	#[test]
	fn wait_for_immediate() {
		let mut app = App::new();
		app.add_plugins((MinimalPlugins, AsyncEcsPlugin));
		app.register_type::<Counter>();

		app.insert_resource(Counter(1));

		let async_world = AsyncWorld::from_world(&mut app.world);
		let (value_tx, value_rx) = async_channel::bounded(1);

		std::thread::spawn(move || {
			future::block_on(async move {
				let counter = async_world.wait_for_resource::<Counter>().await;
				value_tx.send(counter.0).await.unwrap();
			});
		});

		let value = loop {
			match value_rx.try_recv() {
				Ok(value) => break value,
				Err(_) => app.update(),
			}
		};
		app.update();

		assert_eq!(1, value);
	}
}