use bevy_ecs::{ptr::OwningPtr, query::QueryBuilder};
use bevy_mod_scripting_world::WorldGuard;
use super::{DynamicComponent, ReflectReference};
use crate::{
GetTypeDependencies, IntoScript, PartialReflectExt, ReflectNoTypeFunctions, ScriptValue,
ThroughTypeInfo, TypedThrough, WorldExtensions,
error::InteropError,
function::{
from::{Union, V},
from_ref::FromScriptErased,
},
};
use ::{
bevy_ecs::{
change_detection::Tick,
component::ComponentId,
entity::Entity,
query::{QueryData, QueryState},
reflect::{ReflectBundle, ReflectComponent, ReflectFromWorld},
world::{World, unsafe_world_cell::UnsafeEntityCell},
},
bevy_reflect::{
PartialReflect, Reflect, ReflectFromReflect, TypeRegistration, std_traits::ReflectDefault,
},
};
use std::{any::TypeId, collections::VecDeque, sync::Arc};
#[derive(Clone, Reflect)]
#[reflect(opaque, NoTypeFunctions)]
pub struct ScriptTypeRegistration {
pub(crate) registration: Arc<TypeRegistration>,
}
#[derive(Clone, Reflect, Debug)]
#[reflect(opaque, NoTypeFunctions)]
pub struct ScriptComponentRegistration {
pub(crate) registration: ScriptTypeRegistration,
pub(crate) component_id: ComponentId,
pub(crate) is_dynamic_script_component: bool,
pub(crate) script_namespace: Option<String>,
}
#[derive(Clone, Reflect, Debug)]
#[reflect(opaque, NoTypeFunctions)]
pub struct ScriptResourceRegistration {
pub(crate) registration: ScriptTypeRegistration,
pub(crate) resource_id: ComponentId,
}
#[derive(Clone, Reflect, Debug)]
#[reflect(opaque, NoTypeFunctions)]
pub struct ScriptBundleRegistration {
pub registration: ScriptTypeRegistration,
}
pub type AnyTypeRegistration = Union<
ScriptTypeRegistration,
Union<ScriptComponentRegistration, Union<ScriptResourceRegistration, ScriptBundleRegistration>>,
>;
pub type AnyTypeRegistrationV = Union<
V<ScriptTypeRegistration>,
Union<
V<ScriptComponentRegistration>,
Union<V<ScriptResourceRegistration>, V<ScriptBundleRegistration>>,
>,
>;
impl AnyTypeRegistration {
pub fn into_script(self) -> AnyTypeRegistrationV {
self.map_both(V, |other| other.map_both(V, |other| other.map_both(V, V)))
}
}
impl AnyTypeRegistrationV {
pub fn into_type_registration(self) -> ScriptTypeRegistration {
match self.into_left() {
Ok(registration) => registration.into_inner(),
Err(other) => match other.into_left() {
Ok(component) => component.into_inner().into_type_registration(),
Err(other) => match other.into_left() {
Ok(resource) => resource.into_inner().into_type_registration(),
Err(bundle) => bundle.into_inner().into_type_registration(),
},
},
}
}
}
#[profiling::all_functions]
impl ScriptTypeRegistration {
pub fn new(registration: Arc<TypeRegistration>) -> Self {
Self { registration }
}
#[inline(always)]
pub fn short_name(&self) -> &'static str {
self.registration.type_info().type_path_table().short_path()
}
#[inline(always)]
pub fn type_name(&self) -> &'static str {
self.registration.type_info().type_path_table().path()
}
#[inline(always)]
pub fn type_id(&self) -> TypeId {
self.registration.type_info().type_id()
}
pub fn namespace(&self) -> &str {
match self.registration.data::<crate::ScriptNamespace>() {
Some(namespace) => namespace.0.as_ref(),
None => self
.registration
.type_info()
.type_path_table()
.crate_name()
.unwrap_or(""),
}
}
pub fn type_registration(&self) -> &TypeRegistration {
&self.registration
}
}
#[profiling::all_functions]
impl ScriptResourceRegistration {
pub unsafe fn new(registration: ScriptTypeRegistration, resource_id: ComponentId) -> Self {
Self {
registration,
resource_id,
}
}
#[inline(always)]
pub fn resource_id(&self) -> ComponentId {
self.resource_id
}
pub fn type_registration(&self) -> &ScriptTypeRegistration {
&self.registration
}
pub fn into_type_registration(self) -> ScriptTypeRegistration {
self.registration
}
}
#[profiling::all_functions]
impl ScriptComponentRegistration {
pub unsafe fn new(registration: ScriptTypeRegistration, component_id: ComponentId) -> Self {
Self {
is_dynamic_script_component: registration.type_id()
== std::any::TypeId::of::<DynamicComponent>(),
registration,
component_id,
script_namespace: None,
}
}
pub fn namespace(&self) -> &str {
match (&self.script_namespace, self.is_dynamic_script_component) {
(Some(namespace), _) => namespace,
(None, true) => "",
(None, false) => self.registration.namespace(),
}
}
#[inline(always)]
pub fn component_id(&self) -> ComponentId {
self.component_id
}
pub fn type_registration(&self) -> &ScriptTypeRegistration {
&self.registration
}
pub fn into_type_registration(self) -> ScriptTypeRegistration {
self.registration
}
pub fn remove_from_entity(
&self,
world: WorldGuard,
entity: Entity,
) -> Result<(), InteropError> {
world.with_world_mut(|world| {
let mut entity = world
.get_entity_mut(entity)
.map_err(|_| InteropError::missing_entity(entity))?;
entity.remove_by_id(self.component_id);
Ok(())
})?
}
pub fn insert_into_entity(
&self,
world: WorldGuard,
entity: Entity,
instance: Box<dyn Reflect>,
) -> Result<(), InteropError> {
if self.is_dynamic_script_component {
world.with_world_mut(|world| {
let mut entity = world
.get_entity_mut(entity)
.map_err(|_| InteropError::missing_entity(entity))?;
let cast = instance.downcast::<DynamicComponent>().map_err(|v| {
InteropError::type_mismatch(TypeId::of::<DynamicComponent>(), Some(v.type_id()))
})?;
OwningPtr::make(*cast, |owning_ptr| {
unsafe { entity.insert_by_id(self.component_id, owning_ptr) };
});
Ok(())
})?
} else {
let component_data = self
.type_registration()
.type_registration()
.data::<ReflectComponent>()
.ok_or_else(|| {
InteropError::missing_type_data(
self.registration.type_id(),
"ReflectComponent".to_owned(),
)
})?;
let type_registry = world.type_registry();
world.with_world_mut(|world| {
let mut entity = world
.get_entity_mut(entity)
.map_err(|_| InteropError::missing_entity(entity))?;
{
let registry = type_registry.read();
component_data.insert(&mut entity, instance.as_partial_reflect(), ®istry);
}
Ok(())
})?
}
}
}
#[profiling::all_functions]
impl ScriptBundleRegistration {
pub fn namespace(&self) -> &str {
self.registration.namespace()
}
pub fn new(registration: ScriptTypeRegistration) -> Self {
Self { registration }
}
pub fn type_registration(&self) -> &ScriptTypeRegistration {
&self.registration
}
pub fn into_type_registration(self) -> ScriptTypeRegistration {
self.registration
}
fn reflect_bundle(&self) -> Result<&ReflectBundle, InteropError> {
self.registration
.type_registration()
.data::<ReflectBundle>()
.ok_or_else(|| {
InteropError::missing_type_data(
self.registration.type_id(),
"ReflectBundle".to_owned(),
)
})
}
pub fn instance_from_script(
&self,
world: WorldGuard,
value: ScriptValue,
) -> Result<Box<dyn Reflect>, InteropError> {
let type_id = self.registration.type_id();
let instance =
<Box<dyn PartialReflect>>::from_script_erased(type_id, value, world.clone())?;
let instance = match instance.try_into_reflect() {
Ok(instance) if instance.as_any().type_id() == type_id => instance,
Ok(instance) => {
<dyn PartialReflect>::from_reflect(instance.as_partial_reflect(), world)?
}
Err(instance) => <dyn PartialReflect>::from_reflect(instance.as_ref(), world)?,
};
Ok(instance)
}
pub fn insert_into_entity(
&self,
world: WorldGuard,
entity: Entity,
instance: Box<dyn Reflect>,
) -> Result<(), InteropError> {
let reflect_bundle = self.reflect_bundle()?;
let type_registration = self.registration.type_registration();
if instance.as_any().type_id() != self.registration.type_id() {
return Err(InteropError::type_mismatch(
self.registration.type_id(),
Some(instance.as_any().type_id()),
));
}
if type_registration.data::<ReflectFromReflect>().is_none()
&& type_registration.data::<ReflectDefault>().is_none()
&& type_registration.data::<ReflectFromWorld>().is_none()
{
return Err(InteropError::missing_type_data(
self.registration.type_id(),
"ReflectFromReflect, ReflectDefault or ReflectFromWorld".to_owned(),
));
}
let type_registry = world.type_registry();
world.with_world_mut(|world| {
let mut entity = world
.get_entity_mut(entity)
.map_err(|_| InteropError::missing_entity(entity))?;
let registry = type_registry.read();
reflect_bundle.insert(&mut entity, instance.as_partial_reflect(), ®istry);
Ok(())
})?
}
}
impl std::fmt::Debug for ScriptTypeRegistration {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_tuple("ScriptTypeRegistration")
.field(&self.registration.type_info().type_path())
.finish()
}
}
impl std::fmt::Display for ScriptTypeRegistration {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.registration.type_info().type_path())
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum QueryAccess {
MatchOnly,
Declared,
}
#[derive(Clone, Default, Reflect)]
#[reflect(opaque)]
pub struct ScriptQueryBuilder {
pub components: Vec<ScriptComponentRegistration>,
writes: Vec<bool>,
optionals: Vec<bool>,
pub with: Vec<ScriptComponentRegistration>,
pub without: Vec<ScriptComponentRegistration>,
pub added: Vec<ScriptComponentRegistration>,
pub changed: Vec<ScriptComponentRegistration>,
}
#[profiling::all_functions]
impl ScriptQueryBuilder {
pub fn new() -> Self {
Default::default()
}
pub fn components(&mut self, components: Vec<ScriptComponentRegistration>) -> &mut Self {
for component in components {
self.component(component);
}
self
}
pub fn component(&mut self, component: ScriptComponentRegistration) -> &mut Self {
self.push_component(component, true, false)
}
pub fn component_read(&mut self, component: ScriptComponentRegistration) -> &mut Self {
self.push_component(component, false, false)
}
pub fn optional(&mut self, component: ScriptComponentRegistration) -> &mut Self {
self.push_component(component, true, true)
}
pub fn optional_read(&mut self, component: ScriptComponentRegistration) -> &mut Self {
self.push_component(component, false, true)
}
fn push_component(
&mut self,
component: ScriptComponentRegistration,
write: bool,
optional: bool,
) -> &mut Self {
self.writes.resize(self.components.len(), true);
self.optionals.resize(self.components.len(), false);
self.components.push(component);
self.writes.push(write);
self.optionals.push(optional);
self
}
pub fn is_written(&self, index: usize) -> bool {
self.writes.get(index).copied().unwrap_or(true)
}
pub fn is_optional(&self, index: usize) -> bool {
self.optionals.get(index).copied().unwrap_or(false)
}
pub fn added_component(&mut self, component: ScriptComponentRegistration) -> &mut Self {
self.added.push(component);
self
}
pub fn changed_component(&mut self, component: ScriptComponentRegistration) -> &mut Self {
self.changed.push(component);
self
}
pub fn accessed_components(&self) -> impl Iterator<Item = (ComponentId, bool)> + '_ {
self.components
.iter()
.enumerate()
.map(|(index, c)| (c.component_id(), self.is_written(index)))
.chain(
self.added
.iter()
.chain(&self.changed)
.map(|c| (c.component_id(), false)),
)
}
pub unsafe fn result_for(
&self,
entity: UnsafeEntityCell,
last_run: Tick,
this_run: Tick,
) -> Option<ScriptQueryResult> {
let ticks = |c: &ScriptComponentRegistration| unsafe {
entity.get_change_ticks_by_id(c.component_id())
};
let passes = self
.added
.iter()
.all(|c| ticks(c).is_some_and(|t| t.is_added(last_run, this_run)))
&& self
.changed
.iter()
.all(|c| ticks(c).is_some_and(|t| t.is_changed(last_run, this_run)));
if !passes {
return None;
}
let components = self
.components
.iter()
.enumerate()
.map(|(index, c)| {
(!self.is_optional(index) || entity.contains_id(c.component_id())).then(|| {
unsafe {
ReflectReference::new_component_ref_by_id(
entity.id(),
c.component_id(),
c.type_registration().type_id(),
)
}
})
})
.collect();
Some(ScriptQueryResult {
entity: entity.id(),
components,
})
}
pub fn with_components(&mut self, with: Vec<ScriptComponentRegistration>) -> &mut Self {
self.with.extend(with);
self
}
pub fn with_component(&mut self, with: ScriptComponentRegistration) -> &mut Self {
self.with.push(with);
self
}
pub fn without_components(&mut self, without: Vec<ScriptComponentRegistration>) -> &mut Self {
self.without.extend(without);
self
}
pub fn without_component(&mut self, without: ScriptComponentRegistration) -> &mut Self {
self.without.push(without);
self
}
pub fn as_query_state<Q: QueryData>(
&self,
world: &mut World,
access: QueryAccess,
) -> QueryState<Q> {
let mut dynamic_query = QueryBuilder::<Q>::new(world);
for (index, c) in self.components.iter().enumerate() {
let write = access == QueryAccess::Declared && self.is_written(index);
let id = c.component_id();
if self.is_optional(index) {
dynamic_query.optional(|optional| {
if write {
optional.mut_id(id);
} else {
optional.ref_id(id);
}
});
} else if write {
dynamic_query.mut_id(id);
} else {
dynamic_query.ref_id(id);
}
}
for c in self.added.iter().chain(&self.changed) {
let id = c.component_id();
dynamic_query.with_id(id);
let retrieved = self
.components
.iter()
.enumerate()
.any(|(index, other)| other.component_id() == id && !self.is_optional(index));
if !retrieved {
dynamic_query.ref_id(id);
}
}
for w in &self.with {
dynamic_query.with_id(w.component_id());
}
for without_id in &self.without {
dynamic_query.without_id(without_id.component_id());
}
dynamic_query.build()
}
}
#[derive(Clone, Reflect)]
#[reflect(opaque, NoTypeFunctions)]
pub struct ScriptQueryResult {
pub entity: Entity,
pub components: Vec<Option<ReflectReference>>,
}
impl IntoScript for ScriptQueryResult {
fn into_script(self, _world: WorldGuard) -> Result<ScriptValue, InteropError> {
let mut values = VecDeque::with_capacity(self.components.len() + 1);
values.push_back(V(self.entity).into_script(_world)?);
values.extend(
self.components
.into_iter()
.map(|c| c.map_or(ScriptValue::Unit, ScriptValue::Reference)),
);
Ok(ScriptValue::List(values))
}
}
impl TypedThrough for ScriptQueryResult {
fn through_type_info() -> ThroughTypeInfo {
ThroughTypeInfo::TupleWithRest {
head: vec![V::<Entity>::through_type_info()],
rest: Box::new(Option::<ReflectReference>::through_type_info()),
}
}
}
impl GetTypeDependencies for ScriptQueryResult {
type Underlying = Self;
fn register_type_dependencies(registry: &mut bevy_reflect::TypeRegistry) {
registry.register::<ScriptQueryResult>();
}
}