use crate::render_phase::{PhaseItem, TrackedRenderPass};
use bevy_app::App;
use bevy_ecs::{
entity::Entity,
query::{QueryState, ROQueryItem, ReadOnlyWorldQuery},
system::{ReadOnlySystemParam, Resource, SystemParam, SystemParamItem, SystemState},
world::World,
};
use bevy_utils::{all_tuples, HashMap};
use std::{
any::TypeId,
fmt::Debug,
hash::Hash,
sync::{PoisonError, RwLock, RwLockReadGuard, RwLockWriteGuard},
};
pub trait Draw<P: PhaseItem>: Send + Sync + 'static {
#[allow(unused_variables)]
fn prepare(&mut self, world: &'_ World) {}
fn draw<'w>(
&mut self,
world: &'w World,
pass: &mut TrackedRenderPass<'w>,
view: Entity,
item: &P,
);
}
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
pub struct DrawFunctionId(u32);
pub struct DrawFunctionsInternal<P: PhaseItem> {
pub draw_functions: Vec<Box<dyn Draw<P>>>,
pub indices: HashMap<TypeId, DrawFunctionId>,
}
impl<P: PhaseItem> DrawFunctionsInternal<P> {
pub fn prepare(&mut self, world: &World) {
for function in &mut self.draw_functions {
function.prepare(world);
}
}
pub fn add<T: Draw<P>>(&mut self, draw_function: T) -> DrawFunctionId {
self.add_with::<T, T>(draw_function)
}
pub fn add_with<T: 'static, D: Draw<P>>(&mut self, draw_function: D) -> DrawFunctionId {
let id = DrawFunctionId(self.draw_functions.len().try_into().unwrap());
self.draw_functions.push(Box::new(draw_function));
self.indices.insert(TypeId::of::<T>(), id);
id
}
pub fn get_mut(&mut self, id: DrawFunctionId) -> Option<&mut dyn Draw<P>> {
self.draw_functions.get_mut(id.0 as usize).map(|f| &mut **f)
}
pub fn get_id<T: 'static>(&self) -> Option<DrawFunctionId> {
self.indices.get(&TypeId::of::<T>()).copied()
}
pub fn id<T: 'static>(&self) -> DrawFunctionId {
self.get_id::<T>().unwrap_or_else(|| {
panic!(
"Draw function {} not found for {}",
std::any::type_name::<T>(),
std::any::type_name::<P>()
)
})
}
}
#[derive(Resource)]
pub struct DrawFunctions<P: PhaseItem> {
internal: RwLock<DrawFunctionsInternal<P>>,
}
impl<P: PhaseItem> Default for DrawFunctions<P> {
fn default() -> Self {
Self {
internal: RwLock::new(DrawFunctionsInternal {
draw_functions: Vec::new(),
indices: HashMap::default(),
}),
}
}
}
impl<P: PhaseItem> DrawFunctions<P> {
pub fn read(&self) -> RwLockReadGuard<'_, DrawFunctionsInternal<P>> {
self.internal.read().unwrap_or_else(PoisonError::into_inner)
}
pub fn write(&self) -> RwLockWriteGuard<'_, DrawFunctionsInternal<P>> {
self.internal
.write()
.unwrap_or_else(PoisonError::into_inner)
}
}
pub trait RenderCommand<P: PhaseItem> {
type Param: SystemParam + 'static;
type ViewWorldQuery: ReadOnlyWorldQuery;
type ItemWorldQuery: ReadOnlyWorldQuery;
fn render<'w>(
item: &P,
view: ROQueryItem<'w, Self::ViewWorldQuery>,
entity: ROQueryItem<'w, Self::ItemWorldQuery>,
param: SystemParamItem<'w, '_, Self::Param>,
pass: &mut TrackedRenderPass<'w>,
) -> RenderCommandResult;
}
pub enum RenderCommandResult {
Success,
Failure,
}
macro_rules! render_command_tuple_impl {
($(($name: ident, $view: ident, $entity: ident)),*) => {
impl<P: PhaseItem, $($name: RenderCommand<P>),*> RenderCommand<P> for ($($name,)*) {
type Param = ($($name::Param,)*);
type ViewWorldQuery = ($($name::ViewWorldQuery,)*);
type ItemWorldQuery = ($($name::ItemWorldQuery,)*);
#[allow(non_snake_case)]
fn render<'w>(
_item: &P,
($($view,)*): ROQueryItem<'w, Self::ViewWorldQuery>,
($($entity,)*): ROQueryItem<'w, Self::ItemWorldQuery>,
($($name,)*): SystemParamItem<'w, '_, Self::Param>,
_pass: &mut TrackedRenderPass<'w>,
) -> RenderCommandResult {
$(if let RenderCommandResult::Failure = $name::render(_item, $view, $entity, $name, _pass) {
return RenderCommandResult::Failure;
})*
RenderCommandResult::Success
}
}
};
}
all_tuples!(render_command_tuple_impl, 0, 15, C, V, E);
pub struct RenderCommandState<P: PhaseItem + 'static, C: RenderCommand<P>> {
state: SystemState<C::Param>,
view: QueryState<C::ViewWorldQuery>,
entity: QueryState<C::ItemWorldQuery>,
}
impl<P: PhaseItem, C: RenderCommand<P>> RenderCommandState<P, C> {
pub fn new(world: &mut World) -> Self {
Self {
state: SystemState::new(world),
view: world.query(),
entity: world.query(),
}
}
}
impl<P: PhaseItem, C: RenderCommand<P> + Send + Sync + 'static> Draw<P> for RenderCommandState<P, C>
where
C::Param: ReadOnlySystemParam,
{
fn prepare(&mut self, world: &'_ World) {
self.state.update_archetypes(world);
self.view.update_archetypes(world);
self.entity.update_archetypes(world);
}
fn draw<'w>(
&mut self,
world: &'w World,
pass: &mut TrackedRenderPass<'w>,
view: Entity,
item: &P,
) {
let param = self.state.get_manual(world);
let view = self.view.get_manual(world, view).unwrap();
let entity = self.entity.get_manual(world, item.entity()).unwrap();
C::render(item, view, entity, param, pass);
}
}
pub trait AddRenderCommand {
fn add_render_command<P: PhaseItem, C: RenderCommand<P> + Send + Sync + 'static>(
&mut self,
) -> &mut Self
where
C::Param: ReadOnlySystemParam;
}
impl AddRenderCommand for App {
fn add_render_command<P: PhaseItem, C: RenderCommand<P> + Send + Sync + 'static>(
&mut self,
) -> &mut Self
where
C::Param: ReadOnlySystemParam,
{
let draw_function = RenderCommandState::<P, C>::new(&mut self.world);
let draw_functions = self
.world
.get_resource::<DrawFunctions<P>>()
.unwrap_or_else(|| {
panic!(
"DrawFunctions<{}> must be added to the world as a resource \
before adding render commands to it",
std::any::type_name::<P>(),
);
});
draw_functions.write().add_with::<C, _>(draw_function);
self
}
}