1use std::any::Any;
16use std::cell::{Cell, RefCell};
17use std::rc::Rc;
18use std::time::Duration;
19
20use mln_gfx::command_encoder::CommandEncoder as GfxCommandEncoder;
21use mln_gfx::texture2d::{SamplerState, Texture2D as _, Texture2DPtr};
22use mln_gfx::types::{TextureChannelDataType, TextureFilterType, TexturePixelType, TextureWrapType};
23use mln_gfx::{frame, offscreen_texture};
24use mln_util::image::PremultipliedImage;
25use mln_util::size::Size;
26use mln_util::time::Instant;
27
28use crate::command_encoder::CommandEncoder;
29use crate::context::Context;
30use crate::draw_target::{DrawTarget, TargetResource};
31use crate::texture2d::Texture2D;
32
33const BYTES_PER_ROW_ALIGNMENT: u32 = 256;
34
35const WAIT_AGAIN_LIMIT: Duration = Duration::from_secs(1);
37
38fn linear_clamp() -> SamplerState {
39 SamplerState {
40 filter: TextureFilterType::Linear,
41 wrap_u: TextureWrapType::Clamp,
42 wrap_v: TextureWrapType::Clamp,
43 ..SamplerState::default()
44 }
45}
46
47pub struct OffscreenTextureResource {
48 context: Rc<Context>,
49 size: Size,
50 type_: TextureChannelDataType,
51 color_texture: RefCell<Option<Rc<RefCell<Texture2D>>>>,
52 depth_texture: Option<Rc<RefCell<Texture2D>>>,
53 staging_buffer: RefCell<Option<wgpu::Buffer>>,
56 read_back: Cell<bool>,
58 copied_at: Cell<Option<u64>>,
61}
62
63impl OffscreenTextureResource {
64 pub fn new(context: Rc<Context>, size: Size, type_: TextureChannelDataType, depth: bool, stencil: bool) -> Self {
65 debug_assert!(size.width != 0 && size.height != 0);
66 let mut res = OffscreenTextureResource {
67 context,
68 size,
69 type_,
70 color_texture: RefCell::new(None),
71 depth_texture: None,
72 staging_buffer: RefCell::default(),
73 read_back: Cell::default(),
74 copied_at: Cell::default(),
75 };
76 res.context.rendering_stats_mut().num_frame_buffers += 1;
78 *res.color_texture.borrow_mut() = Some(res.create_color_texture());
80
81 if depth || stencil {
84 let depth_texture = res.context.create_webgpu_texture_2d();
85 {
86 let mut t = depth_texture.borrow_mut();
87 t.set_size(size);
88 if depth && stencil {
90 t.set_format(TexturePixelType::Stencil, TextureChannelDataType::UnsignedByte);
91 } else if depth {
92 t.set_format(TexturePixelType::Depth, TextureChannelDataType::Float);
93 } else {
94 t.set_format(TexturePixelType::Stencil, TextureChannelDataType::UnsignedByte);
95 }
96 t.set_usage(wgpu::TextureUsages::RENDER_ATTACHMENT);
97 t.set_sampler_configuration(linear_clamp());
98 }
99 res.depth_texture = Some(depth_texture);
100 }
101 res
102 }
103
104 fn create_color_texture(&self) -> Rc<RefCell<Texture2D>> {
105 let texture = self.context.create_webgpu_texture_2d();
106 {
107 let mut t = texture.borrow_mut();
108 t.set_size(self.size);
109 t.set_format(TexturePixelType::RGBA, self.type_);
110 t.set_usage(
111 wgpu::TextureUsages::TEXTURE_BINDING
112 | wgpu::TextureUsages::COPY_DST
113 | wgpu::TextureUsages::COPY_SRC
114 | wgpu::TextureUsages::RENDER_ATTACHMENT,
115 );
116 t.set_sampler_configuration(linear_clamp());
117 }
118 texture
119 }
120
121 fn color(&self) -> Option<Rc<RefCell<Texture2D>>> {
122 self.color_texture.borrow().clone()
123 }
124
125 fn row_strides(&self) -> (u32, u32) {
126 let row_stride = self.size.width * 4; (row_stride, row_stride.next_multiple_of(BYTES_PER_ROW_ALIGNMENT))
128 }
129
130 fn encode_copy(&self, device: &wgpu::Device, encoder: &mut wgpu::CommandEncoder) -> bool {
133 let color = self.color();
134 let Some(texture) = color.as_ref().and_then(|c| c.borrow().get_texture().cloned()) else {
135 return false;
136 };
137 let size = self.size;
138 let (_, aligned_row_stride) = self.row_strides();
139 let mut staging = self.staging_buffer.borrow_mut();
140 let staging = staging.get_or_insert_with(|| {
141 device.create_buffer(&wgpu::BufferDescriptor {
142 label: Some("Readback Buffer"),
143 size: u64::from(aligned_row_stride) * u64::from(size.height),
144 usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
145 mapped_at_creation: false,
146 })
147 });
148 encoder.copy_texture_to_buffer(
149 wgpu::TexelCopyTextureInfo {
150 texture: &texture,
151 mip_level: 0,
152 origin: wgpu::Origin3d::ZERO,
153 aspect: wgpu::TextureAspect::All,
154 },
155 wgpu::TexelCopyBufferInfo {
156 buffer: staging,
157 layout: wgpu::TexelCopyBufferLayout {
158 offset: 0,
159 bytes_per_row: Some(aligned_row_stride),
160 rows_per_image: Some(size.height),
161 },
162 },
163 wgpu::Extent3d { width: size.width, height: size.height, depth_or_array_layers: 1 },
164 );
165 true
166 }
167
168 pub(crate) fn encode_requested_copy(&self, encoder: &mut wgpu::CommandEncoder) {
172 let Some(device) = self.context.get_backend().get_device() else {
173 return;
174 };
175 if self.read_back.replace(false) && self.encode_copy(&device, encoder) {
176 self.copied_at.set(Some(self.context.submissions()));
177 }
178 }
179
180 pub fn read_still_image(&self) -> PremultipliedImage {
183 let size = self.size;
184 let (row_stride, aligned_row_stride) = self.row_strides();
185 let mut data = vec![0u8; row_stride as usize * size.height as usize];
186 self.read_back.set(true);
187
188 let backend = self.context.get_backend();
189 let (Some(device), Some(queue)) = (backend.get_device(), backend.get_queue()) else {
190 eprintln!("WebGPU: No device or queue available for readback");
191 return PremultipliedImage::from_vec(size, data);
192 };
193
194 if self.copied_at.take() != Some(self.context.submissions()) {
196 let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None });
197 if !self.encode_copy(&device, &mut encoder) {
198 eprintln!("WebGPU: Color texture is null");
199 return PremultipliedImage::from_vec(size, data);
200 }
201 queue.submit([encoder.finish()]);
202 }
203 let staging = self.staging_buffer.borrow();
204 let Some(staging_buffer) = staging.as_ref() else {
205 return PremultipliedImage::from_vec(size, data);
206 };
207
208 let (tx, rx) = std::sync::mpsc::channel();
210 staging_buffer.map_async(wgpu::MapMode::Read, .., move |result| {
211 let _ = tx.send(result);
212 });
213 let wait = || device.poll(wgpu::PollType::Wait { submission_index: None, timeout: None });
218 let start = Instant::now();
219 let mut waited = wait();
220 while matches!(waited, Err(wgpu::PollError::Timeout)) && start.elapsed() < WAIT_AGAIN_LIMIT {
221 waited = wait();
222 }
223 if let Err(e) = waited {
224 eprintln!("WebGPU: Buffer mapping wait failed: {e}");
225 }
226 match rx.try_recv() {
227 Ok(Ok(())) => match staging_buffer.get_mapped_range(..) {
228 Ok(mapped) => {
229 if aligned_row_stride == row_stride {
230 let n = data.len();
231 data.copy_from_slice(&mapped[..n]);
232 } else {
233 let rs = row_stride as usize;
234 let ars = aligned_row_stride as usize;
235 for row in 0..size.height as usize {
236 data[row * rs..(row + 1) * rs].copy_from_slice(&mapped[row * ars..row * ars + rs]);
237 }
238 }
239 }
240 Err(e) => eprintln!("WebGPU: Failed to get mapped range: {e}"),
241 },
242 Ok(Err(e)) => eprintln!("WebGPU: Buffer mapping failed with status: {e}"),
243 Err(_) => eprintln!("WebGPU: Buffer mapping timeout after polling"),
244 }
245 staging_buffer.unmap();
246 PremultipliedImage::from_vec(size, data)
247 }
248
249 pub fn get_texture(&self) -> Texture2DPtr {
250 self.color().expect("offscreen texture without color texture")
251 }
252}
253
254impl Drop for OffscreenTextureResource {
255 fn drop(&mut self) {
256 self.context.rendering_stats_mut().num_frame_buffers -= 1;
257 }
258}
259
260impl TargetResource for OffscreenTextureResource {
261 fn bind(&self) {
262 if let Some(color) = self.color() {
264 color.borrow_mut().create();
265 }
266 if let Some(depth) = &self.depth_texture {
267 depth.borrow_mut().create();
268 }
269 }
270
271 fn finish_frame(&self, encoder: &mut wgpu::CommandEncoder) {
272 self.encode_requested_copy(encoder);
273 }
274
275 fn get_color_texture_view(&self) -> Option<wgpu::TextureView> {
276 let color = self.color()?;
277 let mut texture = color.borrow_mut();
278 texture.create();
279 texture.get_texture_view().cloned()
280 }
281
282 fn get_color_texture_format(&self) -> Option<wgpu::TextureFormat> {
283 self.color()?.borrow().get_native_format()
284 }
285
286 fn get_depth_stencil_texture_view(&self) -> Option<wgpu::TextureView> {
287 let depth = self.depth_texture.as_ref()?;
288 let mut texture = depth.borrow_mut();
289 texture.create();
290 texture.get_texture_view().cloned()
291 }
292
293 fn get_depth_stencil_texture_format(&self) -> Option<wgpu::TextureFormat> {
294 self.depth_texture.as_ref()?.borrow().get_native_format()
295 }
296
297 fn as_any(&self) -> &dyn Any {
298 self
299 }
300}
301
302pub struct OffscreenTexture {
304 target: DrawTarget,
305 resource: Rc<OffscreenTextureResource>,
306}
307
308impl OffscreenTexture {
309 pub fn new(context: Rc<Context>, size: Size, type_: TextureChannelDataType, depth: bool, stencil: bool) -> Self {
310 let resource = Rc::new(OffscreenTextureResource::new(context, size, type_, depth, stencil));
311 OffscreenTexture { target: DrawTarget::new(size, resource.clone()), resource }
312 }
313
314 fn resource(&self) -> &OffscreenTextureResource {
315 &self.resource
316 }
317}
318
319impl offscreen_texture::OffscreenTexture for OffscreenTexture {
320 fn draw_target(&self) -> &dyn frame::DrawTarget {
321 &self.target
322 }
323
324 fn is_renderable(&self) -> bool {
326 self.resource().color().is_some()
327 }
328
329 fn read_still_image(&self) -> PremultipliedImage {
330 self.resource().read_still_image()
331 }
332
333 fn get_texture(&self) -> Texture2DPtr {
334 self.resource().get_texture()
335 }
336
337 fn submit(&self, encoder: &dyn GfxCommandEncoder) {
338 if let Some(encoder) = encoder.as_any().downcast_ref::<CommandEncoder>() {
339 encoder.submit_frame(Some(self.target.resource()));
340 }
341 }
342
343 fn as_any(&self) -> &dyn Any {
344 self
345 }
346}