-
-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathmod.rs
293 lines (241 loc) · 9.32 KB
/
mod.rs
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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
use std::{
ops::{Deref, DerefMut},
sync::Arc,
};
use crate::ScriptRef;
/// Common functionality for all script hosts
use bevy::{
ecs::system::Command,
prelude::{
AppTypeRegistry, BuildWorldChildren, Children, DespawnChildrenRecursive, DespawnRecursive,
Entity, Parent, ReflectComponent, ReflectDefault, ReflectResource,
},
reflect::{
DynamicArray, DynamicEnum, DynamicList, DynamicMap, DynamicStruct, DynamicTuple,
DynamicTupleStruct, TypeRegistration,
},
};
use bevy_mod_scripting_core::{prelude::ScriptError, world::WorldPointer};
/// Helper trait for retrieving a world pointer from a script context.
pub trait GetWorld {
type Error;
fn get_world(&self) -> Result<WorldPointer, Self::Error>;
}
#[derive(Clone)]
pub struct ScriptTypeRegistration(pub(crate) Arc<TypeRegistration>);
impl ScriptTypeRegistration {
pub fn new(arc: Arc<TypeRegistration>) -> Self {
Self(arc)
}
#[inline(always)]
pub fn short_name(&self) -> &str {
self.0.short_name()
}
#[inline(always)]
pub fn type_name(&self) -> &'static str {
self.0.type_name()
}
}
impl std::fmt::Debug for ScriptTypeRegistration {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_tuple("ScriptTypeRegistration")
.field(&self.0.type_name())
.finish()
}
}
impl std::fmt::Display for ScriptTypeRegistration {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.0.short_name())
}
}
impl Deref for ScriptTypeRegistration {
type Target = TypeRegistration;
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[derive(Clone, Debug)]
pub struct ScriptWorld(WorldPointer);
impl std::fmt::Display for ScriptWorld {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("World")
}
}
impl Deref for ScriptWorld {
type Target = WorldPointer;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl DerefMut for ScriptWorld {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl AsRef<WorldPointer> for ScriptWorld {
fn as_ref(&self) -> &WorldPointer {
&self.0
}
}
impl From<ScriptWorld> for WorldPointer {
fn from(val: ScriptWorld) -> Self {
val.0
}
}
impl ScriptWorld {
pub fn new(ptr: WorldPointer) -> Self {
Self(ptr)
}
pub fn get_children(&self, parent: Entity) -> Vec<Entity> {
let w = self.read();
w.get::<Children>(parent)
.map(|v| v.to_vec())
.unwrap_or_default()
}
pub fn get_parent(&self, entity: Entity) -> Option<Entity> {
let w = self.read();
w.get::<Parent>(entity).map(|parent| parent.get())
}
pub fn push_child(&self, parent: Entity, child: Entity) {
let mut w = self.write();
if let Some(mut entity) = w.get_entity_mut(parent) {
entity.push_children(&[child]);
}
}
pub fn remove_children(&self, parent: Entity, children: &[Entity]) {
let mut w = self.write();
if let Some(mut entity) = w.get_entity_mut(parent) {
entity.remove_children(children);
}
}
pub fn insert_children(&self, parent: Entity, index: usize, children: &[Entity]) {
let mut w = self.write();
if let Some(mut entity) = w.get_entity_mut(parent) {
entity.insert_children(index, children);
}
}
pub fn despawn_children_recursive(&self, entity: Entity) {
let mut w = self.write();
DespawnChildrenRecursive { entity }.apply(&mut w);
}
pub fn despawn_recursive(&self, entity: Entity) {
let mut w = self.write();
DespawnRecursive { entity }.apply(&mut w);
}
pub fn get_type_by_name(&self, type_name: &str) -> Option<ScriptTypeRegistration> {
let w = self.read();
let registry: &AppTypeRegistry = w.get_resource().unwrap();
let registry = registry.read();
registry
.get_with_short_name(type_name)
.or_else(|| registry.get_with_name(type_name))
.map(|registration| ScriptTypeRegistration::new(Arc::new(registration.clone())))
}
pub fn add_default_component(
&self,
entity: Entity,
comp_type: ScriptTypeRegistration,
) -> Result<ScriptRef, ScriptError> {
let mut w = self.write();
let mut entity_ref = w
.get_entity_mut(entity)
.ok_or_else(|| ScriptError::Other(format!("Entity is not valid {:#?}", entity)))?;
let component_data = comp_type.data::<ReflectComponent>().ok_or_else(|| {
ScriptError::Other(format!("Not a component {}", comp_type.short_name()))
})?;
// this is just a formality
// TODO: maybe get an add_default impl added to ReflectComponent
// this means that we don't require ReflectDefault for adding components!
match comp_type.0.type_info(){
bevy::reflect::TypeInfo::Struct(_) => component_data.insert(&mut entity_ref, &DynamicStruct::default()),
bevy::reflect::TypeInfo::TupleStruct(_) => component_data.insert(&mut entity_ref, &DynamicTupleStruct::default()),
bevy::reflect::TypeInfo::Tuple(_) => component_data.insert(&mut entity_ref, &DynamicTuple::default()),
bevy::reflect::TypeInfo::List(_) => component_data.insert(&mut entity_ref, &DynamicList::default()),
bevy::reflect::TypeInfo::Array(_) => component_data.insert(&mut entity_ref, &DynamicArray::new(Box::new([]))),
bevy::reflect::TypeInfo::Map(_) => component_data.insert(&mut entity_ref, &DynamicMap::default()),
bevy::reflect::TypeInfo::Value(_) => component_data.insert(&mut entity_ref,
comp_type.data::<ReflectDefault>().ok_or_else(||
ScriptError::Other(format!("Component {} is a value or dynamic type with no `ReflectDefault` type_data, cannot instantiate sensible value",comp_type.short_name())))?
.default()
.as_ref()),
bevy::reflect::TypeInfo::Enum(_) => component_data.insert(&mut entity_ref, &DynamicEnum::default())
};
Ok(ScriptRef::new_component_ref(
component_data.clone(),
entity,
self.clone().into(),
))
}
pub fn get_component(
&self,
entity: Entity,
comp_type: ScriptTypeRegistration,
) -> Result<Option<ScriptRef>, ScriptError> {
let w = self.read();
let entity_ref = w
.get_entity(entity)
.ok_or_else(|| ScriptError::Other(format!("Entity is not valid {:#?}", entity)))?;
let component_data = comp_type.data::<ReflectComponent>().ok_or_else(|| {
ScriptError::Other(format!("Not a component {}", comp_type.short_name()))
})?;
Ok(component_data.reflect(entity_ref).map(|_component| {
ScriptRef::new_component_ref(component_data.clone(), entity, self.clone().into())
}))
}
pub fn has_component(
&self,
entity: Entity,
comp_type: ScriptTypeRegistration,
) -> Result<bool, ScriptError> {
let w = self.read();
let component_data = comp_type.data::<ReflectComponent>().ok_or_else(|| {
ScriptError::Other(format!("Not a component {}", comp_type.short_name()))
})?;
let entity_ref = w
.get_entity(entity)
.ok_or_else(|| ScriptError::Other(format!("Entity is not valid {:#?}", entity)))?;
Ok(component_data.reflect(entity_ref).is_some())
}
pub fn remove_component(
&mut self,
entity: Entity,
comp_type: ScriptTypeRegistration,
) -> Result<(), ScriptError> {
let mut w = self.write();
let mut entity_ref = w
.get_entity_mut(entity)
.ok_or_else(|| ScriptError::Other(format!("Entity is not valid {:#?}", entity)))?;
let component_data = comp_type.data::<ReflectComponent>().ok_or_else(|| {
ScriptError::Other(format!("Not a component {}", comp_type.short_name()))
})?;
component_data.remove(&mut entity_ref);
Ok(())
}
pub fn get_resource(
&self,
res_type: ScriptTypeRegistration,
) -> Result<Option<ScriptRef>, ScriptError> {
let w = self.read();
let resource_data = res_type.data::<ReflectResource>().ok_or_else(|| {
ScriptError::Other(format!("Not a resource {}", res_type.short_name()))
})?;
Ok(resource_data
.reflect(&w)
.map(|_res| ScriptRef::new_resource_ref(resource_data.clone(), self.clone().into())))
}
pub fn has_resource(&self, res_type: ScriptTypeRegistration) -> Result<bool, ScriptError> {
let w = self.read();
let resource_data = res_type.data::<ReflectResource>().ok_or_else(|| {
ScriptError::Other(format!("Not a resource {}", res_type.short_name()))
})?;
Ok(resource_data.reflect(&w).is_some())
}
pub fn remove_resource(&mut self, res_type: ScriptTypeRegistration) -> Result<(), ScriptError> {
let mut w = self.write();
let resource_data = res_type.data::<ReflectResource>().ok_or_else(|| {
ScriptError::Other(format!("Not a resource {}", res_type.short_name()))
})?;
resource_data.remove(&mut w);
Ok(())
}
}