This commit is contained in:
1 parent
f29712d158
commit
3e053a81ab
123 files changed
+31930
-1404
No files matched your search
+174
@@ -0,0 +1,174 @@
|
||||
use bevy_app::{App, SubApp};
|
||||
use bevy_ecs::world::{FromWorld, World};
|
||||
use tracing::warn;
|
||||
|
||||
use super::{IntoRenderNodeArray, Node, RenderGraph, RenderLabel, RenderSubGraph};
|
||||
|
||||
/// Adds common [`RenderGraph`] operations to [`SubApp`] (and [`App`]).
|
||||
pub trait RenderGraphExt {
|
||||
// Add a sub graph to the [`RenderGraph`]
|
||||
fn add_render_sub_graph(&mut self, sub_graph: impl RenderSubGraph) -> &mut Self;
|
||||
/// Add a [`Node`] to the [`RenderGraph`]:
|
||||
/// * Create the [`Node`] using the [`FromWorld`] implementation
|
||||
/// * Add it to the graph
|
||||
fn add_render_graph_node<T: Node + FromWorld>(
|
||||
&mut self,
|
||||
sub_graph: impl RenderSubGraph,
|
||||
node_label: impl RenderLabel,
|
||||
) -> &mut Self;
|
||||
/// Automatically add the required node edges based on the given ordering
|
||||
fn add_render_graph_edges<const N: usize>(
|
||||
&mut self,
|
||||
sub_graph: impl RenderSubGraph,
|
||||
edges: impl IntoRenderNodeArray<N>,
|
||||
) -> &mut Self;
|
||||
|
||||
/// Add node edge to the specified graph
|
||||
fn add_render_graph_edge(
|
||||
&mut self,
|
||||
sub_graph: impl RenderSubGraph,
|
||||
output_node: impl RenderLabel,
|
||||
input_node: impl RenderLabel,
|
||||
) -> &mut Self;
|
||||
}
|
||||
|
||||
impl RenderGraphExt for World {
|
||||
fn add_render_graph_node<T: Node + FromWorld>(
|
||||
&mut self,
|
||||
sub_graph: impl RenderSubGraph,
|
||||
node_label: impl RenderLabel,
|
||||
) -> &mut Self {
|
||||
let sub_graph = sub_graph.intern();
|
||||
let node = T::from_world(self);
|
||||
let mut render_graph = self.get_resource_mut::<RenderGraph>().expect(
|
||||
"RenderGraph not found. Make sure you are using add_render_graph_node on the RenderApp",
|
||||
);
|
||||
if let Some(graph) = render_graph.get_sub_graph_mut(sub_graph) {
|
||||
graph.add_node(node_label, node);
|
||||
} else {
|
||||
warn!(
|
||||
"Tried adding a render graph node to {sub_graph:?} but the sub graph doesn't exist"
|
||||
);
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
#[track_caller]
|
||||
fn add_render_graph_edges<const N: usize>(
|
||||
&mut self,
|
||||
sub_graph: impl RenderSubGraph,
|
||||
edges: impl IntoRenderNodeArray<N>,
|
||||
) -> &mut Self {
|
||||
let sub_graph = sub_graph.intern();
|
||||
let mut render_graph = self.get_resource_mut::<RenderGraph>().expect(
|
||||
"RenderGraph not found. Make sure you are using add_render_graph_edges on the RenderApp",
|
||||
);
|
||||
if let Some(graph) = render_graph.get_sub_graph_mut(sub_graph) {
|
||||
graph.add_node_edges(edges);
|
||||
} else {
|
||||
warn!(
|
||||
"Tried adding render graph edges to {sub_graph:?} but the sub graph doesn't exist"
|
||||
);
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
fn add_render_graph_edge(
|
||||
&mut self,
|
||||
sub_graph: impl RenderSubGraph,
|
||||
output_node: impl RenderLabel,
|
||||
input_node: impl RenderLabel,
|
||||
) -> &mut Self {
|
||||
let sub_graph = sub_graph.intern();
|
||||
let mut render_graph = self.get_resource_mut::<RenderGraph>().expect(
|
||||
"RenderGraph not found. Make sure you are using add_render_graph_edge on the RenderApp",
|
||||
);
|
||||
if let Some(graph) = render_graph.get_sub_graph_mut(sub_graph) {
|
||||
graph.add_node_edge(output_node, input_node);
|
||||
} else {
|
||||
warn!(
|
||||
"Tried adding a render graph edge to {sub_graph:?} but the sub graph doesn't exist"
|
||||
);
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
fn add_render_sub_graph(&mut self, sub_graph: impl RenderSubGraph) -> &mut Self {
|
||||
let mut render_graph = self.get_resource_mut::<RenderGraph>().expect(
|
||||
"RenderGraph not found. Make sure you are using add_render_sub_graph on the RenderApp",
|
||||
);
|
||||
render_graph.add_sub_graph(sub_graph, RenderGraph::default());
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl RenderGraphExt for SubApp {
|
||||
fn add_render_graph_node<T: Node + FromWorld>(
|
||||
&mut self,
|
||||
sub_graph: impl RenderSubGraph,
|
||||
node_label: impl RenderLabel,
|
||||
) -> &mut Self {
|
||||
World::add_render_graph_node::<T>(self.world_mut(), sub_graph, node_label);
|
||||
self
|
||||
}
|
||||
|
||||
fn add_render_graph_edge(
|
||||
&mut self,
|
||||
sub_graph: impl RenderSubGraph,
|
||||
output_node: impl RenderLabel,
|
||||
input_node: impl RenderLabel,
|
||||
) -> &mut Self {
|
||||
World::add_render_graph_edge(self.world_mut(), sub_graph, output_node, input_node);
|
||||
self
|
||||
}
|
||||
|
||||
#[track_caller]
|
||||
fn add_render_graph_edges<const N: usize>(
|
||||
&mut self,
|
||||
sub_graph: impl RenderSubGraph,
|
||||
edges: impl IntoRenderNodeArray<N>,
|
||||
) -> &mut Self {
|
||||
World::add_render_graph_edges(self.world_mut(), sub_graph, edges);
|
||||
self
|
||||
}
|
||||
|
||||
fn add_render_sub_graph(&mut self, sub_graph: impl RenderSubGraph) -> &mut Self {
|
||||
World::add_render_sub_graph(self.world_mut(), sub_graph);
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl RenderGraphExt for App {
|
||||
fn add_render_graph_node<T: Node + FromWorld>(
|
||||
&mut self,
|
||||
sub_graph: impl RenderSubGraph,
|
||||
node_label: impl RenderLabel,
|
||||
) -> &mut Self {
|
||||
World::add_render_graph_node::<T>(self.world_mut(), sub_graph, node_label);
|
||||
self
|
||||
}
|
||||
|
||||
fn add_render_graph_edge(
|
||||
&mut self,
|
||||
sub_graph: impl RenderSubGraph,
|
||||
output_node: impl RenderLabel,
|
||||
input_node: impl RenderLabel,
|
||||
) -> &mut Self {
|
||||
World::add_render_graph_edge(self.world_mut(), sub_graph, output_node, input_node);
|
||||
self
|
||||
}
|
||||
|
||||
fn add_render_graph_edges<const N: usize>(
|
||||
&mut self,
|
||||
sub_graph: impl RenderSubGraph,
|
||||
edges: impl IntoRenderNodeArray<N>,
|
||||
) -> &mut Self {
|
||||
World::add_render_graph_edges(self.world_mut(), sub_graph, edges);
|
||||
self
|
||||
}
|
||||
|
||||
fn add_render_sub_graph(&mut self, sub_graph: impl RenderSubGraph) -> &mut Self {
|
||||
World::add_render_sub_graph(self.world_mut(), sub_graph);
|
||||
self
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
use crate::{
|
||||
camera::{ExtractedCamera, SortedCameras},
|
||||
render_graph::{Node, NodeRunError, RenderGraphContext},
|
||||
renderer::RenderContext,
|
||||
view::ExtractedWindows,
|
||||
};
|
||||
use bevy_camera::{ClearColor, NormalizedRenderTarget};
|
||||
use bevy_ecs::{entity::ContainsEntity, prelude::QueryState, world::World};
|
||||
use bevy_platform::collections::HashSet;
|
||||
use wgpu::{LoadOp, Operations, RenderPassColorAttachment, RenderPassDescriptor, StoreOp};
|
||||
|
||||
pub struct CameraDriverNode {
|
||||
cameras: QueryState<&'static ExtractedCamera>,
|
||||
}
|
||||
|
||||
impl CameraDriverNode {
|
||||
pub fn new(world: &mut World) -> Self {
|
||||
Self {
|
||||
cameras: world.query(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Node for CameraDriverNode {
|
||||
fn update(&mut self, world: &mut World) {
|
||||
self.cameras.update_archetypes(world);
|
||||
}
|
||||
fn run(
|
||||
&self,
|
||||
graph: &mut RenderGraphContext,
|
||||
render_context: &mut RenderContext,
|
||||
world: &World,
|
||||
) -> Result<(), NodeRunError> {
|
||||
let sorted_cameras = world.resource::<SortedCameras>();
|
||||
let windows = world.resource::<ExtractedWindows>();
|
||||
let mut camera_windows = <HashSet<_>>::default();
|
||||
for sorted_camera in &sorted_cameras.0 {
|
||||
let Ok(camera) = self.cameras.get_manual(world, sorted_camera.entity) else {
|
||||
continue;
|
||||
};
|
||||
|
||||
let mut run_graph = true;
|
||||
if let Some(NormalizedRenderTarget::Window(window_ref)) = camera.target {
|
||||
let window_entity = window_ref.entity();
|
||||
if windows
|
||||
.windows
|
||||
.get(&window_entity)
|
||||
.is_some_and(|w| w.physical_width > 0 && w.physical_height > 0)
|
||||
{
|
||||
camera_windows.insert(window_entity);
|
||||
} else {
|
||||
// The window doesn't exist anymore or zero-sized so we don't need to run the graph
|
||||
run_graph = false;
|
||||
}
|
||||
}
|
||||
if run_graph {
|
||||
graph.run_sub_graph(
|
||||
camera.render_graph,
|
||||
vec![],
|
||||
Some(sorted_camera.entity),
|
||||
Some(format!(
|
||||
"Camera {} ({})",
|
||||
sorted_camera.order, sorted_camera.entity
|
||||
)),
|
||||
)?;
|
||||
}
|
||||
}
|
||||
|
||||
let clear_color_global = world.resource::<ClearColor>();
|
||||
|
||||
// wgpu (and some backends) require doing work for swap chains if you call `get_current_texture()` and `present()`
|
||||
// This ensures that Bevy doesn't crash, even when there are no cameras (and therefore no work submitted).
|
||||
for (id, window) in world.resource::<ExtractedWindows>().iter() {
|
||||
if camera_windows.contains(id) && render_context.has_commands() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let Some(swap_chain_texture) = &window.swap_chain_texture_view else {
|
||||
continue;
|
||||
};
|
||||
|
||||
#[cfg(feature = "trace")]
|
||||
let _span = tracing::info_span!("no_camera_clear_pass").entered();
|
||||
let pass_descriptor = RenderPassDescriptor {
|
||||
label: Some("no_camera_clear_pass"),
|
||||
color_attachments: &[Some(RenderPassColorAttachment {
|
||||
view: swap_chain_texture,
|
||||
depth_slice: None,
|
||||
resolve_target: None,
|
||||
ops: Operations {
|
||||
load: LoadOp::Clear(clear_color_global.to_linear().into()),
|
||||
store: StoreOp::Store,
|
||||
},
|
||||
})],
|
||||
depth_stencil_attachment: None,
|
||||
timestamp_writes: None,
|
||||
occlusion_query_set: None,
|
||||
};
|
||||
|
||||
render_context
|
||||
.command_encoder()
|
||||
.begin_render_pass(&pass_descriptor);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
+286
@@ -0,0 +1,286 @@
|
||||
use crate::{
|
||||
render_graph::{NodeState, RenderGraph, SlotInfos, SlotLabel, SlotType, SlotValue},
|
||||
render_resource::{Buffer, Sampler, TextureView},
|
||||
};
|
||||
use alloc::borrow::Cow;
|
||||
use bevy_ecs::{entity::Entity, intern::Interned};
|
||||
use thiserror::Error;
|
||||
|
||||
use super::{InternedRenderSubGraph, RenderLabel, RenderSubGraph};
|
||||
|
||||
/// A command that signals the graph runner to run the sub graph corresponding to the `sub_graph`
|
||||
/// with the specified `inputs` next.
|
||||
pub struct RunSubGraph {
|
||||
pub sub_graph: InternedRenderSubGraph,
|
||||
pub inputs: Vec<SlotValue>,
|
||||
pub view_entity: Option<Entity>,
|
||||
pub debug_group: Option<String>,
|
||||
}
|
||||
|
||||
/// The context with all graph information required to run a [`Node`](super::Node).
|
||||
/// This context is created for each node by the render graph runner.
|
||||
///
|
||||
/// The slot input can be read from here and the outputs must be written back to the context for
|
||||
/// passing them onto the next node.
|
||||
///
|
||||
/// Sub graphs can be queued for running by adding a [`RunSubGraph`] command to the context.
|
||||
/// After the node has finished running the graph runner is responsible for executing the sub graphs.
|
||||
pub struct RenderGraphContext<'a> {
|
||||
graph: &'a RenderGraph,
|
||||
node: &'a NodeState,
|
||||
inputs: &'a [SlotValue],
|
||||
outputs: &'a mut [Option<SlotValue>],
|
||||
run_sub_graphs: Vec<RunSubGraph>,
|
||||
/// The `view_entity` associated with the render graph being executed
|
||||
/// This is optional because you aren't required to have a `view_entity` for a node.
|
||||
/// For example, compute shader nodes don't have one.
|
||||
/// It should always be set when the [`RenderGraph`] is running on a View.
|
||||
view_entity: Option<Entity>,
|
||||
}
|
||||
|
||||
impl<'a> RenderGraphContext<'a> {
|
||||
/// Creates a new render graph context for the `node`.
|
||||
pub fn new(
|
||||
graph: &'a RenderGraph,
|
||||
node: &'a NodeState,
|
||||
inputs: &'a [SlotValue],
|
||||
outputs: &'a mut [Option<SlotValue>],
|
||||
) -> Self {
|
||||
Self {
|
||||
graph,
|
||||
node,
|
||||
inputs,
|
||||
outputs,
|
||||
run_sub_graphs: Vec::new(),
|
||||
view_entity: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the input slot values for the node.
|
||||
#[inline]
|
||||
pub fn inputs(&self) -> &[SlotValue] {
|
||||
self.inputs
|
||||
}
|
||||
|
||||
/// Returns the [`SlotInfos`] of the inputs.
|
||||
pub fn input_info(&self) -> &SlotInfos {
|
||||
&self.node.input_slots
|
||||
}
|
||||
|
||||
/// Returns the [`SlotInfos`] of the outputs.
|
||||
pub fn output_info(&self) -> &SlotInfos {
|
||||
&self.node.output_slots
|
||||
}
|
||||
|
||||
/// Retrieves the input slot value referenced by the `label`.
|
||||
pub fn get_input(&self, label: impl Into<SlotLabel>) -> Result<&SlotValue, InputSlotError> {
|
||||
let label = label.into();
|
||||
let index = self
|
||||
.input_info()
|
||||
.get_slot_index(label.clone())
|
||||
.ok_or(InputSlotError::InvalidSlot(label))?;
|
||||
Ok(&self.inputs[index])
|
||||
}
|
||||
|
||||
// TODO: should this return an Arc or a reference?
|
||||
/// Retrieves the input slot value referenced by the `label` as a [`TextureView`].
|
||||
pub fn get_input_texture(
|
||||
&self,
|
||||
label: impl Into<SlotLabel>,
|
||||
) -> Result<&TextureView, InputSlotError> {
|
||||
let label = label.into();
|
||||
match self.get_input(label.clone())? {
|
||||
SlotValue::TextureView(value) => Ok(value),
|
||||
value => Err(InputSlotError::MismatchedSlotType {
|
||||
label,
|
||||
actual: value.slot_type(),
|
||||
expected: SlotType::TextureView,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// Retrieves the input slot value referenced by the `label` as a [`Sampler`].
|
||||
pub fn get_input_sampler(
|
||||
&self,
|
||||
label: impl Into<SlotLabel>,
|
||||
) -> Result<&Sampler, InputSlotError> {
|
||||
let label = label.into();
|
||||
match self.get_input(label.clone())? {
|
||||
SlotValue::Sampler(value) => Ok(value),
|
||||
value => Err(InputSlotError::MismatchedSlotType {
|
||||
label,
|
||||
actual: value.slot_type(),
|
||||
expected: SlotType::Sampler,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// Retrieves the input slot value referenced by the `label` as a [`Buffer`].
|
||||
pub fn get_input_buffer(&self, label: impl Into<SlotLabel>) -> Result<&Buffer, InputSlotError> {
|
||||
let label = label.into();
|
||||
match self.get_input(label.clone())? {
|
||||
SlotValue::Buffer(value) => Ok(value),
|
||||
value => Err(InputSlotError::MismatchedSlotType {
|
||||
label,
|
||||
actual: value.slot_type(),
|
||||
expected: SlotType::Buffer,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// Retrieves the input slot value referenced by the `label` as an [`Entity`].
|
||||
pub fn get_input_entity(&self, label: impl Into<SlotLabel>) -> Result<Entity, InputSlotError> {
|
||||
let label = label.into();
|
||||
match self.get_input(label.clone())? {
|
||||
SlotValue::Entity(value) => Ok(*value),
|
||||
value => Err(InputSlotError::MismatchedSlotType {
|
||||
label,
|
||||
actual: value.slot_type(),
|
||||
expected: SlotType::Entity,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets the output slot value referenced by the `label`.
|
||||
pub fn set_output(
|
||||
&mut self,
|
||||
label: impl Into<SlotLabel>,
|
||||
value: impl Into<SlotValue>,
|
||||
) -> Result<(), OutputSlotError> {
|
||||
let label = label.into();
|
||||
let value = value.into();
|
||||
let slot_index = self
|
||||
.output_info()
|
||||
.get_slot_index(label.clone())
|
||||
.ok_or_else(|| OutputSlotError::InvalidSlot(label.clone()))?;
|
||||
let slot = self
|
||||
.output_info()
|
||||
.get_slot(slot_index)
|
||||
.expect("slot is valid");
|
||||
if value.slot_type() != slot.slot_type {
|
||||
return Err(OutputSlotError::MismatchedSlotType {
|
||||
label,
|
||||
actual: slot.slot_type,
|
||||
expected: value.slot_type(),
|
||||
});
|
||||
}
|
||||
self.outputs[slot_index] = Some(value);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn view_entity(&self) -> Entity {
|
||||
self.view_entity.unwrap()
|
||||
}
|
||||
|
||||
pub fn get_view_entity(&self) -> Option<Entity> {
|
||||
self.view_entity
|
||||
}
|
||||
|
||||
pub fn set_view_entity(&mut self, view_entity: Entity) {
|
||||
self.view_entity = Some(view_entity);
|
||||
}
|
||||
|
||||
/// Queues up a sub graph for execution after the node has finished running.
|
||||
pub fn run_sub_graph(
|
||||
&mut self,
|
||||
name: impl RenderSubGraph,
|
||||
inputs: Vec<SlotValue>,
|
||||
view_entity: Option<Entity>,
|
||||
debug_group: Option<String>,
|
||||
) -> Result<(), RunSubGraphError> {
|
||||
let name = name.intern();
|
||||
let sub_graph = self
|
||||
.graph
|
||||
.get_sub_graph(name)
|
||||
.ok_or(RunSubGraphError::MissingSubGraph(name))?;
|
||||
if let Some(input_node) = sub_graph.get_input_node() {
|
||||
for (i, input_slot) in input_node.input_slots.iter().enumerate() {
|
||||
if let Some(input_value) = inputs.get(i) {
|
||||
if input_slot.slot_type != input_value.slot_type() {
|
||||
return Err(RunSubGraphError::MismatchedInputSlotType {
|
||||
graph_name: name,
|
||||
slot_index: i,
|
||||
actual: input_value.slot_type(),
|
||||
expected: input_slot.slot_type,
|
||||
label: input_slot.name.clone().into(),
|
||||
});
|
||||
}
|
||||
} else {
|
||||
return Err(RunSubGraphError::MissingInput {
|
||||
slot_index: i,
|
||||
slot_name: input_slot.name.clone(),
|
||||
graph_name: name,
|
||||
});
|
||||
}
|
||||
}
|
||||
} else if !inputs.is_empty() {
|
||||
return Err(RunSubGraphError::SubGraphHasNoInputs(name));
|
||||
}
|
||||
|
||||
self.run_sub_graphs.push(RunSubGraph {
|
||||
sub_graph: name,
|
||||
inputs,
|
||||
view_entity,
|
||||
debug_group,
|
||||
});
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Returns a human-readable label for this node, for debugging purposes.
|
||||
pub fn label(&self) -> Interned<dyn RenderLabel> {
|
||||
self.node.label
|
||||
}
|
||||
|
||||
/// Finishes the context for this [`Node`](super::Node) by
|
||||
/// returning the sub graphs to run next.
|
||||
pub fn finish(self) -> Vec<RunSubGraph> {
|
||||
self.run_sub_graphs
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Error, Debug, Eq, PartialEq)]
|
||||
pub enum RunSubGraphError {
|
||||
#[error("attempted to run sub-graph `{0:?}`, but it does not exist")]
|
||||
MissingSubGraph(InternedRenderSubGraph),
|
||||
#[error("attempted to pass inputs to sub-graph `{0:?}`, which has no input slots")]
|
||||
SubGraphHasNoInputs(InternedRenderSubGraph),
|
||||
#[error("sub graph (name: `{graph_name:?}`) could not be run because slot `{slot_name}` at index {slot_index} has no value")]
|
||||
MissingInput {
|
||||
slot_index: usize,
|
||||
slot_name: Cow<'static, str>,
|
||||
graph_name: InternedRenderSubGraph,
|
||||
},
|
||||
#[error("attempted to use the wrong type for input slot")]
|
||||
MismatchedInputSlotType {
|
||||
graph_name: InternedRenderSubGraph,
|
||||
slot_index: usize,
|
||||
label: SlotLabel,
|
||||
expected: SlotType,
|
||||
actual: SlotType,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Error, Debug, Eq, PartialEq)]
|
||||
pub enum OutputSlotError {
|
||||
#[error("output slot `{0:?}` does not exist")]
|
||||
InvalidSlot(SlotLabel),
|
||||
#[error("attempted to output a value of type `{actual}` to output slot `{label:?}`, which has type `{expected}`")]
|
||||
MismatchedSlotType {
|
||||
label: SlotLabel,
|
||||
expected: SlotType,
|
||||
actual: SlotType,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Error, Debug, Eq, PartialEq)]
|
||||
pub enum InputSlotError {
|
||||
#[error("input slot `{0:?}` does not exist")]
|
||||
InvalidSlot(SlotLabel),
|
||||
#[error("attempted to retrieve a value of type `{actual}` from input slot `{label:?}`, which has type `{expected}`")]
|
||||
MismatchedSlotType {
|
||||
label: SlotLabel,
|
||||
expected: SlotType,
|
||||
actual: SlotType,
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
use super::InternedRenderLabel;
|
||||
|
||||
/// An edge, which connects two [`Nodes`](super::Node) in
|
||||
/// a [`RenderGraph`](crate::render_graph::RenderGraph).
|
||||
///
|
||||
/// They are used to describe the ordering (which node has to run first)
|
||||
/// and may be of two kinds: [`NodeEdge`](Self::NodeEdge) and [`SlotEdge`](Self::SlotEdge).
|
||||
///
|
||||
/// Edges are added via the [`RenderGraph::add_node_edge`] and the
|
||||
/// [`RenderGraph::add_slot_edge`] methods.
|
||||
///
|
||||
/// The former simply states that the `output_node` has to be run before the `input_node`,
|
||||
/// while the later connects an output slot of the `output_node`
|
||||
/// with an input slot of the `input_node` to pass additional data along.
|
||||
/// For more information see [`SlotType`](super::SlotType).
|
||||
///
|
||||
/// [`RenderGraph::add_node_edge`]: crate::render_graph::RenderGraph::add_node_edge
|
||||
/// [`RenderGraph::add_slot_edge`]: crate::render_graph::RenderGraph::add_slot_edge
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub enum Edge {
|
||||
/// An edge describing to ordering of both nodes (`output_node` before `input_node`)
|
||||
/// and connecting the output slot at the `output_index` of the `output_node`
|
||||
/// with the slot at the `input_index` of the `input_node`.
|
||||
SlotEdge {
|
||||
input_node: InternedRenderLabel,
|
||||
input_index: usize,
|
||||
output_node: InternedRenderLabel,
|
||||
output_index: usize,
|
||||
},
|
||||
/// An edge describing to ordering of both nodes (`output_node` before `input_node`).
|
||||
NodeEdge {
|
||||
input_node: InternedRenderLabel,
|
||||
output_node: InternedRenderLabel,
|
||||
},
|
||||
}
|
||||
|
||||
impl Edge {
|
||||
/// Returns the id of the `input_node`.
|
||||
pub fn get_input_node(&self) -> InternedRenderLabel {
|
||||
match self {
|
||||
Edge::SlotEdge { input_node, .. } | Edge::NodeEdge { input_node, .. } => *input_node,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the id of the `output_node`.
|
||||
pub fn get_output_node(&self) -> InternedRenderLabel {
|
||||
match self {
|
||||
Edge::SlotEdge { output_node, .. } | Edge::NodeEdge { output_node, .. } => *output_node,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Eq)]
|
||||
pub enum EdgeExistence {
|
||||
Exists,
|
||||
DoesNotExist,
|
||||
}
|
||||
+918
@@ -0,0 +1,918 @@
|
||||
use crate::{
|
||||
render_graph::{
|
||||
Edge, Node, NodeRunError, NodeState, RenderGraphContext, RenderGraphError, RenderLabel,
|
||||
SlotInfo, SlotLabel,
|
||||
},
|
||||
renderer::RenderContext,
|
||||
};
|
||||
use bevy_ecs::{define_label, intern::Interned, prelude::World, resource::Resource};
|
||||
use bevy_platform::collections::HashMap;
|
||||
use core::fmt::Debug;
|
||||
|
||||
use super::{EdgeExistence, InternedRenderLabel, IntoRenderNodeArray};
|
||||
|
||||
pub use bevy_render_macros::RenderSubGraph;
|
||||
|
||||
define_label!(
|
||||
#[diagnostic::on_unimplemented(
|
||||
note = "consider annotating `{Self}` with `#[derive(RenderSubGraph)]`"
|
||||
)]
|
||||
/// A strongly-typed class of labels used to identify a [`SubGraph`] in a render graph.
|
||||
RenderSubGraph,
|
||||
RENDER_SUB_GRAPH_INTERNER
|
||||
);
|
||||
|
||||
/// A shorthand for `Interned<dyn RenderSubGraph>`.
|
||||
pub type InternedRenderSubGraph = Interned<dyn RenderSubGraph>;
|
||||
|
||||
/// The render graph configures the modular and re-usable render logic.
|
||||
///
|
||||
/// It is a retained and stateless (nodes themselves may have their own internal state) structure,
|
||||
/// which can not be modified while it is executed by the graph runner.
|
||||
///
|
||||
/// The render graph runner is responsible for executing the entire graph each frame.
|
||||
/// It will execute each node in the graph in the correct order, based on the edges between the nodes.
|
||||
///
|
||||
/// It consists of three main components: [`Nodes`](Node), [`Edges`](Edge)
|
||||
/// and [`Slots`](super::SlotType).
|
||||
///
|
||||
/// Nodes are responsible for generating draw calls and operating on input and output slots.
|
||||
/// Edges specify the order of execution for nodes and connect input and output slots together.
|
||||
/// Slots describe the render resources created or used by the nodes.
|
||||
///
|
||||
/// Additionally a render graph can contain multiple sub graphs, which are run by the
|
||||
/// corresponding nodes. Every render graph can have its own optional input node.
|
||||
///
|
||||
/// ## Example
|
||||
/// Here is a simple render graph example with two nodes connected by a node edge.
|
||||
/// ```ignore
|
||||
/// # TODO: Remove when #10645 is fixed
|
||||
/// # use bevy_app::prelude::*;
|
||||
/// # use bevy_ecs::prelude::World;
|
||||
/// # use bevy_render::render_graph::{RenderGraph, RenderLabel, Node, RenderGraphContext, NodeRunError};
|
||||
/// # use bevy_render::renderer::RenderContext;
|
||||
/// #
|
||||
/// #[derive(RenderLabel)]
|
||||
/// enum Labels {
|
||||
/// A,
|
||||
/// B,
|
||||
/// }
|
||||
///
|
||||
/// # struct MyNode;
|
||||
/// #
|
||||
/// # impl Node for MyNode {
|
||||
/// # fn run(&self, graph: &mut RenderGraphContext, render_context: &mut RenderContext, world: &World) -> Result<(), NodeRunError> {
|
||||
/// # unimplemented!()
|
||||
/// # }
|
||||
/// # }
|
||||
/// #
|
||||
/// let mut graph = RenderGraph::default();
|
||||
/// graph.add_node(Labels::A, MyNode);
|
||||
/// graph.add_node(Labels::B, MyNode);
|
||||
/// graph.add_node_edge(Labels::B, Labels::A);
|
||||
/// ```
|
||||
#[derive(Resource, Default)]
|
||||
pub struct RenderGraph {
|
||||
nodes: HashMap<InternedRenderLabel, NodeState>,
|
||||
sub_graphs: HashMap<InternedRenderSubGraph, RenderGraph>,
|
||||
}
|
||||
|
||||
/// The label for the input node of a graph. Used to connect other nodes to it.
|
||||
#[derive(Debug, Hash, PartialEq, Eq, Clone, RenderLabel)]
|
||||
pub struct GraphInput;
|
||||
|
||||
impl RenderGraph {
|
||||
/// Updates all nodes and sub graphs of the render graph. Should be called before executing it.
|
||||
pub fn update(&mut self, world: &mut World) {
|
||||
for node in self.nodes.values_mut() {
|
||||
node.node.update(world);
|
||||
}
|
||||
|
||||
for sub_graph in self.sub_graphs.values_mut() {
|
||||
sub_graph.update(world);
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates an [`GraphInputNode`] with the specified slots if not already present.
|
||||
pub fn set_input(&mut self, inputs: Vec<SlotInfo>) {
|
||||
assert!(
|
||||
matches!(
|
||||
self.get_node_state(GraphInput),
|
||||
Err(RenderGraphError::InvalidNode(_))
|
||||
),
|
||||
"Graph already has an input node"
|
||||
);
|
||||
|
||||
self.add_node(GraphInput, GraphInputNode { inputs });
|
||||
}
|
||||
|
||||
/// Returns the [`NodeState`] of the input node of this graph.
|
||||
///
|
||||
/// # See also
|
||||
///
|
||||
/// - [`input_node`](Self::input_node) for an unchecked version.
|
||||
#[inline]
|
||||
pub fn get_input_node(&self) -> Option<&NodeState> {
|
||||
self.get_node_state(GraphInput).ok()
|
||||
}
|
||||
|
||||
/// Returns the [`NodeState`] of the input node of this graph.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// Panics if there is no input node set.
|
||||
///
|
||||
/// # See also
|
||||
///
|
||||
/// - [`get_input_node`](Self::get_input_node) for a version which returns an [`Option`] instead.
|
||||
#[inline]
|
||||
pub fn input_node(&self) -> &NodeState {
|
||||
self.get_input_node().unwrap()
|
||||
}
|
||||
|
||||
/// Adds the `node` with the `label` to the graph.
|
||||
/// If the label is already present replaces it instead.
|
||||
pub fn add_node<T>(&mut self, label: impl RenderLabel, node: T)
|
||||
where
|
||||
T: Node,
|
||||
{
|
||||
let label = label.intern();
|
||||
let node_state = NodeState::new(label, node);
|
||||
self.nodes.insert(label, node_state);
|
||||
}
|
||||
|
||||
/// Add `node_edge`s based on the order of the given `edges` array.
|
||||
///
|
||||
/// Defining an edge that already exists is not considered an error with this api.
|
||||
/// It simply won't create a new edge.
|
||||
#[track_caller]
|
||||
pub fn add_node_edges<const N: usize>(&mut self, edges: impl IntoRenderNodeArray<N>) {
|
||||
for window in edges.into_array().windows(2) {
|
||||
let [a, b] = window else {
|
||||
break;
|
||||
};
|
||||
if let Err(err) = self.try_add_node_edge(*a, *b) {
|
||||
match err {
|
||||
// Already existing edges are very easy to produce with this api
|
||||
// and shouldn't cause a panic
|
||||
RenderGraphError::EdgeAlreadyExists(_) => {}
|
||||
_ => panic!("{err}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Removes the `node` with the `label` from the graph.
|
||||
/// If the label does not exist, nothing happens.
|
||||
pub fn remove_node(&mut self, label: impl RenderLabel) -> Result<(), RenderGraphError> {
|
||||
let label = label.intern();
|
||||
if let Some(node_state) = self.nodes.remove(&label) {
|
||||
// Remove all edges from other nodes to this one. Note that as we're removing this
|
||||
// node, we don't need to remove its input edges
|
||||
for input_edge in node_state.edges.input_edges() {
|
||||
match input_edge {
|
||||
Edge::SlotEdge { output_node, .. }
|
||||
| Edge::NodeEdge {
|
||||
input_node: _,
|
||||
output_node,
|
||||
} => {
|
||||
if let Ok(output_node) = self.get_node_state_mut(*output_node) {
|
||||
output_node.edges.remove_output_edge(input_edge.clone())?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Remove all edges from this node to other nodes. Note that as we're removing this
|
||||
// node, we don't need to remove its output edges
|
||||
for output_edge in node_state.edges.output_edges() {
|
||||
match output_edge {
|
||||
Edge::SlotEdge {
|
||||
output_node: _,
|
||||
output_index: _,
|
||||
input_node,
|
||||
input_index: _,
|
||||
}
|
||||
| Edge::NodeEdge {
|
||||
output_node: _,
|
||||
input_node,
|
||||
} => {
|
||||
if let Ok(input_node) = self.get_node_state_mut(*input_node) {
|
||||
input_node.edges.remove_input_edge(output_edge.clone())?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Retrieves the [`NodeState`] referenced by the `label`.
|
||||
pub fn get_node_state(&self, label: impl RenderLabel) -> Result<&NodeState, RenderGraphError> {
|
||||
let label = label.intern();
|
||||
self.nodes
|
||||
.get(&label)
|
||||
.ok_or(RenderGraphError::InvalidNode(label))
|
||||
}
|
||||
|
||||
/// Retrieves the [`NodeState`] referenced by the `label` mutably.
|
||||
pub fn get_node_state_mut(
|
||||
&mut self,
|
||||
label: impl RenderLabel,
|
||||
) -> Result<&mut NodeState, RenderGraphError> {
|
||||
let label = label.intern();
|
||||
self.nodes
|
||||
.get_mut(&label)
|
||||
.ok_or(RenderGraphError::InvalidNode(label))
|
||||
}
|
||||
|
||||
/// Retrieves the [`Node`] referenced by the `label`.
|
||||
pub fn get_node<T>(&self, label: impl RenderLabel) -> Result<&T, RenderGraphError>
|
||||
where
|
||||
T: Node,
|
||||
{
|
||||
self.get_node_state(label).and_then(|n| n.node())
|
||||
}
|
||||
|
||||
/// Retrieves the [`Node`] referenced by the `label` mutably.
|
||||
pub fn get_node_mut<T>(&mut self, label: impl RenderLabel) -> Result<&mut T, RenderGraphError>
|
||||
where
|
||||
T: Node,
|
||||
{
|
||||
self.get_node_state_mut(label).and_then(|n| n.node_mut())
|
||||
}
|
||||
|
||||
/// Adds the [`Edge::SlotEdge`] to the graph. This guarantees that the `output_node`
|
||||
/// is run before the `input_node` and also connects the `output_slot` to the `input_slot`.
|
||||
///
|
||||
/// Fails if any invalid [`RenderLabel`]s or [`SlotLabel`]s are given.
|
||||
///
|
||||
/// # See also
|
||||
///
|
||||
/// - [`add_slot_edge`](Self::add_slot_edge) for an infallible version.
|
||||
pub fn try_add_slot_edge(
|
||||
&mut self,
|
||||
output_node: impl RenderLabel,
|
||||
output_slot: impl Into<SlotLabel>,
|
||||
input_node: impl RenderLabel,
|
||||
input_slot: impl Into<SlotLabel>,
|
||||
) -> Result<(), RenderGraphError> {
|
||||
let output_slot = output_slot.into();
|
||||
let input_slot = input_slot.into();
|
||||
|
||||
let output_node = output_node.intern();
|
||||
let input_node = input_node.intern();
|
||||
|
||||
let output_index = self
|
||||
.get_node_state(output_node)?
|
||||
.output_slots
|
||||
.get_slot_index(output_slot.clone())
|
||||
.ok_or(RenderGraphError::InvalidOutputNodeSlot(output_slot))?;
|
||||
let input_index = self
|
||||
.get_node_state(input_node)?
|
||||
.input_slots
|
||||
.get_slot_index(input_slot.clone())
|
||||
.ok_or(RenderGraphError::InvalidInputNodeSlot(input_slot))?;
|
||||
|
||||
let edge = Edge::SlotEdge {
|
||||
output_node,
|
||||
output_index,
|
||||
input_node,
|
||||
input_index,
|
||||
};
|
||||
|
||||
self.validate_edge(&edge, EdgeExistence::DoesNotExist)?;
|
||||
|
||||
{
|
||||
let output_node = self.get_node_state_mut(output_node)?;
|
||||
output_node.edges.add_output_edge(edge.clone())?;
|
||||
}
|
||||
let input_node = self.get_node_state_mut(input_node)?;
|
||||
input_node.edges.add_input_edge(edge)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Adds the [`Edge::SlotEdge`] to the graph. This guarantees that the `output_node`
|
||||
/// is run before the `input_node` and also connects the `output_slot` to the `input_slot`.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// Any invalid [`RenderLabel`]s or [`SlotLabel`]s are given.
|
||||
///
|
||||
/// # See also
|
||||
///
|
||||
/// - [`try_add_slot_edge`](Self::try_add_slot_edge) for a fallible version.
|
||||
pub fn add_slot_edge(
|
||||
&mut self,
|
||||
output_node: impl RenderLabel,
|
||||
output_slot: impl Into<SlotLabel>,
|
||||
input_node: impl RenderLabel,
|
||||
input_slot: impl Into<SlotLabel>,
|
||||
) {
|
||||
self.try_add_slot_edge(output_node, output_slot, input_node, input_slot)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
/// Removes the [`Edge::SlotEdge`] from the graph. If any nodes or slots do not exist then
|
||||
/// nothing happens.
|
||||
pub fn remove_slot_edge(
|
||||
&mut self,
|
||||
output_node: impl RenderLabel,
|
||||
output_slot: impl Into<SlotLabel>,
|
||||
input_node: impl RenderLabel,
|
||||
input_slot: impl Into<SlotLabel>,
|
||||
) -> Result<(), RenderGraphError> {
|
||||
let output_slot = output_slot.into();
|
||||
let input_slot = input_slot.into();
|
||||
|
||||
let output_node = output_node.intern();
|
||||
let input_node = input_node.intern();
|
||||
|
||||
let output_index = self
|
||||
.get_node_state(output_node)?
|
||||
.output_slots
|
||||
.get_slot_index(output_slot.clone())
|
||||
.ok_or(RenderGraphError::InvalidOutputNodeSlot(output_slot))?;
|
||||
let input_index = self
|
||||
.get_node_state(input_node)?
|
||||
.input_slots
|
||||
.get_slot_index(input_slot.clone())
|
||||
.ok_or(RenderGraphError::InvalidInputNodeSlot(input_slot))?;
|
||||
|
||||
let edge = Edge::SlotEdge {
|
||||
output_node,
|
||||
output_index,
|
||||
input_node,
|
||||
input_index,
|
||||
};
|
||||
|
||||
self.validate_edge(&edge, EdgeExistence::Exists)?;
|
||||
|
||||
{
|
||||
let output_node = self.get_node_state_mut(output_node)?;
|
||||
output_node.edges.remove_output_edge(edge.clone())?;
|
||||
}
|
||||
let input_node = self.get_node_state_mut(input_node)?;
|
||||
input_node.edges.remove_input_edge(edge)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Adds the [`Edge::NodeEdge`] to the graph. This guarantees that the `output_node`
|
||||
/// is run before the `input_node`.
|
||||
///
|
||||
/// Fails if any invalid [`RenderLabel`] is given.
|
||||
///
|
||||
/// # See also
|
||||
///
|
||||
/// - [`add_node_edge`](Self::add_node_edge) for an infallible version.
|
||||
pub fn try_add_node_edge(
|
||||
&mut self,
|
||||
output_node: impl RenderLabel,
|
||||
input_node: impl RenderLabel,
|
||||
) -> Result<(), RenderGraphError> {
|
||||
let output_node = output_node.intern();
|
||||
let input_node = input_node.intern();
|
||||
|
||||
let edge = Edge::NodeEdge {
|
||||
output_node,
|
||||
input_node,
|
||||
};
|
||||
|
||||
self.validate_edge(&edge, EdgeExistence::DoesNotExist)?;
|
||||
|
||||
{
|
||||
let output_node = self.get_node_state_mut(output_node)?;
|
||||
output_node.edges.add_output_edge(edge.clone())?;
|
||||
}
|
||||
let input_node = self.get_node_state_mut(input_node)?;
|
||||
input_node.edges.add_input_edge(edge)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Adds the [`Edge::NodeEdge`] to the graph. This guarantees that the `output_node`
|
||||
/// is run before the `input_node`.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// Panics if any invalid [`RenderLabel`] is given.
|
||||
///
|
||||
/// # See also
|
||||
///
|
||||
/// - [`try_add_node_edge`](Self::try_add_node_edge) for a fallible version.
|
||||
pub fn add_node_edge(&mut self, output_node: impl RenderLabel, input_node: impl RenderLabel) {
|
||||
self.try_add_node_edge(output_node, input_node).unwrap();
|
||||
}
|
||||
|
||||
/// Removes the [`Edge::NodeEdge`] from the graph. If either node does not exist then nothing
|
||||
/// happens.
|
||||
pub fn remove_node_edge(
|
||||
&mut self,
|
||||
output_node: impl RenderLabel,
|
||||
input_node: impl RenderLabel,
|
||||
) -> Result<(), RenderGraphError> {
|
||||
let output_node = output_node.intern();
|
||||
let input_node = input_node.intern();
|
||||
|
||||
let edge = Edge::NodeEdge {
|
||||
output_node,
|
||||
input_node,
|
||||
};
|
||||
|
||||
self.validate_edge(&edge, EdgeExistence::Exists)?;
|
||||
|
||||
{
|
||||
let output_node = self.get_node_state_mut(output_node)?;
|
||||
output_node.edges.remove_output_edge(edge.clone())?;
|
||||
}
|
||||
let input_node = self.get_node_state_mut(input_node)?;
|
||||
input_node.edges.remove_input_edge(edge)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Verifies that the edge existence is as expected and
|
||||
/// checks that slot edges are connected correctly.
|
||||
pub fn validate_edge(
|
||||
&mut self,
|
||||
edge: &Edge,
|
||||
should_exist: EdgeExistence,
|
||||
) -> Result<(), RenderGraphError> {
|
||||
if should_exist == EdgeExistence::Exists && !self.has_edge(edge) {
|
||||
return Err(RenderGraphError::EdgeDoesNotExist(edge.clone()));
|
||||
} else if should_exist == EdgeExistence::DoesNotExist && self.has_edge(edge) {
|
||||
return Err(RenderGraphError::EdgeAlreadyExists(edge.clone()));
|
||||
}
|
||||
|
||||
match *edge {
|
||||
Edge::SlotEdge {
|
||||
output_node,
|
||||
output_index,
|
||||
input_node,
|
||||
input_index,
|
||||
} => {
|
||||
let output_node_state = self.get_node_state(output_node)?;
|
||||
let input_node_state = self.get_node_state(input_node)?;
|
||||
|
||||
let output_slot = output_node_state
|
||||
.output_slots
|
||||
.get_slot(output_index)
|
||||
.ok_or(RenderGraphError::InvalidOutputNodeSlot(SlotLabel::Index(
|
||||
output_index,
|
||||
)))?;
|
||||
let input_slot = input_node_state.input_slots.get_slot(input_index).ok_or(
|
||||
RenderGraphError::InvalidInputNodeSlot(SlotLabel::Index(input_index)),
|
||||
)?;
|
||||
|
||||
if let Some(Edge::SlotEdge {
|
||||
output_node: current_output_node,
|
||||
..
|
||||
}) = input_node_state.edges.input_edges().iter().find(|e| {
|
||||
if let Edge::SlotEdge {
|
||||
input_index: current_input_index,
|
||||
..
|
||||
} = e
|
||||
{
|
||||
input_index == *current_input_index
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}) && should_exist == EdgeExistence::DoesNotExist
|
||||
{
|
||||
return Err(RenderGraphError::NodeInputSlotAlreadyOccupied {
|
||||
node: input_node,
|
||||
input_slot: input_index,
|
||||
occupied_by_node: *current_output_node,
|
||||
});
|
||||
}
|
||||
|
||||
if output_slot.slot_type != input_slot.slot_type {
|
||||
return Err(RenderGraphError::MismatchedNodeSlots {
|
||||
output_node,
|
||||
output_slot: output_index,
|
||||
input_node,
|
||||
input_slot: input_index,
|
||||
});
|
||||
}
|
||||
}
|
||||
Edge::NodeEdge { .. } => { /* nothing to validate here */ }
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Checks whether the `edge` already exists in the graph.
|
||||
pub fn has_edge(&self, edge: &Edge) -> bool {
|
||||
let output_node_state = self.get_node_state(edge.get_output_node());
|
||||
let input_node_state = self.get_node_state(edge.get_input_node());
|
||||
if let Ok(output_node_state) = output_node_state
|
||||
&& output_node_state.edges.output_edges().contains(edge)
|
||||
&& let Ok(input_node_state) = input_node_state
|
||||
&& input_node_state.edges.input_edges().contains(edge)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
false
|
||||
}
|
||||
|
||||
/// Returns an iterator over the [`NodeStates`](NodeState).
|
||||
pub fn iter_nodes(&self) -> impl Iterator<Item = &NodeState> {
|
||||
self.nodes.values()
|
||||
}
|
||||
|
||||
/// Returns an iterator over the [`NodeStates`](NodeState), that allows modifying each value.
|
||||
pub fn iter_nodes_mut(&mut self) -> impl Iterator<Item = &mut NodeState> {
|
||||
self.nodes.values_mut()
|
||||
}
|
||||
|
||||
/// Returns an iterator over the sub graphs.
|
||||
pub fn iter_sub_graphs(&self) -> impl Iterator<Item = (InternedRenderSubGraph, &RenderGraph)> {
|
||||
self.sub_graphs.iter().map(|(name, graph)| (*name, graph))
|
||||
}
|
||||
|
||||
/// Returns an iterator over the sub graphs, that allows modifying each value.
|
||||
pub fn iter_sub_graphs_mut(
|
||||
&mut self,
|
||||
) -> impl Iterator<Item = (InternedRenderSubGraph, &mut RenderGraph)> {
|
||||
self.sub_graphs
|
||||
.iter_mut()
|
||||
.map(|(name, graph)| (*name, graph))
|
||||
}
|
||||
|
||||
/// Returns an iterator over a tuple of the input edges and the corresponding output nodes
|
||||
/// for the node referenced by the label.
|
||||
pub fn iter_node_inputs(
|
||||
&self,
|
||||
label: impl RenderLabel,
|
||||
) -> Result<impl Iterator<Item = (&Edge, &NodeState)>, RenderGraphError> {
|
||||
let node = self.get_node_state(label)?;
|
||||
Ok(node
|
||||
.edges
|
||||
.input_edges()
|
||||
.iter()
|
||||
.map(|edge| (edge, edge.get_output_node()))
|
||||
.map(move |(edge, output_node)| (edge, self.get_node_state(output_node).unwrap())))
|
||||
}
|
||||
|
||||
/// Returns an iterator over a tuple of the output edges and the corresponding input nodes
|
||||
/// for the node referenced by the label.
|
||||
pub fn iter_node_outputs(
|
||||
&self,
|
||||
label: impl RenderLabel,
|
||||
) -> Result<impl Iterator<Item = (&Edge, &NodeState)>, RenderGraphError> {
|
||||
let node = self.get_node_state(label)?;
|
||||
Ok(node
|
||||
.edges
|
||||
.output_edges()
|
||||
.iter()
|
||||
.map(|edge| (edge, edge.get_input_node()))
|
||||
.map(move |(edge, input_node)| (edge, self.get_node_state(input_node).unwrap())))
|
||||
}
|
||||
|
||||
/// Adds the `sub_graph` with the `label` to the graph.
|
||||
/// If the label is already present replaces it instead.
|
||||
pub fn add_sub_graph(&mut self, label: impl RenderSubGraph, sub_graph: RenderGraph) {
|
||||
self.sub_graphs.insert(label.intern(), sub_graph);
|
||||
}
|
||||
|
||||
/// Removes the `sub_graph` with the `label` from the graph.
|
||||
/// If the label does not exist then nothing happens.
|
||||
pub fn remove_sub_graph(&mut self, label: impl RenderSubGraph) {
|
||||
self.sub_graphs.remove(&label.intern());
|
||||
}
|
||||
|
||||
/// Retrieves the sub graph corresponding to the `label`.
|
||||
pub fn get_sub_graph(&self, label: impl RenderSubGraph) -> Option<&RenderGraph> {
|
||||
self.sub_graphs.get(&label.intern())
|
||||
}
|
||||
|
||||
/// Retrieves the sub graph corresponding to the `label` mutably.
|
||||
pub fn get_sub_graph_mut(&mut self, label: impl RenderSubGraph) -> Option<&mut RenderGraph> {
|
||||
self.sub_graphs.get_mut(&label.intern())
|
||||
}
|
||||
|
||||
/// Retrieves the sub graph corresponding to the `label`.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// Panics if any invalid subgraph label is given.
|
||||
///
|
||||
/// # See also
|
||||
///
|
||||
/// - [`get_sub_graph`](Self::get_sub_graph) for a fallible version.
|
||||
pub fn sub_graph(&self, label: impl RenderSubGraph) -> &RenderGraph {
|
||||
let label = label.intern();
|
||||
self.sub_graphs
|
||||
.get(&label)
|
||||
.unwrap_or_else(|| panic!("Subgraph {label:?} not found"))
|
||||
}
|
||||
|
||||
/// Retrieves the sub graph corresponding to the `label` mutably.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// Panics if any invalid subgraph label is given.
|
||||
///
|
||||
/// # See also
|
||||
///
|
||||
/// - [`get_sub_graph_mut`](Self::get_sub_graph_mut) for a fallible version.
|
||||
pub fn sub_graph_mut(&mut self, label: impl RenderSubGraph) -> &mut RenderGraph {
|
||||
let label = label.intern();
|
||||
self.sub_graphs
|
||||
.get_mut(&label)
|
||||
.unwrap_or_else(|| panic!("Subgraph {label:?} not found"))
|
||||
}
|
||||
}
|
||||
|
||||
impl Debug for RenderGraph {
|
||||
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
|
||||
for node in self.iter_nodes() {
|
||||
writeln!(f, "{:?}", node.label)?;
|
||||
writeln!(f, " in: {:?}", node.input_slots)?;
|
||||
writeln!(f, " out: {:?}", node.output_slots)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// A [`Node`] which acts as an entry point for a [`RenderGraph`] with custom inputs.
|
||||
/// It has the same input and output slots and simply copies them over when run.
|
||||
pub struct GraphInputNode {
|
||||
inputs: Vec<SlotInfo>,
|
||||
}
|
||||
|
||||
impl Node for GraphInputNode {
|
||||
fn input(&self) -> Vec<SlotInfo> {
|
||||
self.inputs.clone()
|
||||
}
|
||||
|
||||
fn output(&self) -> Vec<SlotInfo> {
|
||||
self.inputs.clone()
|
||||
}
|
||||
|
||||
fn run(
|
||||
&self,
|
||||
graph: &mut RenderGraphContext,
|
||||
_render_context: &mut RenderContext,
|
||||
_world: &World,
|
||||
) -> Result<(), NodeRunError> {
|
||||
for i in 0..graph.inputs().len() {
|
||||
let input = graph.inputs()[i].clone();
|
||||
graph.set_output(i, input)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::{
|
||||
render_graph::{
|
||||
node::IntoRenderNodeArray, Edge, InternedRenderLabel, Node, NodeRunError, RenderGraph,
|
||||
RenderGraphContext, RenderGraphError, RenderLabel, SlotInfo, SlotType,
|
||||
},
|
||||
renderer::RenderContext,
|
||||
};
|
||||
use bevy_ecs::world::{FromWorld, World};
|
||||
use bevy_platform::collections::HashSet;
|
||||
|
||||
#[derive(Debug, Hash, PartialEq, Eq, Clone, RenderLabel)]
|
||||
enum TestLabel {
|
||||
A,
|
||||
B,
|
||||
C,
|
||||
D,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct TestNode {
|
||||
inputs: Vec<SlotInfo>,
|
||||
outputs: Vec<SlotInfo>,
|
||||
}
|
||||
|
||||
impl TestNode {
|
||||
pub fn new(inputs: usize, outputs: usize) -> Self {
|
||||
TestNode {
|
||||
inputs: (0..inputs)
|
||||
.map(|i| SlotInfo::new(format!("in_{i}"), SlotType::TextureView))
|
||||
.collect(),
|
||||
outputs: (0..outputs)
|
||||
.map(|i| SlotInfo::new(format!("out_{i}"), SlotType::TextureView))
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Node for TestNode {
|
||||
fn input(&self) -> Vec<SlotInfo> {
|
||||
self.inputs.clone()
|
||||
}
|
||||
|
||||
fn output(&self) -> Vec<SlotInfo> {
|
||||
self.outputs.clone()
|
||||
}
|
||||
|
||||
fn run(
|
||||
&self,
|
||||
_: &mut RenderGraphContext,
|
||||
_: &mut RenderContext,
|
||||
_: &World,
|
||||
) -> Result<(), NodeRunError> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn input_nodes(label: impl RenderLabel, graph: &RenderGraph) -> HashSet<InternedRenderLabel> {
|
||||
graph
|
||||
.iter_node_inputs(label)
|
||||
.unwrap()
|
||||
.map(|(_edge, node)| node.label)
|
||||
.collect::<HashSet<InternedRenderLabel>>()
|
||||
}
|
||||
|
||||
fn output_nodes(label: impl RenderLabel, graph: &RenderGraph) -> HashSet<InternedRenderLabel> {
|
||||
graph
|
||||
.iter_node_outputs(label)
|
||||
.unwrap()
|
||||
.map(|(_edge, node)| node.label)
|
||||
.collect::<HashSet<InternedRenderLabel>>()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_graph_edges() {
|
||||
let mut graph = RenderGraph::default();
|
||||
graph.add_node(TestLabel::A, TestNode::new(0, 1));
|
||||
graph.add_node(TestLabel::B, TestNode::new(0, 1));
|
||||
graph.add_node(TestLabel::C, TestNode::new(1, 1));
|
||||
graph.add_node(TestLabel::D, TestNode::new(1, 0));
|
||||
|
||||
graph.add_slot_edge(TestLabel::A, "out_0", TestLabel::C, "in_0");
|
||||
graph.add_node_edge(TestLabel::B, TestLabel::C);
|
||||
graph.add_slot_edge(TestLabel::C, 0, TestLabel::D, 0);
|
||||
|
||||
assert!(
|
||||
input_nodes(TestLabel::A, &graph).is_empty(),
|
||||
"A has no inputs"
|
||||
);
|
||||
assert_eq!(
|
||||
output_nodes(TestLabel::A, &graph),
|
||||
HashSet::from_iter((TestLabel::C,).into_array()),
|
||||
"A outputs to C"
|
||||
);
|
||||
|
||||
assert!(
|
||||
input_nodes(TestLabel::B, &graph).is_empty(),
|
||||
"B has no inputs"
|
||||
);
|
||||
assert_eq!(
|
||||
output_nodes(TestLabel::B, &graph),
|
||||
HashSet::from_iter((TestLabel::C,).into_array()),
|
||||
"B outputs to C"
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
input_nodes(TestLabel::C, &graph),
|
||||
HashSet::from_iter((TestLabel::A, TestLabel::B).into_array()),
|
||||
"A and B input to C"
|
||||
);
|
||||
assert_eq!(
|
||||
output_nodes(TestLabel::C, &graph),
|
||||
HashSet::from_iter((TestLabel::D,).into_array()),
|
||||
"C outputs to D"
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
input_nodes(TestLabel::D, &graph),
|
||||
HashSet::from_iter((TestLabel::C,).into_array()),
|
||||
"C inputs to D"
|
||||
);
|
||||
assert!(
|
||||
output_nodes(TestLabel::D, &graph).is_empty(),
|
||||
"D has no outputs"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_get_node_typed() {
|
||||
struct MyNode {
|
||||
value: usize,
|
||||
}
|
||||
|
||||
impl Node for MyNode {
|
||||
fn run(
|
||||
&self,
|
||||
_: &mut RenderGraphContext,
|
||||
_: &mut RenderContext,
|
||||
_: &World,
|
||||
) -> Result<(), NodeRunError> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
let mut graph = RenderGraph::default();
|
||||
|
||||
graph.add_node(TestLabel::A, MyNode { value: 42 });
|
||||
|
||||
let node: &MyNode = graph.get_node(TestLabel::A).unwrap();
|
||||
assert_eq!(node.value, 42, "node value matches");
|
||||
|
||||
let result: Result<&TestNode, RenderGraphError> = graph.get_node(TestLabel::A);
|
||||
assert_eq!(
|
||||
result.unwrap_err(),
|
||||
RenderGraphError::WrongNodeType,
|
||||
"expect a wrong node type error"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_slot_already_occupied() {
|
||||
let mut graph = RenderGraph::default();
|
||||
|
||||
graph.add_node(TestLabel::A, TestNode::new(0, 1));
|
||||
graph.add_node(TestLabel::B, TestNode::new(0, 1));
|
||||
graph.add_node(TestLabel::C, TestNode::new(1, 1));
|
||||
|
||||
graph.add_slot_edge(TestLabel::A, 0, TestLabel::C, 0);
|
||||
assert_eq!(
|
||||
graph.try_add_slot_edge(TestLabel::B, 0, TestLabel::C, 0),
|
||||
Err(RenderGraphError::NodeInputSlotAlreadyOccupied {
|
||||
node: TestLabel::C.intern(),
|
||||
input_slot: 0,
|
||||
occupied_by_node: TestLabel::A.intern(),
|
||||
}),
|
||||
"Adding to a slot that is already occupied should return an error"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_edge_already_exists() {
|
||||
let mut graph = RenderGraph::default();
|
||||
|
||||
graph.add_node(TestLabel::A, TestNode::new(0, 1));
|
||||
graph.add_node(TestLabel::B, TestNode::new(1, 0));
|
||||
|
||||
graph.add_slot_edge(TestLabel::A, 0, TestLabel::B, 0);
|
||||
assert_eq!(
|
||||
graph.try_add_slot_edge(TestLabel::A, 0, TestLabel::B, 0),
|
||||
Err(RenderGraphError::EdgeAlreadyExists(Edge::SlotEdge {
|
||||
output_node: TestLabel::A.intern(),
|
||||
output_index: 0,
|
||||
input_node: TestLabel::B.intern(),
|
||||
input_index: 0,
|
||||
})),
|
||||
"Adding to a duplicate edge should return an error"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_add_node_edges() {
|
||||
struct SimpleNode;
|
||||
impl Node for SimpleNode {
|
||||
fn run(
|
||||
&self,
|
||||
_graph: &mut RenderGraphContext,
|
||||
_render_context: &mut RenderContext,
|
||||
_world: &World,
|
||||
) -> Result<(), NodeRunError> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
impl FromWorld for SimpleNode {
|
||||
fn from_world(_world: &mut World) -> Self {
|
||||
Self
|
||||
}
|
||||
}
|
||||
|
||||
let mut graph = RenderGraph::default();
|
||||
graph.add_node(TestLabel::A, SimpleNode);
|
||||
graph.add_node(TestLabel::B, SimpleNode);
|
||||
graph.add_node(TestLabel::C, SimpleNode);
|
||||
|
||||
graph.add_node_edges((TestLabel::A, TestLabel::B, TestLabel::C));
|
||||
|
||||
assert_eq!(
|
||||
output_nodes(TestLabel::A, &graph),
|
||||
HashSet::from_iter((TestLabel::B,).into_array()),
|
||||
"A -> B"
|
||||
);
|
||||
assert_eq!(
|
||||
input_nodes(TestLabel::B, &graph),
|
||||
HashSet::from_iter((TestLabel::A,).into_array()),
|
||||
"A -> B"
|
||||
);
|
||||
assert_eq!(
|
||||
output_nodes(TestLabel::B, &graph),
|
||||
HashSet::from_iter((TestLabel::C,).into_array()),
|
||||
"B -> C"
|
||||
);
|
||||
assert_eq!(
|
||||
input_nodes(TestLabel::C, &graph),
|
||||
HashSet::from_iter((TestLabel::B,).into_array()),
|
||||
"B -> C"
|
||||
);
|
||||
}
|
||||
}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
mod app;
|
||||
mod camera_driver_node;
|
||||
mod context;
|
||||
mod edge;
|
||||
mod graph;
|
||||
mod node;
|
||||
mod node_slot;
|
||||
|
||||
pub use app::*;
|
||||
pub use camera_driver_node::*;
|
||||
pub use context::*;
|
||||
pub use edge::*;
|
||||
pub use graph::*;
|
||||
pub use node::*;
|
||||
pub use node_slot::*;
|
||||
|
||||
use thiserror::Error;
|
||||
|
||||
#[derive(Error, Debug, Eq, PartialEq)]
|
||||
pub enum RenderGraphError {
|
||||
#[error("node {0:?} does not exist")]
|
||||
InvalidNode(InternedRenderLabel),
|
||||
#[error("output node slot does not exist")]
|
||||
InvalidOutputNodeSlot(SlotLabel),
|
||||
#[error("input node slot does not exist")]
|
||||
InvalidInputNodeSlot(SlotLabel),
|
||||
#[error("node does not match the given type")]
|
||||
WrongNodeType,
|
||||
#[error("attempted to connect output slot {output_slot} from node {output_node:?} to incompatible input slot {input_slot} from node {input_node:?}")]
|
||||
MismatchedNodeSlots {
|
||||
output_node: InternedRenderLabel,
|
||||
output_slot: usize,
|
||||
input_node: InternedRenderLabel,
|
||||
input_slot: usize,
|
||||
},
|
||||
#[error("attempted to add an edge that already exists")]
|
||||
EdgeAlreadyExists(Edge),
|
||||
#[error("attempted to remove an edge that does not exist")]
|
||||
EdgeDoesNotExist(Edge),
|
||||
#[error("node {node:?} has an unconnected input slot {input_slot}")]
|
||||
UnconnectedNodeInputSlot {
|
||||
node: InternedRenderLabel,
|
||||
input_slot: usize,
|
||||
},
|
||||
#[error("node {node:?} has an unconnected output slot {output_slot}")]
|
||||
UnconnectedNodeOutputSlot {
|
||||
node: InternedRenderLabel,
|
||||
output_slot: usize,
|
||||
},
|
||||
#[error("node {node:?} input slot {input_slot} already occupied by {occupied_by_node:?}")]
|
||||
NodeInputSlotAlreadyOccupied {
|
||||
node: InternedRenderLabel,
|
||||
input_slot: usize,
|
||||
occupied_by_node: InternedRenderLabel,
|
||||
},
|
||||
}
|
||||
+426
@@ -0,0 +1,426 @@
|
||||
use crate::{
|
||||
render_graph::{
|
||||
Edge, InputSlotError, OutputSlotError, RenderGraphContext, RenderGraphError,
|
||||
RunSubGraphError, SlotInfo, SlotInfos,
|
||||
},
|
||||
render_phase::DrawError,
|
||||
renderer::RenderContext,
|
||||
};
|
||||
pub use bevy_ecs::label::DynEq;
|
||||
use bevy_ecs::{
|
||||
define_label,
|
||||
intern::Interned,
|
||||
query::{QueryItem, QueryState, ReadOnlyQueryData},
|
||||
world::{FromWorld, World},
|
||||
};
|
||||
use core::fmt::Debug;
|
||||
use downcast_rs::{impl_downcast, Downcast};
|
||||
use thiserror::Error;
|
||||
use variadics_please::all_tuples_with_size;
|
||||
|
||||
pub use bevy_render_macros::RenderLabel;
|
||||
|
||||
use super::{InternedRenderSubGraph, RenderSubGraph};
|
||||
|
||||
define_label!(
|
||||
#[diagnostic::on_unimplemented(
|
||||
note = "consider annotating `{Self}` with `#[derive(RenderLabel)]`"
|
||||
)]
|
||||
/// A strongly-typed class of labels used to identify a [`Node`] in a render graph.
|
||||
RenderLabel,
|
||||
RENDER_LABEL_INTERNER
|
||||
);
|
||||
|
||||
/// A shorthand for `Interned<dyn RenderLabel>`.
|
||||
pub type InternedRenderLabel = Interned<dyn RenderLabel>;
|
||||
|
||||
pub trait IntoRenderNodeArray<const N: usize> {
|
||||
fn into_array(self) -> [InternedRenderLabel; N];
|
||||
}
|
||||
|
||||
impl<const N: usize> IntoRenderNodeArray<N> for Vec<InternedRenderLabel> {
|
||||
fn into_array(self) -> [InternedRenderLabel; N] {
|
||||
self.try_into().unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! impl_render_label_tuples {
|
||||
($N: expr, $(#[$meta:meta])* $(($T: ident, $I: ident)),*) => {
|
||||
$(#[$meta])*
|
||||
impl<$($T: RenderLabel),*> IntoRenderNodeArray<$N> for ($($T,)*) {
|
||||
#[inline]
|
||||
fn into_array(self) -> [InternedRenderLabel; $N] {
|
||||
let ($($I,)*) = self;
|
||||
[$($I.intern(), )*]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
all_tuples_with_size!(
|
||||
#[doc(fake_variadic)]
|
||||
impl_render_label_tuples,
|
||||
1,
|
||||
32,
|
||||
T,
|
||||
l
|
||||
);
|
||||
|
||||
/// A render node that can be added to a [`RenderGraph`](super::RenderGraph).
|
||||
///
|
||||
/// Nodes are the fundamental part of the graph and used to extend its functionality, by
|
||||
/// generating draw calls and/or running subgraphs.
|
||||
/// They are added via the `render_graph::add_node(my_node)` method.
|
||||
///
|
||||
/// To determine their position in the graph and ensure that all required dependencies (inputs)
|
||||
/// are already executed, [`Edges`](Edge) are used.
|
||||
///
|
||||
/// A node can produce outputs used as dependencies by other nodes.
|
||||
/// Those inputs and outputs are called slots and are the default way of passing render data
|
||||
/// inside the graph. For more information see [`SlotType`](super::SlotType).
|
||||
pub trait Node: Downcast + Send + Sync + 'static {
|
||||
/// Specifies the required input slots for this node.
|
||||
/// They will then be available during the run method inside the [`RenderGraphContext`].
|
||||
fn input(&self) -> Vec<SlotInfo> {
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
/// Specifies the produced output slots for this node.
|
||||
/// They can then be passed one inside [`RenderGraphContext`] during the run method.
|
||||
fn output(&self) -> Vec<SlotInfo> {
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
/// Updates internal node state using the current render [`World`] prior to the run method.
|
||||
fn update(&mut self, _world: &mut World) {}
|
||||
|
||||
/// Runs the graph node logic, issues draw calls, updates the output slots and
|
||||
/// optionally queues up subgraphs for execution. The graph data, input and output values are
|
||||
/// passed via the [`RenderGraphContext`].
|
||||
fn run<'w>(
|
||||
&self,
|
||||
graph: &mut RenderGraphContext,
|
||||
render_context: &mut RenderContext<'w>,
|
||||
world: &'w World,
|
||||
) -> Result<(), NodeRunError>;
|
||||
}
|
||||
|
||||
impl_downcast!(Node);
|
||||
|
||||
#[derive(Error, Debug, Eq, PartialEq)]
|
||||
pub enum NodeRunError {
|
||||
#[error("encountered an input slot error")]
|
||||
InputSlotError(#[from] InputSlotError),
|
||||
#[error("encountered an output slot error")]
|
||||
OutputSlotError(#[from] OutputSlotError),
|
||||
#[error("encountered an error when running a sub-graph")]
|
||||
RunSubGraphError(#[from] RunSubGraphError),
|
||||
#[error("encountered an error when executing draw command")]
|
||||
DrawError(#[from] DrawError),
|
||||
}
|
||||
|
||||
/// A collection of input and output [`Edges`](Edge) for a [`Node`].
|
||||
#[derive(Debug)]
|
||||
pub struct Edges {
|
||||
label: InternedRenderLabel,
|
||||
input_edges: Vec<Edge>,
|
||||
output_edges: Vec<Edge>,
|
||||
}
|
||||
|
||||
impl Edges {
|
||||
/// Returns all "input edges" (edges going "in") for this node .
|
||||
#[inline]
|
||||
pub fn input_edges(&self) -> &[Edge] {
|
||||
&self.input_edges
|
||||
}
|
||||
|
||||
/// Returns all "output edges" (edges going "out") for this node .
|
||||
#[inline]
|
||||
pub fn output_edges(&self) -> &[Edge] {
|
||||
&self.output_edges
|
||||
}
|
||||
|
||||
/// Returns this node's label.
|
||||
#[inline]
|
||||
pub fn label(&self) -> InternedRenderLabel {
|
||||
self.label
|
||||
}
|
||||
|
||||
/// Adds an edge to the `input_edges` if it does not already exist.
|
||||
pub(crate) fn add_input_edge(&mut self, edge: Edge) -> Result<(), RenderGraphError> {
|
||||
if self.has_input_edge(&edge) {
|
||||
return Err(RenderGraphError::EdgeAlreadyExists(edge));
|
||||
}
|
||||
self.input_edges.push(edge);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Removes an edge from the `input_edges` if it exists.
|
||||
pub(crate) fn remove_input_edge(&mut self, edge: Edge) -> Result<(), RenderGraphError> {
|
||||
if let Some(index) = self.input_edges.iter().position(|e| *e == edge) {
|
||||
self.input_edges.swap_remove(index);
|
||||
Ok(())
|
||||
} else {
|
||||
Err(RenderGraphError::EdgeDoesNotExist(edge))
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds an edge to the `output_edges` if it does not already exist.
|
||||
pub(crate) fn add_output_edge(&mut self, edge: Edge) -> Result<(), RenderGraphError> {
|
||||
if self.has_output_edge(&edge) {
|
||||
return Err(RenderGraphError::EdgeAlreadyExists(edge));
|
||||
}
|
||||
self.output_edges.push(edge);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Removes an edge from the `output_edges` if it exists.
|
||||
pub(crate) fn remove_output_edge(&mut self, edge: Edge) -> Result<(), RenderGraphError> {
|
||||
if let Some(index) = self.output_edges.iter().position(|e| *e == edge) {
|
||||
self.output_edges.swap_remove(index);
|
||||
Ok(())
|
||||
} else {
|
||||
Err(RenderGraphError::EdgeDoesNotExist(edge))
|
||||
}
|
||||
}
|
||||
|
||||
/// Checks whether the input edge already exists.
|
||||
pub fn has_input_edge(&self, edge: &Edge) -> bool {
|
||||
self.input_edges.contains(edge)
|
||||
}
|
||||
|
||||
/// Checks whether the output edge already exists.
|
||||
pub fn has_output_edge(&self, edge: &Edge) -> bool {
|
||||
self.output_edges.contains(edge)
|
||||
}
|
||||
|
||||
/// Searches the `input_edges` for a [`Edge::SlotEdge`],
|
||||
/// which `input_index` matches the `index`;
|
||||
pub fn get_input_slot_edge(&self, index: usize) -> Result<&Edge, RenderGraphError> {
|
||||
self.input_edges
|
||||
.iter()
|
||||
.find(|e| {
|
||||
if let Edge::SlotEdge { input_index, .. } = e {
|
||||
*input_index == index
|
||||
} else {
|
||||
false
|
||||
}
|
||||
})
|
||||
.ok_or(RenderGraphError::UnconnectedNodeInputSlot {
|
||||
input_slot: index,
|
||||
node: self.label,
|
||||
})
|
||||
}
|
||||
|
||||
/// Searches the `output_edges` for a [`Edge::SlotEdge`],
|
||||
/// which `output_index` matches the `index`;
|
||||
pub fn get_output_slot_edge(&self, index: usize) -> Result<&Edge, RenderGraphError> {
|
||||
self.output_edges
|
||||
.iter()
|
||||
.find(|e| {
|
||||
if let Edge::SlotEdge { output_index, .. } = e {
|
||||
*output_index == index
|
||||
} else {
|
||||
false
|
||||
}
|
||||
})
|
||||
.ok_or(RenderGraphError::UnconnectedNodeOutputSlot {
|
||||
output_slot: index,
|
||||
node: self.label,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The internal representation of a [`Node`], with all data required
|
||||
/// by the [`RenderGraph`](super::RenderGraph).
|
||||
///
|
||||
/// The `input_slots` and `output_slots` are provided by the `node`.
|
||||
pub struct NodeState {
|
||||
pub label: InternedRenderLabel,
|
||||
/// The name of the type that implements [`Node`].
|
||||
pub type_name: &'static str,
|
||||
pub node: Box<dyn Node>,
|
||||
pub input_slots: SlotInfos,
|
||||
pub output_slots: SlotInfos,
|
||||
pub edges: Edges,
|
||||
}
|
||||
|
||||
impl Debug for NodeState {
|
||||
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
|
||||
writeln!(f, "{:?} ({})", self.label, self.type_name)
|
||||
}
|
||||
}
|
||||
|
||||
impl NodeState {
|
||||
/// Creates an [`NodeState`] without edges, but the `input_slots` and `output_slots`
|
||||
/// are provided by the `node`.
|
||||
pub fn new<T>(label: InternedRenderLabel, node: T) -> Self
|
||||
where
|
||||
T: Node,
|
||||
{
|
||||
NodeState {
|
||||
label,
|
||||
input_slots: node.input().into(),
|
||||
output_slots: node.output().into(),
|
||||
node: Box::new(node),
|
||||
type_name: core::any::type_name::<T>(),
|
||||
edges: Edges {
|
||||
label,
|
||||
input_edges: Vec::new(),
|
||||
output_edges: Vec::new(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Retrieves the [`Node`].
|
||||
pub fn node<T>(&self) -> Result<&T, RenderGraphError>
|
||||
where
|
||||
T: Node,
|
||||
{
|
||||
self.node
|
||||
.downcast_ref::<T>()
|
||||
.ok_or(RenderGraphError::WrongNodeType)
|
||||
}
|
||||
|
||||
/// Retrieves the [`Node`] mutably.
|
||||
pub fn node_mut<T>(&mut self) -> Result<&mut T, RenderGraphError>
|
||||
where
|
||||
T: Node,
|
||||
{
|
||||
self.node
|
||||
.downcast_mut::<T>()
|
||||
.ok_or(RenderGraphError::WrongNodeType)
|
||||
}
|
||||
|
||||
/// Validates that each input slot corresponds to an input edge.
|
||||
pub fn validate_input_slots(&self) -> Result<(), RenderGraphError> {
|
||||
for i in 0..self.input_slots.len() {
|
||||
self.edges.get_input_slot_edge(i)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Validates that each output slot corresponds to an output edge.
|
||||
pub fn validate_output_slots(&self) -> Result<(), RenderGraphError> {
|
||||
for i in 0..self.output_slots.len() {
|
||||
self.edges.get_output_slot_edge(i)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// A [`Node`] without any inputs, outputs and subgraphs, which does nothing when run.
|
||||
/// Used (as a label) to bundle multiple dependencies into one inside
|
||||
/// the [`RenderGraph`](super::RenderGraph).
|
||||
#[derive(Default)]
|
||||
pub struct EmptyNode;
|
||||
|
||||
impl Node for EmptyNode {
|
||||
fn run(
|
||||
&self,
|
||||
_graph: &mut RenderGraphContext,
|
||||
_render_context: &mut RenderContext,
|
||||
_world: &World,
|
||||
) -> Result<(), NodeRunError> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// A [`RenderGraph`](super::RenderGraph) [`Node`] that runs the configured subgraph once.
|
||||
/// This makes it easier to insert sub-graph runs into a graph.
|
||||
pub struct RunGraphOnViewNode {
|
||||
sub_graph: InternedRenderSubGraph,
|
||||
}
|
||||
|
||||
impl RunGraphOnViewNode {
|
||||
pub fn new<T: RenderSubGraph>(sub_graph: T) -> Self {
|
||||
Self {
|
||||
sub_graph: sub_graph.intern(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Node for RunGraphOnViewNode {
|
||||
fn run(
|
||||
&self,
|
||||
graph: &mut RenderGraphContext,
|
||||
_render_context: &mut RenderContext,
|
||||
_world: &World,
|
||||
) -> Result<(), NodeRunError> {
|
||||
graph.run_sub_graph(self.sub_graph, vec![], Some(graph.view_entity()), None)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// This trait should be used instead of the [`Node`] trait when making a render node that runs on a view.
|
||||
///
|
||||
/// It is intended to be used with [`ViewNodeRunner`]
|
||||
pub trait ViewNode {
|
||||
/// The query that will be used on the view entity.
|
||||
/// It is guaranteed to run on the view entity, so there's no need for a filter
|
||||
type ViewQuery: ReadOnlyQueryData;
|
||||
|
||||
/// Updates internal node state using the current render [`World`] prior to the run method.
|
||||
fn update(&mut self, _world: &mut World) {}
|
||||
|
||||
/// Runs the graph node logic, issues draw calls, updates the output slots and
|
||||
/// optionally queues up subgraphs for execution. The graph data, input and output values are
|
||||
/// passed via the [`RenderGraphContext`].
|
||||
fn run<'w>(
|
||||
&self,
|
||||
graph: &mut RenderGraphContext,
|
||||
render_context: &mut RenderContext<'w>,
|
||||
view_query: QueryItem<'w, '_, Self::ViewQuery>,
|
||||
world: &'w World,
|
||||
) -> Result<(), NodeRunError>;
|
||||
}
|
||||
|
||||
/// This [`Node`] can be used to run any [`ViewNode`].
|
||||
/// It will take care of updating the view query in `update()` and running the query in `run()`.
|
||||
///
|
||||
/// This [`Node`] exists to help reduce boilerplate when making a render node that runs on a view.
|
||||
pub struct ViewNodeRunner<N: ViewNode> {
|
||||
view_query: QueryState<N::ViewQuery>,
|
||||
node: N,
|
||||
}
|
||||
|
||||
impl<N: ViewNode> ViewNodeRunner<N> {
|
||||
pub fn new(node: N, world: &mut World) -> Self {
|
||||
Self {
|
||||
view_query: world.query_filtered(),
|
||||
node,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<N: ViewNode + FromWorld> FromWorld for ViewNodeRunner<N> {
|
||||
fn from_world(world: &mut World) -> Self {
|
||||
Self::new(N::from_world(world), world)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Node for ViewNodeRunner<T>
|
||||
where
|
||||
T: ViewNode + Send + Sync + 'static,
|
||||
{
|
||||
fn update(&mut self, world: &mut World) {
|
||||
self.view_query.update_archetypes(world);
|
||||
self.node.update(world);
|
||||
}
|
||||
|
||||
fn run<'w>(
|
||||
&self,
|
||||
graph: &mut RenderGraphContext,
|
||||
render_context: &mut RenderContext<'w>,
|
||||
world: &'w World,
|
||||
) -> Result<(), NodeRunError> {
|
||||
let Ok(view) = self.view_query.get_manual(world, graph.view_entity()) else {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
ViewNode::run(&self.node, graph, render_context, view, world)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
use alloc::borrow::Cow;
|
||||
use bevy_ecs::entity::Entity;
|
||||
use core::fmt;
|
||||
use derive_more::derive::From;
|
||||
|
||||
use crate::render_resource::{Buffer, Sampler, TextureView};
|
||||
|
||||
/// A value passed between render [`Nodes`](super::Node).
|
||||
/// Corresponds to the [`SlotType`] specified in the [`RenderGraph`](super::RenderGraph).
|
||||
///
|
||||
/// Slots can have four different types of values:
|
||||
/// [`Buffer`], [`TextureView`], [`Sampler`] and [`Entity`].
|
||||
///
|
||||
/// These values do not contain the actual render data, but only the ids to retrieve them.
|
||||
#[derive(Debug, Clone, From)]
|
||||
pub enum SlotValue {
|
||||
/// A GPU-accessible [`Buffer`].
|
||||
Buffer(Buffer),
|
||||
/// A [`TextureView`] describes a texture used in a pipeline.
|
||||
TextureView(TextureView),
|
||||
/// A texture [`Sampler`] defines how a pipeline will sample from a [`TextureView`].
|
||||
Sampler(Sampler),
|
||||
/// An entity from the ECS.
|
||||
Entity(Entity),
|
||||
}
|
||||
|
||||
impl SlotValue {
|
||||
/// Returns the [`SlotType`] of this value.
|
||||
pub fn slot_type(&self) -> SlotType {
|
||||
match self {
|
||||
SlotValue::Buffer(_) => SlotType::Buffer,
|
||||
SlotValue::TextureView(_) => SlotType::TextureView,
|
||||
SlotValue::Sampler(_) => SlotType::Sampler,
|
||||
SlotValue::Entity(_) => SlotType::Entity,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Describes the render resources created (output) or used (input) by
|
||||
/// the render [`Nodes`](super::Node).
|
||||
///
|
||||
/// This should not be confused with [`SlotValue`], which actually contains the passed data.
|
||||
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
|
||||
pub enum SlotType {
|
||||
/// A GPU-accessible [`Buffer`].
|
||||
Buffer,
|
||||
/// A [`TextureView`] describes a texture used in a pipeline.
|
||||
TextureView,
|
||||
/// A texture [`Sampler`] defines how a pipeline will sample from a [`TextureView`].
|
||||
Sampler,
|
||||
/// An entity from the ECS.
|
||||
Entity,
|
||||
}
|
||||
|
||||
impl fmt::Display for SlotType {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
let s = match self {
|
||||
SlotType::Buffer => "Buffer",
|
||||
SlotType::TextureView => "TextureView",
|
||||
SlotType::Sampler => "Sampler",
|
||||
SlotType::Entity => "Entity",
|
||||
};
|
||||
|
||||
f.write_str(s)
|
||||
}
|
||||
}
|
||||
|
||||
/// A [`SlotLabel`] is used to reference a slot by either its name or index
|
||||
/// inside the [`RenderGraph`](super::RenderGraph).
|
||||
#[derive(Debug, Clone, Eq, PartialEq, From)]
|
||||
pub enum SlotLabel {
|
||||
Index(usize),
|
||||
Name(Cow<'static, str>),
|
||||
}
|
||||
|
||||
impl From<&SlotLabel> for SlotLabel {
|
||||
fn from(value: &SlotLabel) -> Self {
|
||||
value.clone()
|
||||
}
|
||||
}
|
||||
|
||||
impl From<String> for SlotLabel {
|
||||
fn from(value: String) -> Self {
|
||||
SlotLabel::Name(value.into())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&'static str> for SlotLabel {
|
||||
fn from(value: &'static str) -> Self {
|
||||
SlotLabel::Name(value.into())
|
||||
}
|
||||
}
|
||||
|
||||
/// The internal representation of a slot, which specifies its [`SlotType`] and name.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct SlotInfo {
|
||||
pub name: Cow<'static, str>,
|
||||
pub slot_type: SlotType,
|
||||
}
|
||||
|
||||
impl SlotInfo {
|
||||
pub fn new(name: impl Into<Cow<'static, str>>, slot_type: SlotType) -> Self {
|
||||
SlotInfo {
|
||||
name: name.into(),
|
||||
slot_type,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A collection of input or output [`SlotInfos`](SlotInfo) for
|
||||
/// a [`NodeState`](super::NodeState).
|
||||
#[derive(Default, Debug)]
|
||||
pub struct SlotInfos {
|
||||
slots: Vec<SlotInfo>,
|
||||
}
|
||||
|
||||
impl<T: IntoIterator<Item = SlotInfo>> From<T> for SlotInfos {
|
||||
fn from(slots: T) -> Self {
|
||||
SlotInfos {
|
||||
slots: slots.into_iter().collect(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl SlotInfos {
|
||||
/// Returns the count of slots.
|
||||
#[inline]
|
||||
pub fn len(&self) -> usize {
|
||||
self.slots.len()
|
||||
}
|
||||
|
||||
/// Returns true if there are no slots.
|
||||
#[inline]
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.slots.is_empty()
|
||||
}
|
||||
|
||||
/// Retrieves the [`SlotInfo`] for the provided label.
|
||||
pub fn get_slot(&self, label: impl Into<SlotLabel>) -> Option<&SlotInfo> {
|
||||
let label = label.into();
|
||||
let index = self.get_slot_index(label)?;
|
||||
self.slots.get(index)
|
||||
}
|
||||
|
||||
/// Retrieves the [`SlotInfo`] for the provided label mutably.
|
||||
pub fn get_slot_mut(&mut self, label: impl Into<SlotLabel>) -> Option<&mut SlotInfo> {
|
||||
let label = label.into();
|
||||
let index = self.get_slot_index(label)?;
|
||||
self.slots.get_mut(index)
|
||||
}
|
||||
|
||||
/// Retrieves the index (inside input or output slots) of the slot for the provided label.
|
||||
pub fn get_slot_index(&self, label: impl Into<SlotLabel>) -> Option<usize> {
|
||||
let label = label.into();
|
||||
match label {
|
||||
SlotLabel::Index(index) => Some(index),
|
||||
SlotLabel::Name(ref name) => self.slots.iter().position(|s| s.name == *name),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an iterator over the slot infos.
|
||||
pub fn iter(&self) -> impl Iterator<Item = &SlotInfo> {
|
||||
self.slots.iter()
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user