bevy/crates/bevy_render/src/render_graph/node.rs
IceSentry 613b5a69ae
Add ViewNode to simplify render node management (#8118)
# Objective

- When writing render nodes that need a view, you always need to define
a `Query` on the associated view and make sure to update it manually and
query it manually. This is verbose and error prone.

## Solution

- Introduce a new `ViewNode` trait and `ViewNodeRunner` `Node` that will
take care of managing the associated view query automatically.
- The trait is currently a passthrough of the `Node` trait. So it still
has the update/run with all the same data passed in.
- The `ViewNodeRunner` is the actual node that is added to the render
graph and it contains the custom node. This is necessary because it's
the one that takes care of updating the node.

---

## Changelog

- Add `ViewNode`
- Add `ViewNodeRunner`

## Notes

Currently, this only handles the view query, but it could probably have
a ReadOnlySystemState that would also simplify querying all the readonly
resources that most render nodes currently query manually. The issue is
that I don't know how to do that without a `&mut self`.

At first, I tried making this a default feature of all `Node`, but I
kept hitting errors related to traits and generics and stuff I'm not
super comfortable with. This implementations is much simpler and keeps
the default Node behaviour so isn't a breaking change

## Reviewer Notes

The PR looks quite big, but the core of the PR is the changes in
`render_graph/node.rs`. Every other change is simply updating existing
nodes to use this new feature.

## Open questions

~~- Naming is not final, I'm opened to anything. I named it
ViewQueryNode because it's a node with a managed Query on a View.~~
~~- What to do when the query fails? All nodes using this pattern
currently just `return Ok(())` when it fails, so I chose that, but
should it be more flexible?~~
~~- Is the ViewQueryFilter actually necessary? All view queries run on
the entity that is already guaranteed to be a view. Filtering won't do
much, but maybe someone wants to control an effect with the presence of
a component instead of a flag.~~
~~- What to do with Nodes that are empty struct? Implementing
`FromWorld` is pretty verbose but not implementing it means there's 2
ways to create a `ViewNodeRunner` which seems less ideal. This is an
issue now because most node simply existed to hold the query, but now
that they don't hold the query state we are left with a bunch of empty
structs.~~
- Should we have a `RenderGraphApp::add_render_graph_view_node()`, this
isn't necessary, but it could make the code a bit shorter.

---------

Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2023-05-08 19:42:23 +00:00

410 lines
12 KiB
Rust

use crate::{
define_atomic_id,
render_graph::{
Edge, InputSlotError, OutputSlotError, RenderGraphContext, RenderGraphError,
RunSubGraphError, SlotInfo, SlotInfos,
},
renderer::RenderContext,
};
use bevy_ecs::{
query::{QueryItem, QueryState, ReadOnlyWorldQuery},
world::{FromWorld, World},
};
use downcast_rs::{impl_downcast, Downcast};
use std::{borrow::Cow, fmt::Debug};
use thiserror::Error;
define_atomic_id!(NodeId);
/// 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(
&self,
graph: &mut RenderGraphContext,
render_context: &mut RenderContext,
world: &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),
}
/// A collection of input and output [`Edges`](Edge) for a [`Node`].
#[derive(Debug)]
pub struct Edges {
id: NodeId,
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 id.
#[inline]
pub fn id(&self) -> NodeId {
self.id
}
/// 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.id,
})
}
/// 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.id,
})
}
}
/// 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 id: NodeId,
pub name: Option<Cow<'static, str>>,
/// 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 std::fmt::Formatter<'_>) -> std::fmt::Result {
writeln!(f, "{:?} ({:?})", self.id, self.name)
}
}
impl NodeState {
/// Creates an [`NodeState`] without edges, but the `input_slots` and `output_slots`
/// are provided by the `node`.
pub fn new<T>(id: NodeId, node: T) -> Self
where
T: Node,
{
NodeState {
id,
name: None,
input_slots: node.input().into(),
output_slots: node.output().into(),
node: Box::new(node),
type_name: std::any::type_name::<T>(),
edges: Edges {
id,
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 [`NodeLabel`] is used to reference a [`NodeState`] by either its name or [`NodeId`]
/// inside the [`RenderGraph`](super::RenderGraph).
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum NodeLabel {
Id(NodeId),
Name(Cow<'static, str>),
}
impl From<&NodeLabel> for NodeLabel {
fn from(value: &NodeLabel) -> Self {
value.clone()
}
}
impl From<String> for NodeLabel {
fn from(value: String) -> Self {
NodeLabel::Name(value.into())
}
}
impl From<&'static str> for NodeLabel {
fn from(value: &'static str) -> Self {
NodeLabel::Name(value.into())
}
}
impl From<NodeId> for NodeLabel {
fn from(value: NodeId) -> Self {
NodeLabel::Id(value)
}
}
/// 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 graph name once.
/// This makes it easier to insert sub-graph runs into a graph.
pub struct RunGraphOnViewNode {
graph_name: Cow<'static, str>,
}
impl RunGraphOnViewNode {
pub fn new<T: Into<Cow<'static, str>>>(graph_name: T) -> Self {
Self {
graph_name: graph_name.into(),
}
}
}
impl Node for RunGraphOnViewNode {
fn run(
&self,
graph: &mut RenderGraphContext,
_render_context: &mut RenderContext,
_world: &World,
) -> Result<(), NodeRunError> {
graph.run_sub_graph(self.graph_name.clone(), vec![], Some(graph.view_entity()))?;
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: ReadOnlyWorldQuery;
/// 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(
&self,
graph: &mut RenderGraphContext,
render_context: &mut RenderContext,
view_query: QueryItem<Self::ViewQuery>,
world: &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(
&self,
graph: &mut RenderGraphContext,
render_context: &mut RenderContext,
world: &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(())
}
}