use bevy_ecs::{ptr::OwningPtr, query::QueryBuilder};
use bevy_mod_scripting_world::WorldGuard;
use super::{DynamicComponent, ReflectReference};
use crate::{WorldExtensions, error::InteropError};
use ::{
bevy_ecs::{
component::ComponentId,
entity::Entity,
query::{QueryData, QueryState},
reflect::ReflectComponent,
world::World,
},
bevy_reflect::{Reflect, TypeRegistration},
};
use std::{any::TypeId, ptr::NonNull, sync::Arc};
#[derive(Clone, Reflect)]
#[reflect(opaque)]
pub struct ScriptTypeRegistration {
pub(crate) registration: Arc<TypeRegistration>,
}
#[derive(Clone, Reflect, Debug)]
pub struct ScriptComponentRegistration {
pub registration: ScriptTypeRegistration,
pub component_id: ComponentId,
pub is_dynamic_script_component: bool,
}
#[derive(Clone, Reflect, Debug)]
pub struct ScriptResourceRegistration {
pub registration: ScriptTypeRegistration,
pub resource_id: ComponentId,
}
#[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 type_registration(&self) -> &TypeRegistration {
&self.registration
}
}
#[profiling::all_functions]
impl ScriptResourceRegistration {
pub 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 fn new(registration: ScriptTypeRegistration, component_id: ComponentId) -> Self {
Self {
is_dynamic_script_component: registration.type_id()
== std::any::TypeId::of::<DynamicComponent>(),
registration,
component_id,
}
}
#[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()))
})?;
let ptr = (Box::leak(cast) as *mut DynamicComponent).cast();
let non_null_ptr = unsafe { NonNull::new_unchecked(ptr) };
let owning_ptr = unsafe { OwningPtr::new(non_null_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(())
})?
}
}
}
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, Default, Reflect)]
#[reflect(opaque)]
pub struct ScriptQueryBuilder {
pub components: Vec<ScriptComponentRegistration>,
pub with: Vec<ScriptComponentRegistration>,
pub without: Vec<ScriptComponentRegistration>,
}
#[profiling::all_functions]
impl ScriptQueryBuilder {
pub fn new() -> Self {
Default::default()
}
pub fn components(&mut self, components: Vec<ScriptComponentRegistration>) -> &mut Self {
self.components.extend(components);
self
}
pub fn component(&mut self, component: ScriptComponentRegistration) -> &mut Self {
self.components.push(component);
self
}
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) -> QueryState<Q> {
let mut dynamic_query = QueryBuilder::<Q>::new(world);
for c in &self.components {
dynamic_query.ref_id(c.component_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)]
pub struct ScriptQueryResult {
pub entity: Entity,
pub components: Vec<ReflectReference>,
}