mln_engine/render/terrain/
ground.rs1use std::sync::{Arc, Weak};
7
8use mln_gfx::gpu::{ColorAttachment, DepthStencilAttachment, Gpu, LoadOp, TargetFormats, TextureFormat};
9use mln_gfx::texture2d::SamplerState;
10use mln_gfx::types::{TextureFilterType, TextureWrapType};
11use mln_gfx::{AttributeDataType, Rgba, Size};
12
13use super::{TerrainElevation, TileGround};
14use crate::draw::context::Context;
15use crate::draw::objects::Mesh;
16use crate::draw::resources::{GpuTexture, Resources};
17use crate::draw::store::Texture;
18use crate::draw::vertex::{VertexAttribute, VertexBinding};
19use crate::draw::vertices::VertexBuffer;
20use crate::render::paint_parameters::OpenPass;
21use crate::tile::UnwrappedTileID;
22
23const DEPTH_FORMAT: TextureFormat = TextureFormat::Rgba8Unorm;
26
27const DEPTH_STENCIL: TextureFormat = TextureFormat::Depth24PlusStencil8;
31
32pub struct FrameGround {
35 elevation: Arc<TerrainElevation>,
36 depth: Option<Texture>,
37}
38
39impl FrameGround {
40 pub(crate) fn new(elevation: Arc<TerrainElevation>, depth: Option<Texture>) -> FrameGround {
43 FrameGround { elevation, depth }
44 }
45
46 pub(crate) fn elevation(&self) -> &Arc<TerrainElevation> {
48 &self.elevation
49 }
50
51 #[must_use]
53 pub fn tile(&self, tile: UnwrappedTileID) -> TileGround<'_> {
54 TileGround::new(&self.elevation, tile)
55 }
56
57 #[must_use]
61 pub fn depth(&self) -> Option<&Texture> {
62 self.depth.as_ref()
63 }
64}
65
66#[must_use]
69pub fn point_center(a1: [i16; 2]) -> [i16; 2] {
70 a1.map(|value| value >> 1)
71}
72
73#[derive(Default)]
76pub struct GroundHeights(Option<(Weak<TerrainElevation>, VertexBuffer)>);
77
78impl GroundHeights {
79 #[must_use]
82 pub fn are_of(&self, ground: &FrameGround) -> bool {
83 self.0.as_ref().is_some_and(|(of, _)| Weak::ptr_eq(of, &Arc::downgrade(ground.elevation())))
84 }
85
86 pub fn write(&mut self, res: &mut Resources<'_>, ground: &FrameGround, heights: &[f32]) -> Option<VertexBuffer> {
90 let of = Arc::downgrade(ground.elevation());
91 if let Some((_, vertices)) = &self.0
92 && res.update_vertices(vertices, heights)
93 {
94 self.0 = Some((of, vertices.clone()));
95 return None;
96 }
97 let vertices = res.dynamic_vertices(heights);
98 self.0 = Some((of, vertices.clone()));
99 Some(vertices)
100 }
101}
102
103#[must_use]
106pub fn height_binding(heights: &VertexBuffer, name: &'static str) -> VertexBinding {
107 let attribute = VertexAttribute { name, format: AttributeDataType::Float, offset: 0 };
108 VertexBinding::new(heights, size_of::<f32>() as u32, vec![attribute])
109}
110
111pub struct StandingDraw {
115 pub mesh: Mesh,
116 heights: GroundHeights,
117}
118
119impl StandingDraw {
120 #[must_use]
122 pub fn new(mesh: Mesh) -> Self {
123 StandingDraw { mesh, heights: GroundHeights::default() }
124 }
125
126 pub fn stand(
131 &mut self,
132 res: &mut Resources<'_>,
133 ground: Option<&FrameGround>,
134 tile: UnwrappedTileID,
135 name: &'static str,
136 centers: &[[i16; 2]],
137 ) {
138 let Some(ground) = ground.filter(|ground| !self.heights.are_of(ground)) else {
139 return;
140 };
141 let tile_ground = ground.tile(tile);
142 let heights: Vec<f32> =
143 centers.iter().map(|&[x, y]| tile_ground.height(glam::Vec2::new(f32::from(x), f32::from(y)))).collect();
144 if let Some(vertices) = self.heights.write(res, ground, &heights)
145 && let Some(attrs) = self.mesh.vertex_attributes_mut(res.context)
146 {
147 height_binding(&vertices, name).bind(attrs);
148 }
149 }
150}
151
152#[derive(Default)]
157pub(crate) struct GroundDepth {
158 texture: Option<(Texture, Size)>,
159 depth: Option<GpuTexture>,
161}
162
163impl GroundDepth {
164 pub(crate) fn texture(&mut self, context: &mut Context, size: Size) -> Texture {
167 match &self.texture {
168 Some((texture, made)) if *made == size => texture.clone(),
169 _ => {
170 let texture = context.add_texture_with(|texture| {
171 texture.set_size(size);
172 texture.set_format(DEPTH_FORMAT);
173 texture.set_render_target();
174 texture.set_sampler(SamplerState {
175 filter: TextureFilterType::Nearest,
176 wrap_u: TextureWrapType::Clamp,
177 wrap_v: TextureWrapType::Clamp,
178 ..SamplerState::default()
179 });
180 });
181 self.depth = None;
182 self.texture.insert((texture, size)).0.clone()
183 }
184 }
185 }
186
187 pub(crate) fn pass(&mut self, gpu: &mut dyn Gpu, context: &mut Context) -> Option<OpenPass> {
192 let (texture, size) = self.texture.as_ref()?;
193 let made = context.create_texture(gpu, texture).and_then(|color| {
194 if self.depth.is_none() {
195 self.depth = Some(context.device().attachment(gpu, "ground depth", *size, DEPTH_STENCIL)?);
196 }
197 Ok(color)
198 });
199 let color = match made {
200 Ok(color) => color,
201 Err(error) => {
202 context.fail(format!("Making the ground's depth failed: {error}"));
203 return None;
204 }
205 };
206 Some(OpenPass {
207 label: "ground depth",
208 color: Some(ColorAttachment { texture: color, load: LoadOp::Clear(Rgba::new(0.0, 0.0, 0.0, 0.0)) }),
209 depth_stencil: self.depth.as_ref().map(|depth| DepthStencilAttachment {
210 texture: depth.id(),
211 depth: LoadOp::Clear(1.0),
212 stencil: LoadOp::Clear(0),
213 }),
214 size: *size,
215 targets: TargetFormats { color: Some(DEPTH_FORMAT), depth_stencil: Some(DEPTH_STENCIL) },
216 })
217 }
218
219 pub(crate) fn clear(&mut self) {
222 self.texture = None;
223 self.depth = None;
224 }
225}