Path: blob/main/crates/bevy_render/src/extract_component.rs
6595 views
use crate::{1render_resource::{encase::internal::WriteInto, DynamicUniformBuffer, ShaderType},2renderer::{RenderDevice, RenderQueue},3sync_component::SyncComponentPlugin,4sync_world::RenderEntity,5Extract, ExtractSchedule, Render, RenderApp, RenderSystems,6};7use bevy_app::{App, Plugin};8use bevy_camera::visibility::ViewVisibility;9use bevy_ecs::{10bundle::NoBundleEffect,11component::Component,12prelude::*,13query::{QueryFilter, QueryItem, ReadOnlyQueryData},14};15use core::{marker::PhantomData, ops::Deref};1617pub use bevy_render_macros::ExtractComponent;1819/// Stores the index of a uniform inside of [`ComponentUniforms`].20#[derive(Component)]21pub struct DynamicUniformIndex<C: Component> {22index: u32,23marker: PhantomData<C>,24}2526impl<C: Component> DynamicUniformIndex<C> {27#[inline]28pub fn index(&self) -> u32 {29self.index30}31}3233/// Describes how a component gets extracted for rendering.34///35/// Therefore the component is transferred from the "app world" into the "render world"36/// in the [`ExtractSchedule`] step.37pub trait ExtractComponent: Component {38/// ECS [`ReadOnlyQueryData`] to fetch the components to extract.39type QueryData: ReadOnlyQueryData;40/// Filters the entities with additional constraints.41type QueryFilter: QueryFilter;4243/// The output from extraction.44///45/// Returning `None` based on the queried item will remove the component from the entity in46/// the render world. This can be used, for example, to conditionally extract camera settings47/// in order to disable a rendering feature on the basis of those settings, without removing48/// the component from the entity in the main world.49///50/// The output may be different from the queried component.51/// This can be useful for example if only a subset of the fields are useful52/// in the render world.53///54/// `Out` has a [`Bundle`] trait bound instead of a [`Component`] trait bound in order to allow use cases55/// such as tuples of components as output.56type Out: Bundle<Effect: NoBundleEffect>;5758// TODO: https://github.com/rust-lang/rust/issues/2966159// type Out: Component = Self;6061/// Defines how the component is transferred into the "render world".62fn extract_component(item: QueryItem<'_, '_, Self::QueryData>) -> Option<Self::Out>;63}6465/// This plugin prepares the components of the corresponding type for the GPU66/// by transforming them into uniforms.67///68/// They can then be accessed from the [`ComponentUniforms`] resource.69/// For referencing the newly created uniforms a [`DynamicUniformIndex`] is inserted70/// for every processed entity.71///72/// Therefore it sets up the [`RenderSystems::Prepare`] step73/// for the specified [`ExtractComponent`].74pub struct UniformComponentPlugin<C>(PhantomData<fn() -> C>);7576impl<C> Default for UniformComponentPlugin<C> {77fn default() -> Self {78Self(PhantomData)79}80}8182impl<C: Component + ShaderType + WriteInto + Clone> Plugin for UniformComponentPlugin<C> {83fn build(&self, app: &mut App) {84if let Some(render_app) = app.get_sub_app_mut(RenderApp) {85render_app86.insert_resource(ComponentUniforms::<C>::default())87.add_systems(88Render,89prepare_uniform_components::<C>.in_set(RenderSystems::PrepareResources),90);91}92}93}9495/// Stores all uniforms of the component type.96#[derive(Resource)]97pub struct ComponentUniforms<C: Component + ShaderType> {98uniforms: DynamicUniformBuffer<C>,99}100101impl<C: Component + ShaderType> Deref for ComponentUniforms<C> {102type Target = DynamicUniformBuffer<C>;103104#[inline]105fn deref(&self) -> &Self::Target {106&self.uniforms107}108}109110impl<C: Component + ShaderType> ComponentUniforms<C> {111#[inline]112pub fn uniforms(&self) -> &DynamicUniformBuffer<C> {113&self.uniforms114}115}116117impl<C: Component + ShaderType> Default for ComponentUniforms<C> {118fn default() -> Self {119Self {120uniforms: Default::default(),121}122}123}124125/// This system prepares all components of the corresponding component type.126/// They are transformed into uniforms and stored in the [`ComponentUniforms`] resource.127fn prepare_uniform_components<C>(128mut commands: Commands,129render_device: Res<RenderDevice>,130render_queue: Res<RenderQueue>,131mut component_uniforms: ResMut<ComponentUniforms<C>>,132components: Query<(Entity, &C)>,133) where134C: Component + ShaderType + WriteInto + Clone,135{136let components_iter = components.iter();137let count = components_iter.len();138let Some(mut writer) =139component_uniforms140.uniforms141.get_writer(count, &render_device, &render_queue)142else {143return;144};145let entities = components_iter146.map(|(entity, component)| {147(148entity,149DynamicUniformIndex::<C> {150index: writer.write(component),151marker: PhantomData,152},153)154})155.collect::<Vec<_>>();156commands.try_insert_batch(entities);157}158159/// This plugin extracts the components into the render world for synced entities.160///161/// To do so, it sets up the [`ExtractSchedule`] step for the specified [`ExtractComponent`].162pub struct ExtractComponentPlugin<C, F = ()> {163only_extract_visible: bool,164marker: PhantomData<fn() -> (C, F)>,165}166167impl<C, F> Default for ExtractComponentPlugin<C, F> {168fn default() -> Self {169Self {170only_extract_visible: false,171marker: PhantomData,172}173}174}175176impl<C, F> ExtractComponentPlugin<C, F> {177pub fn extract_visible() -> Self {178Self {179only_extract_visible: true,180marker: PhantomData,181}182}183}184185impl<C: ExtractComponent> Plugin for ExtractComponentPlugin<C> {186fn build(&self, app: &mut App) {187app.add_plugins(SyncComponentPlugin::<C>::default());188189if let Some(render_app) = app.get_sub_app_mut(RenderApp) {190if self.only_extract_visible {191render_app.add_systems(ExtractSchedule, extract_visible_components::<C>);192} else {193render_app.add_systems(ExtractSchedule, extract_components::<C>);194}195}196}197}198199/// This system extracts all components of the corresponding [`ExtractComponent`], for entities that are synced via [`crate::sync_world::SyncToRenderWorld`].200fn extract_components<C: ExtractComponent>(201mut commands: Commands,202mut previous_len: Local<usize>,203query: Extract<Query<(RenderEntity, C::QueryData), C::QueryFilter>>,204) {205let mut values = Vec::with_capacity(*previous_len);206for (entity, query_item) in &query {207if let Some(component) = C::extract_component(query_item) {208values.push((entity, component));209} else {210commands.entity(entity).remove::<C::Out>();211}212}213*previous_len = values.len();214commands.try_insert_batch(values);215}216217/// This system extracts all components of the corresponding [`ExtractComponent`], for entities that are visible and synced via [`crate::sync_world::SyncToRenderWorld`].218fn extract_visible_components<C: ExtractComponent>(219mut commands: Commands,220mut previous_len: Local<usize>,221query: Extract<Query<(RenderEntity, &ViewVisibility, C::QueryData), C::QueryFilter>>,222) {223let mut values = Vec::with_capacity(*previous_len);224for (entity, view_visibility, query_item) in &query {225if view_visibility.get() {226if let Some(component) = C::extract_component(query_item) {227values.push((entity, component));228} else {229commands.entity(entity).remove::<C::Out>();230}231}232}233*previous_len = values.len();234commands.try_insert_batch(values);235}236237238