bevy_render/render_phase/
draw.rs

1use crate::render_phase::{PhaseItem, TrackedRenderPass};
2use bevy_app::{App, SubApp};
3use bevy_ecs::{
4    entity::Entity,
5    query::{QueryState, ROQueryItem, ReadOnlyQueryData},
6    system::{ReadOnlySystemParam, Resource, SystemParam, SystemParamItem, SystemState},
7    world::World,
8};
9use bevy_utils::{all_tuples, TypeIdMap};
10use std::{
11    any::TypeId,
12    fmt::Debug,
13    hash::Hash,
14    sync::{PoisonError, RwLock, RwLockReadGuard, RwLockWriteGuard},
15};
16
17/// A draw function used to draw [`PhaseItem`]s.
18///
19/// The draw function can retrieve and query the required ECS data from the render world.
20///
21/// This trait can either be implemented directly or implicitly composed out of multiple modular
22/// [`RenderCommand`]s. For more details and an example see the [`RenderCommand`] documentation.
23pub trait Draw<P: PhaseItem>: Send + Sync + 'static {
24    /// Prepares the draw function to be used. This is called once and only once before the phase
25    /// begins. There may be zero or more [`draw`](Draw::draw) calls following a call to this function.
26    /// Implementing this is optional.
27    #[allow(unused_variables)]
28    fn prepare(&mut self, world: &'_ World) {}
29
30    /// Draws a [`PhaseItem`] by issuing zero or more `draw` calls via the [`TrackedRenderPass`].
31    fn draw<'w>(
32        &mut self,
33        world: &'w World,
34        pass: &mut TrackedRenderPass<'w>,
35        view: Entity,
36        item: &P,
37    );
38}
39
40// TODO: make this generic?
41/// An identifier for a [`Draw`] function stored in [`DrawFunctions`].
42#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord, Hash)]
43pub struct DrawFunctionId(u32);
44
45/// Stores all [`Draw`] functions for the [`PhaseItem`] type.
46///
47/// For retrieval, the [`Draw`] functions are mapped to their respective [`TypeId`]s.
48pub struct DrawFunctionsInternal<P: PhaseItem> {
49    pub draw_functions: Vec<Box<dyn Draw<P>>>,
50    pub indices: TypeIdMap<DrawFunctionId>,
51}
52
53impl<P: PhaseItem> DrawFunctionsInternal<P> {
54    /// Prepares all draw function. This is called once and only once before the phase begins.
55    pub fn prepare(&mut self, world: &World) {
56        for function in &mut self.draw_functions {
57            function.prepare(world);
58        }
59    }
60
61    /// Adds the [`Draw`] function and maps it to its own type.
62    pub fn add<T: Draw<P>>(&mut self, draw_function: T) -> DrawFunctionId {
63        self.add_with::<T, T>(draw_function)
64    }
65
66    /// Adds the [`Draw`] function and maps it to the type `T`
67    pub fn add_with<T: 'static, D: Draw<P>>(&mut self, draw_function: D) -> DrawFunctionId {
68        let id = DrawFunctionId(self.draw_functions.len().try_into().unwrap());
69        self.draw_functions.push(Box::new(draw_function));
70        self.indices.insert(TypeId::of::<T>(), id);
71        id
72    }
73
74    /// Retrieves the [`Draw`] function corresponding to the `id` mutably.
75    pub fn get_mut(&mut self, id: DrawFunctionId) -> Option<&mut dyn Draw<P>> {
76        self.draw_functions.get_mut(id.0 as usize).map(|f| &mut **f)
77    }
78
79    /// Retrieves the id of the [`Draw`] function corresponding to their associated type `T`.
80    pub fn get_id<T: 'static>(&self) -> Option<DrawFunctionId> {
81        self.indices.get(&TypeId::of::<T>()).copied()
82    }
83
84    /// Retrieves the id of the [`Draw`] function corresponding to their associated type `T`.
85    ///
86    /// Fallible wrapper for [`Self::get_id()`]
87    ///
88    /// ## Panics
89    /// If the id doesn't exist, this function will panic.
90    pub fn id<T: 'static>(&self) -> DrawFunctionId {
91        self.get_id::<T>().unwrap_or_else(|| {
92            panic!(
93                "Draw function {} not found for {}",
94                std::any::type_name::<T>(),
95                std::any::type_name::<P>()
96            )
97        })
98    }
99}
100
101/// Stores all draw functions for the [`PhaseItem`] type hidden behind a reader-writer lock.
102///
103/// To access them the [`DrawFunctions::read`] and [`DrawFunctions::write`] methods are used.
104#[derive(Resource)]
105pub struct DrawFunctions<P: PhaseItem> {
106    internal: RwLock<DrawFunctionsInternal<P>>,
107}
108
109impl<P: PhaseItem> Default for DrawFunctions<P> {
110    fn default() -> Self {
111        Self {
112            internal: RwLock::new(DrawFunctionsInternal {
113                draw_functions: Vec::new(),
114                indices: Default::default(),
115            }),
116        }
117    }
118}
119
120impl<P: PhaseItem> DrawFunctions<P> {
121    /// Accesses the draw functions in read mode.
122    pub fn read(&self) -> RwLockReadGuard<'_, DrawFunctionsInternal<P>> {
123        self.internal.read().unwrap_or_else(PoisonError::into_inner)
124    }
125
126    /// Accesses the draw functions in write mode.
127    pub fn write(&self) -> RwLockWriteGuard<'_, DrawFunctionsInternal<P>> {
128        self.internal
129            .write()
130            .unwrap_or_else(PoisonError::into_inner)
131    }
132}
133
134/// [`RenderCommand`]s are modular standardized pieces of render logic that can be composed into
135/// [`Draw`] functions.
136///
137/// To turn a stateless render command into a usable draw function it has to be wrapped by a
138/// [`RenderCommandState`].
139/// This is done automatically when registering a render command as a [`Draw`] function via the
140/// [`AddRenderCommand::add_render_command`] method.
141///
142/// Compared to the draw function the required ECS data is fetched automatically
143/// (by the [`RenderCommandState`]) from the render world.
144/// Therefore the three types [`Param`](RenderCommand::Param),
145/// [`ViewQuery`](RenderCommand::ViewQuery) and
146/// [`ItemQuery`](RenderCommand::ItemQuery) are used.
147/// They specify which information is required to execute the render command.
148///
149/// Multiple render commands can be combined together by wrapping them in a tuple.
150///
151/// # Example
152///
153/// The `DrawMaterial` draw function is created from the following render command
154/// tuple. Const generics are used to set specific bind group locations:
155///
156/// ```
157/// # use bevy_render::render_phase::SetItemPipeline;
158/// # struct SetMeshViewBindGroup<const N: usize>;
159/// # struct SetMeshBindGroup<const N: usize>;
160/// # struct SetMaterialBindGroup<M, const N: usize>(core::marker::PhantomData<M>);
161/// # struct DrawMesh;
162/// pub type DrawMaterial<M> = (
163///     SetItemPipeline,
164///     SetMeshViewBindGroup<0>,
165///     SetMeshBindGroup<1>,
166///     SetMaterialBindGroup<M, 2>,
167///     DrawMesh,
168/// );
169/// ```
170pub trait RenderCommand<P: PhaseItem> {
171    /// Specifies the general ECS data (e.g. resources) required by [`RenderCommand::render`].
172    ///
173    /// When fetching resources, note that, due to lifetime limitations of the `Deref` trait,
174    /// [`SRes::into_inner`] must be called on each [`SRes`] reference in the
175    /// [`RenderCommand::render`] method, instead of being automatically dereferenced as is the
176    /// case in normal `systems`.
177    ///
178    /// All parameters have to be read only.
179    ///
180    /// [`SRes`]: bevy_ecs::system::lifetimeless::SRes
181    /// [`SRes::into_inner`]: bevy_ecs::system::lifetimeless::SRes::into_inner
182    type Param: SystemParam + 'static;
183    /// Specifies the ECS data of the view entity required by [`RenderCommand::render`].
184    ///
185    /// The view entity refers to the camera, or shadow-casting light, etc. from which the phase
186    /// item will be rendered from.
187    /// All components have to be accessed read only.
188    type ViewQuery: ReadOnlyQueryData;
189    /// Specifies the ECS data of the item entity required by [`RenderCommand::render`].
190    ///
191    /// The item is the entity that will be rendered for the corresponding view.
192    /// All components have to be accessed read only.
193    ///
194    /// For efficiency reasons, Bevy doesn't always extract entities to the
195    /// render world; for instance, entities that simply consist of meshes are
196    /// often not extracted. If the entity doesn't exist in the render world,
197    /// the supplied query data will be `None`.
198    type ItemQuery: ReadOnlyQueryData;
199
200    /// Renders a [`PhaseItem`] by recording commands (e.g. setting pipelines, binding bind groups,
201    /// issuing draw calls, etc.) via the [`TrackedRenderPass`].
202    fn render<'w>(
203        item: &P,
204        view: ROQueryItem<'w, Self::ViewQuery>,
205        entity: Option<ROQueryItem<'w, Self::ItemQuery>>,
206        param: SystemParamItem<'w, '_, Self::Param>,
207        pass: &mut TrackedRenderPass<'w>,
208    ) -> RenderCommandResult;
209}
210
211/// The result of a [`RenderCommand`].
212#[derive(Debug)]
213pub enum RenderCommandResult {
214    Success,
215    Failure,
216}
217
218macro_rules! render_command_tuple_impl {
219    ($(($name: ident, $view: ident, $entity: ident)),*) => {
220        impl<P: PhaseItem, $($name: RenderCommand<P>),*> RenderCommand<P> for ($($name,)*) {
221            type Param = ($($name::Param,)*);
222            type ViewQuery = ($($name::ViewQuery,)*);
223            type ItemQuery = ($($name::ItemQuery,)*);
224
225            #[allow(non_snake_case)]
226            fn render<'w>(
227                _item: &P,
228                ($($view,)*): ROQueryItem<'w, Self::ViewQuery>,
229                maybe_entities: Option<ROQueryItem<'w, Self::ItemQuery>>,
230                ($($name,)*): SystemParamItem<'w, '_, Self::Param>,
231                _pass: &mut TrackedRenderPass<'w>,
232            ) -> RenderCommandResult {
233                match maybe_entities {
234                    None => {
235                        $(if let RenderCommandResult::Failure = $name::render(_item, $view, None, $name, _pass) {
236                            return RenderCommandResult::Failure;
237                        })*
238                    }
239                    Some(($($entity,)*)) => {
240                        $(if let RenderCommandResult::Failure = $name::render(_item, $view, Some($entity), $name, _pass) {
241                            return RenderCommandResult::Failure;
242                        })*
243                    }
244                }
245                RenderCommandResult::Success
246            }
247        }
248    };
249}
250
251all_tuples!(render_command_tuple_impl, 0, 15, C, V, E);
252
253/// Wraps a [`RenderCommand`] into a state so that it can be used as a [`Draw`] function.
254///
255/// The [`RenderCommand::Param`], [`RenderCommand::ViewQuery`] and
256/// [`RenderCommand::ItemQuery`] are fetched from the ECS and passed to the command.
257pub struct RenderCommandState<P: PhaseItem + 'static, C: RenderCommand<P>> {
258    state: SystemState<C::Param>,
259    view: QueryState<C::ViewQuery>,
260    entity: QueryState<C::ItemQuery>,
261}
262
263impl<P: PhaseItem, C: RenderCommand<P>> RenderCommandState<P, C> {
264    /// Creates a new [`RenderCommandState`] for the [`RenderCommand`].
265    pub fn new(world: &mut World) -> Self {
266        Self {
267            state: SystemState::new(world),
268            view: world.query(),
269            entity: world.query(),
270        }
271    }
272}
273
274impl<P: PhaseItem, C: RenderCommand<P> + Send + Sync + 'static> Draw<P> for RenderCommandState<P, C>
275where
276    C::Param: ReadOnlySystemParam,
277{
278    /// Prepares the render command to be used. This is called once and only once before the phase
279    /// begins. There may be zero or more [`draw`](RenderCommandState::draw) calls following a call to this function.
280    fn prepare(&mut self, world: &'_ World) {
281        self.state.update_archetypes(world);
282        self.view.update_archetypes(world);
283        self.entity.update_archetypes(world);
284    }
285
286    /// Fetches the ECS parameters for the wrapped [`RenderCommand`] and then renders it.
287    fn draw<'w>(
288        &mut self,
289        world: &'w World,
290        pass: &mut TrackedRenderPass<'w>,
291        view: Entity,
292        item: &P,
293    ) {
294        let param = self.state.get_manual(world);
295        let view = self.view.get_manual(world, view).unwrap();
296        let entity = self.entity.get_manual(world, item.entity()).ok();
297        // TODO: handle/log `RenderCommand` failure
298        C::render(item, view, entity, param, pass);
299    }
300}
301
302/// Registers a [`RenderCommand`] as a [`Draw`] function.
303/// They are stored inside the [`DrawFunctions`] resource of the app.
304pub trait AddRenderCommand {
305    /// Adds the [`RenderCommand`] for the specified render phase to the app.
306    fn add_render_command<P: PhaseItem, C: RenderCommand<P> + Send + Sync + 'static>(
307        &mut self,
308    ) -> &mut Self
309    where
310        C::Param: ReadOnlySystemParam;
311}
312
313impl AddRenderCommand for SubApp {
314    fn add_render_command<P: PhaseItem, C: RenderCommand<P> + Send + Sync + 'static>(
315        &mut self,
316    ) -> &mut Self
317    where
318        C::Param: ReadOnlySystemParam,
319    {
320        let draw_function = RenderCommandState::<P, C>::new(self.world_mut());
321        let draw_functions = self
322            .world()
323            .get_resource::<DrawFunctions<P>>()
324            .unwrap_or_else(|| {
325                panic!(
326                    "DrawFunctions<{}> must be added to the world as a resource \
327                     before adding render commands to it",
328                    std::any::type_name::<P>(),
329                );
330            });
331        draw_functions.write().add_with::<C, _>(draw_function);
332        self
333    }
334}
335
336impl AddRenderCommand for App {
337    fn add_render_command<P: PhaseItem, C: RenderCommand<P> + Send + Sync + 'static>(
338        &mut self,
339    ) -> &mut Self
340    where
341        C::Param: ReadOnlySystemParam,
342    {
343        SubApp::add_render_command::<P, C>(self.main_mut());
344        self
345    }
346}