Skip to main content

eframe/web/
web_painter_wgpu.rs

1use std::sync::Arc;
2
3use egui::ScreenshotCallback;
4use egui_wgpu::{RenderState, SurfaceErrorAction, capture::CaptureState};
5use wasm_bindgen::JsValue;
6use web_sys::HtmlCanvasElement;
7
8use super::web_painter::WebPainter;
9
10pub(crate) struct WebPainterWgpu {
11    canvas: HtmlCanvasElement,
12    instance: wgpu::Instance,
13    surface: wgpu::Surface<'static>,
14    surface_configuration: wgpu::SurfaceConfiguration,
15    render_state: Option<RenderState>,
16    on_surface_status: Arc<dyn Fn(&wgpu::CurrentSurfaceTexture) -> SurfaceErrorAction>,
17    depth_stencil_format: Option<wgpu::TextureFormat>,
18    depth_texture_view: Option<wgpu::TextureView>,
19    screen_capture_state: Option<CaptureState>,
20    ctx: egui::Context,
21    needs_reconfigure: bool,
22    needs_recreate: bool,
23}
24
25/// Owned web display handle that is `Send + Sync`.
26///
27/// `DisplayHandle` from `raw-window-handle` is `!Send`/`!Sync` because the enum
28/// contains platform variants with raw pointers. On web the handle is always empty,
29/// so this wrapper is safe.
30#[cfg(target_arch = "wasm32")]
31#[derive(Clone, Debug)]
32struct WebDisplay;
33
34#[cfg(target_arch = "wasm32")]
35impl egui_wgpu::wgpu::rwh::HasDisplayHandle for WebDisplay {
36    fn display_handle(
37        &self,
38    ) -> Result<egui_wgpu::wgpu::rwh::DisplayHandle<'_>, egui_wgpu::wgpu::rwh::HandleError> {
39        Ok(egui_wgpu::wgpu::rwh::DisplayHandle::web())
40    }
41}
42
43impl WebPainterWgpu {
44    pub fn render_state(&self) -> Option<RenderState> {
45        self.render_state.clone()
46    }
47
48    pub fn generate_depth_texture_view(
49        &self,
50        render_state: &RenderState,
51        width_in_pixels: u32,
52        height_in_pixels: u32,
53    ) -> Option<wgpu::TextureView> {
54        let device = &render_state.device;
55        self.depth_stencil_format.map(|depth_stencil_format| {
56            device
57                .create_texture(&wgpu::TextureDescriptor {
58                    label: Some("egui_depth_texture"),
59                    size: wgpu::Extent3d {
60                        width: width_in_pixels,
61                        height: height_in_pixels,
62                        depth_or_array_layers: 1,
63                    },
64                    mip_level_count: 1,
65                    sample_count: 1,
66                    dimension: wgpu::TextureDimension::D2,
67                    format: depth_stencil_format,
68                    usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
69                    view_formats: &[depth_stencil_format],
70                })
71                .create_view(&wgpu::TextureViewDescriptor::default())
72        })
73    }
74
75    pub async fn new(
76        ctx: egui::Context,
77        canvas: web_sys::HtmlCanvasElement,
78        options: &crate::WebOptions,
79    ) -> Result<Self, String> {
80        log::debug!("Creating wgpu painter");
81
82        // Inject the display handle into the wgpu setup so that wgpu can create surfaces on WebGL.
83        let mut wgpu_options = options.wgpu_options.clone();
84        if let egui_wgpu::WgpuSetup::CreateNew(ref mut create_new) = wgpu_options.wgpu_setup
85            && create_new.display_handle.is_none()
86        {
87            // Force WebGL, useful for quick & dirty testing:
88            // create_new.instance_descriptor.backends = wgpu::Backends::GL;
89            create_new.display_handle = Some(Box::new(WebDisplay));
90        }
91
92        let instance = wgpu_options.wgpu_setup.new_instance().await;
93        let surface = instance
94            .create_surface(wgpu::SurfaceTarget::Canvas(canvas.clone()))
95            .map_err(|err| format!("failed to create wgpu surface: {err}"))?;
96
97        let depth_stencil_format = egui_wgpu::depth_format_from_bits(options.depth_buffer, 0);
98
99        let render_state = RenderState::create(
100            &wgpu_options,
101            &instance,
102            Some(&surface),
103            egui_wgpu::RendererOptions {
104                dithering: options.dithering,
105                depth_stencil_format,
106                ..Default::default()
107            },
108        )
109        .await
110        .map_err(|err| err.to_string())?;
111
112        let default_configuration = surface
113            .get_default_config(&render_state.adapter, 0, 0) // Width/height is set later.
114            .ok_or("The surface isn't supported by this adapter")?;
115
116        let surface_configuration = wgpu::SurfaceConfiguration {
117            format: render_state.target_format,
118            present_mode: wgpu_options.surface.present_mode,
119            view_formats: vec![render_state.target_format],
120            ..default_configuration
121        };
122
123        log::debug!("wgpu painter initialized.");
124
125        Ok(Self {
126            canvas,
127            instance,
128            render_state: Some(render_state),
129            surface,
130            surface_configuration,
131            depth_stencil_format,
132            depth_texture_view: None,
133            on_surface_status: Arc::clone(&wgpu_options.on_surface_status) as _,
134            screen_capture_state: None,
135            ctx,
136            needs_reconfigure: false,
137            needs_recreate: false,
138        })
139    }
140}
141
142impl WebPainter for WebPainterWgpu {
143    fn canvas(&self) -> &HtmlCanvasElement {
144        &self.canvas
145    }
146
147    fn max_texture_side(&self) -> usize {
148        self.render_state.as_ref().map_or(0, |state| {
149            state.device.limits().max_texture_dimension_2d as _
150        })
151    }
152
153    fn paint_and_update_textures(
154        &mut self,
155        clear_color: [f32; 4],
156        clipped_primitives: &[egui::ClippedPrimitive],
157        pixels_per_point: f32,
158        textures_delta: &mut egui::TexturesDelta,
159        capture_data: Vec<ScreenshotCallback>,
160    ) -> Result<(), JsValue> {
161        let capture = !capture_data.is_empty();
162
163        let size_in_pixels = [self.canvas.width(), self.canvas.height()];
164
165        let Some(render_state) = &self.render_state else {
166            return Err(JsValue::from_str(
167                "Can't paint, wgpu renderer was already disposed",
168            ));
169        };
170
171        // If the previous frame produced `CurrentSurfaceTexture::Lost`, drop and recreate the
172        // surface from the canvas before re-borrowing `self.render_state` for the rest of paint.
173        if self.needs_recreate {
174            self.needs_recreate = false;
175            match self
176                .instance
177                .create_surface(wgpu::SurfaceTarget::Canvas(self.canvas.clone()))
178            {
179                Ok(new_surface) => {
180                    new_surface.configure(&render_state.device, &self.surface_configuration);
181                    self.surface = new_surface;
182                }
183                Err(err) => {
184                    log::error!("Failed to recreate wgpu surface for canvas: {err}");
185                }
186            }
187        }
188
189        let mut encoder =
190            render_state
191                .device
192                .create_command_encoder(&wgpu::CommandEncoderDescriptor {
193                    label: Some("egui_webpainter_paint_and_update_textures"),
194                });
195
196        // Upload all resources for the GPU.
197        let screen_descriptor = egui_wgpu::ScreenDescriptor {
198            size_in_pixels,
199            pixels_per_point,
200        };
201
202        let user_cmd_bufs = {
203            let mut renderer = render_state.renderer.write();
204            #[expect(clippy::iter_over_hash_type)] // Order doesn't matter here
205            for (id, image_deltas) in textures_delta.set.drain() {
206                for image_delta in image_deltas {
207                    renderer.update_texture(
208                        &render_state.device,
209                        &render_state.queue,
210                        id,
211                        &image_delta,
212                    );
213                }
214            }
215
216            renderer.update_buffers(
217                &render_state.device,
218                &render_state.queue,
219                &mut encoder,
220                clipped_primitives,
221                &screen_descriptor,
222            )
223        };
224
225        // Resize surface if needed
226        let is_zero_sized_surface = size_in_pixels[0] == 0 || size_in_pixels[1] == 0;
227        let frame_and_capture_buffer = if is_zero_sized_surface {
228            None
229        } else {
230            if size_in_pixels[0] != self.surface_configuration.width
231                || size_in_pixels[1] != self.surface_configuration.height
232            {
233                self.surface_configuration.width = size_in_pixels[0];
234                self.surface_configuration.height = size_in_pixels[1];
235                self.surface
236                    .configure(&render_state.device, &self.surface_configuration);
237                self.depth_texture_view = self.generate_depth_texture_view(
238                    render_state,
239                    size_in_pixels[0],
240                    size_in_pixels[1],
241                );
242            }
243
244            if self.needs_reconfigure {
245                self.surface
246                    .configure(&render_state.device, &self.surface_configuration);
247                self.needs_reconfigure = false;
248            }
249
250            let output_frame = match self.surface.get_current_texture() {
251                wgpu::CurrentSurfaceTexture::Success(frame) => frame,
252                wgpu::CurrentSurfaceTexture::Suboptimal(frame) => {
253                    self.needs_reconfigure = true;
254                    frame
255                }
256                other => {
257                    match (*self.on_surface_status)(&other) {
258                        SurfaceErrorAction::Reconfigure => {
259                            self.surface
260                                .configure(&render_state.device, &self.surface_configuration);
261                        }
262                        SurfaceErrorAction::RecreateSurface => {
263                            // Full recovery needs `&mut self`, which conflicts with the live
264                            // `render_state` / `self.surface` borrows here. Defer to the top
265                            // of the next paint via the `needs_recreate` flag, and request a
266                            // repaint so the next frame actually invokes `paint` to consume it.
267                            self.needs_recreate = true;
268                            self.ctx.request_repaint();
269                        }
270                        SurfaceErrorAction::SkipFrame => {}
271                    }
272                    return Ok(());
273                }
274            };
275
276            {
277                let renderer = render_state.renderer.read();
278
279                let target_texture = if capture {
280                    let size = output_frame.texture.size();
281                    let format = output_frame.texture.format();
282                    let capture_state = self.screen_capture_state.get_or_insert_with(|| {
283                        CaptureState::new(&render_state.device, size, format)
284                    });
285                    capture_state.update(&render_state.device, size);
286
287                    &capture_state.texture
288                } else {
289                    &output_frame.texture
290                };
291                let target_view =
292                    target_texture.create_view(&wgpu::TextureViewDescriptor::default());
293
294                let render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
295                    color_attachments: &[Some(wgpu::RenderPassColorAttachment {
296                        view: &target_view,
297                        resolve_target: None,
298                        ops: wgpu::Operations {
299                            load: wgpu::LoadOp::Clear(wgpu::Color {
300                                r: clear_color[0] as f64,
301                                g: clear_color[1] as f64,
302                                b: clear_color[2] as f64,
303                                a: clear_color[3] as f64,
304                            }),
305                            store: wgpu::StoreOp::Store,
306                        },
307                        depth_slice: None,
308                    })],
309                    depth_stencil_attachment: self.depth_texture_view.as_ref().map(|view| {
310                        wgpu::RenderPassDepthStencilAttachment {
311                            view,
312                            depth_ops: self
313                                .depth_stencil_format
314                                .is_some_and(|depth_stencil_format| {
315                                    depth_stencil_format.has_depth_aspect()
316                                })
317                                .then_some(wgpu::Operations {
318                                    load: wgpu::LoadOp::Clear(1.0),
319                                    // It is very unlikely that the depth buffer is needed after egui finished rendering
320                                    // so no need to store it. (this can improve performance on tiling GPUs like mobile chips or Apple Silicon)
321                                    store: wgpu::StoreOp::Discard,
322                                }),
323                            stencil_ops: self
324                                .depth_stencil_format
325                                .is_some_and(|depth_stencil_format| {
326                                    depth_stencil_format.has_stencil_aspect()
327                                })
328                                .then_some(wgpu::Operations {
329                                    load: wgpu::LoadOp::Clear(0),
330                                    store: wgpu::StoreOp::Discard,
331                                }),
332                        }
333                    }),
334                    label: Some("egui_render"),
335                    occlusion_query_set: None,
336                    timestamp_writes: None,
337                    multiview_mask: None,
338                });
339
340                // Forgetting the pass' lifetime means that we are no longer compile-time protected from
341                // runtime errors caused by accessing the parent encoder before the render pass is dropped.
342                // Since we don't pass it on to the renderer, we should be perfectly safe against this mistake here!
343                renderer.render(
344                    &mut render_pass.forget_lifetime(),
345                    clipped_primitives,
346                    &screen_descriptor,
347                );
348            }
349
350            let capture_buffer =
351                if capture && let Some(capture_state) = &mut self.screen_capture_state {
352                    Some(capture_state.copy_textures(
353                        &render_state.device,
354                        Some(&output_frame),
355                        &mut encoder,
356                    ))
357                } else {
358                    None
359                };
360
361            Some((output_frame, capture_buffer))
362        };
363
364        // Submit the commands: both the main buffer and user-defined ones.
365        render_state
366            .queue
367            .submit(core::iter::chain(user_cmd_bufs, [encoder.finish()]));
368
369        if let Some((frame, capture_buffer)) = frame_and_capture_buffer {
370            if let Some(capture_buffer) = capture_buffer
371                && let Some(capture_state) = &self.screen_capture_state
372            {
373                capture_state.read_screen_rgba(capture_buffer, capture_data);
374            }
375
376            render_state.queue.present(frame);
377        }
378
379        // Free textures marked for destruction **after** queue submit since they might still be used in the current frame.
380        // Calling `wgpu::Texture::destroy` on a texture that is still in use would invalidate the command buffer(s) it is used in.
381        // However, once we called `wgpu::Queue::submit`, it is up for wgpu to determine how long the underlying gpu resource has to live.
382        {
383            let mut renderer = render_state.renderer.write();
384            #[expect(clippy::iter_over_hash_type)] // Order doesn't matter here
385            for id in textures_delta.free.drain() {
386                renderer.free_texture(&id);
387            }
388        }
389
390        Ok(())
391    }
392
393    fn destroy(&mut self) {
394        self.render_state = None;
395    }
396}