Skip to main content

mln_engine/draw/
target.rs

1//! Textures of a layer's own that its draws draw into ahead of a frame and
2//! that its other draws sample: [`Target`]s.
3//!
4//! A layer makes a target of a size and a clear color
5//! ([`Resources::target`]) and keeps it. In a frame it pushes the
6//! draws into the target into the target's group of its draws
7//! ([`Draws::target`](crate::draw::draws::Draws::target)), and binds the
8//! target's [`texture`](Target::texture) to the draws that sample it. The
9//! engine makes the target's texture, and the depth it draws with, of its
10//! size; clears it to its clear color and draws the group into it before the frame, or the
11//! drape, whose draws sample it; and keeps whether it holds what was drawn
12//! into it ([`Target::holds`]), so that a layer whose target holds the same
13//! from frame to frame draws into it once.
14
15use mln_gfx::gpu::{ColorAttachment, DepthStencilAttachment, Gpu, GpuError, LoadOp, TargetFormats, TextureFormat};
16use mln_gfx::scissor_rect::ScissorRect;
17use mln_gfx::texture2d::{SamplerState, texture_format};
18use mln_gfx::types::{TextureChannelDataType, TextureFilterType, TexturePixelType, TextureWrapType};
19use mln_gfx::{Rgba, Size};
20
21use crate::draw::context::Context;
22use crate::draw::resources::{GpuTexture, Resources};
23use crate::draw::store::{Shared, SharedTexture, TargetKey};
24use crate::render::paint_parameters::{OpenPass, PaintParameters};
25use crate::render::pass::RenderPass;
26
27/// A texture that a layer's draws draw into ahead of the frame, which its
28/// other draws sample: a handle of the target in the context's store, which
29/// stays while a clone of the handle does.
30#[derive(Clone, Debug, PartialEq, Eq)]
31pub struct Target {
32    key: Shared<TargetKey>,
33    texture: SharedTexture,
34}
35
36/// What the context keeps of a [`Target`].
37pub(crate) struct TargetObjects {
38    size: Size,
39    /// The color the target clears to before its draws.
40    clear: Rgba,
41    /// The depth the target's draws draw with, of its size, made with its
42    /// first pass where the backend draws with one
43    /// ([`Context::render_target_depth`]).
44    depth: Option<GpuTexture>,
45    /// Whether the target holds what the draws into it drew, as
46    /// [`Target::holds`] says.
47    holds: bool,
48    /// Whether the frame drew into the target without failing.
49    drawn: bool,
50}
51
52impl Target {
53    /// See [`Resources::target`]: of the type the backend draws into for
54    /// `type_` ([`Context::render_target_type`]).
55    pub(crate) fn new(context: &mut Context, size: Size, type_: TextureChannelDataType, clear: Rgba) -> Target {
56        let format = texture_format(TexturePixelType::RGBA, context.render_target_type(type_));
57        let texture = context.add_texture_with(|texture| {
58            texture.set_size(size);
59            texture.set_format(format);
60            texture.set_render_target();
61            texture.set_sampler(SamplerState {
62                filter: TextureFilterType::Linear,
63                wrap_u: TextureWrapType::Clamp,
64                wrap_v: TextureWrapType::Clamp,
65                ..SamplerState::default()
66            });
67        });
68        let key = context.add_target(TargetObjects { size, clear, depth: None, holds: false, drawn: false });
69        Target { key, texture }
70    }
71
72    pub(crate) fn key(&self) -> &Shared<TargetKey> {
73        &self.key
74    }
75
76    /// The texture the target's draws draw into, which draws sample. It is
77    /// the same through a change of the target's size.
78    #[must_use]
79    pub fn texture(&self) -> &SharedTexture {
80        &self.texture
81    }
82
83    /// Makes the target of `size` from now on: of another size, it then
84    /// holds nothing.
85    pub fn set_size(&self, res: &mut Resources<'_>, size: Size) {
86        let context = &mut *res.context;
87        let Some(objects) = context.target_mut(self).filter(|objects| objects.size != size) else {
88            return;
89        };
90        *objects = TargetObjects { size, clear: objects.clear, depth: None, holds: false, drawn: false };
91        if let Some(mut texture) = context.texture_mut(&self.texture) {
92            texture.set_size(size);
93        }
94    }
95
96    /// Whether the target holds what draws drew into it: from the frame
97    /// whose draws into it were written, until a frame fails to draw them,
98    /// or the target changes size.
99    #[must_use]
100    pub fn holds(&self, res: &Resources<'_>) -> bool {
101        res.context.target(self).is_some_and(|objects| objects.holds)
102    }
103
104    /// Clears the target to its clear color and its depth to 1, and runs
105    /// `draw` with `parameters` into the target in the opaque pass and then
106    /// the translucent one, each as the first layer of a frame of its own,
107    /// outside any other pass, through `gpu`, the context's. `draw` returns
108    /// whether its draws didn't fail. A target that draws without failing
109    /// holds what it drew once the frame is done
110    /// ([`Context::end_targets`]).
111    pub(crate) fn render(
112        &self,
113        gpu: &mut dyn Gpu,
114        parameters: &mut PaintParameters<'_>,
115        mut draw: impl FnMut(&mut dyn Gpu, &mut PaintParameters<'_>) -> bool,
116    ) {
117        let begun = self.pass(gpu, parameters.context).and_then(|pass| parameters.begin_pass(gpu, pass).map(|()| pass));
118        let pass = match begun {
119            Ok(pass) => pass,
120            Err(error) => {
121                parameters.context.fail(format!("Beginning a render target's pass failed: {error}"));
122                return;
123            }
124        };
125        let frame = (parameters.scissor_rect, parameters.pass, parameters.depth_range_size, parameters.current_layer);
126        parameters.scissor_rect = ScissorRect { x: 0, y: 0, width: pass.size.width, height: pass.size.height };
127        let num_sublayers = PaintParameters::NUM_SUBLAYERS as usize;
128        let mut drawn = true;
129        for pass in [RenderPass::Opaque, RenderPass::Translucent] {
130            parameters.pass = pass;
131            parameters.depth_range_size = 1.0 - (3 * num_sublayers) as f32 * PaintParameters::DEPTH_EPSILON;
132            parameters.current_layer = 0;
133            drawn &= draw(gpu, parameters);
134        }
135        let ended = parameters.end_pass(gpu);
136        if let Err(error) = &ended {
137            parameters.context.fail(format!("Ending a render target's pass failed: {error}"));
138        }
139        (parameters.scissor_rect, parameters.pass, parameters.depth_range_size, parameters.current_layer) = frame;
140        if let Some(objects) = parameters.context.target_mut(self) {
141            objects.drawn = ended.is_ok() && drawn;
142        }
143    }
144
145    /// The pass that clears the target to its clear color and its depth to 1,
146    /// making them through `gpu`, the context's.
147    fn pass(&self, gpu: &mut dyn Gpu, context: &mut Context) -> Result<OpenPass, GpuError> {
148        let (color, format, size) = self.color_attachment(gpu, context)?;
149        let depth_format = context.render_target_depth();
150        let objects = context.target(self).ok_or(GpuError::UnknownId("render target"))?;
151        if objects.depth.is_none()
152            && let Some(depth_format) = depth_format
153        {
154            let depth = context.device().attachment(gpu, "render target depth", size, depth_format)?;
155            if let Some(objects) = context.target_mut(self) {
156                objects.depth = Some(depth);
157            }
158        }
159        let depth = context.target(self).and_then(|objects| objects.depth.as_ref()).map(GpuTexture::id);
160        Ok(OpenPass {
161            label: "render target",
162            color: Some(color),
163            depth_stencil: depth.map(|texture| DepthStencilAttachment {
164                texture,
165                depth: LoadOp::Clear(1.0),
166                stencil: LoadOp::Load,
167            }),
168            size,
169            targets: TargetFormats { color: Some(format), depth_stencil: depth.and(depth_format) },
170        })
171    }
172}
173
174impl Target {
175    /// The target's texture as a pass's color attachment that clears it to
176    /// its clear color, with its format and size, making the texture
177    /// through `gpu`, the context's.
178    pub(crate) fn color_attachment(
179        &self,
180        gpu: &mut dyn Gpu,
181        context: &mut Context,
182    ) -> Result<(ColorAttachment, TextureFormat, Size), GpuError> {
183        let texture = context.create_texture(gpu, &self.texture)?;
184        let format = context.texture(&self.texture).ok_or(GpuError::UnknownId("texture"))?.format();
185        let objects = context.target(self).ok_or(GpuError::UnknownId("render target"))?;
186        Ok((ColorAttachment { texture, load: LoadOp::Clear(objects.clear) }, format, objects.size))
187    }
188}
189
190impl TargetObjects {
191    /// Marks the target as holding what the frame's draws into it draw,
192    /// until the frame ends without drawing them.
193    pub(crate) fn declare(&mut self) {
194        self.holds = true;
195        self.drawn = false;
196    }
197
198    /// Ends the frame of the target: it holds what the frame drew into it
199    /// if the frame drew it, and `submitted`, its work reached the GPU.
200    pub(crate) fn end(&mut self, submitted: bool) {
201        self.holds = self.drawn && submitted;
202        self.drawn = false;
203    }
204}