Skip to main content

paint_api/
rendering_context.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5#![deny(unsafe_code)]
6
7use std::cell::{Cell, RefCell, RefMut};
8use std::num::NonZeroU32;
9use std::rc::Rc;
10use std::sync::Arc;
11
12use dpi::PhysicalSize;
13use embedder_traits::RefreshDriver;
14use euclid::default::{Rect, Size2D as UntypedSize2D};
15use euclid::{Point2D, Size2D};
16use gleam::gl::{self, Gl};
17use glow::{HasContext, NativeFramebuffer};
18use image::RgbaImage;
19use log::{debug, trace, warn};
20use raw_window_handle::{DisplayHandle, WindowHandle};
21pub use surfman::Error;
22use surfman::chains::{PreserveBuffer, SwapChain};
23use surfman::{
24    Adapter, Connection, Context, ContextAttributeFlags, ContextAttributes, Device, GLApi,
25    GLVersion, NativeWidget, Surface, SurfaceAccess, SurfaceInfo, SurfaceTexture, SurfaceType,
26};
27use webrender_api::units::{DeviceIntRect, DevicePixel};
28
29/// The `RenderingContext` trait defines a set of methods for managing
30/// an OpenGL or GLES rendering context.
31/// Implementors of this trait are responsible for handling the creation,
32/// management, and destruction of the rendering context and its associated
33/// resources.
34pub trait RenderingContext {
35    /// Prepare this [`RenderingContext`] to be rendered upon by Servo. For instance,
36    /// by binding a framebuffer to the current OpenGL context.
37    fn prepare_for_rendering(&self) {}
38    /// Read the contents of this [`Renderingcontext`] into an in-memory image. If the
39    /// image cannot be read (for instance, if no rendering has taken place yet), then
40    /// `None` is returned.
41    ///
42    /// In a double-buffered [`RenderingContext`] this is expected to read from the back
43    /// buffer. That means that once Servo renders to the context, this should return those
44    /// results, even before [`RenderingContext::present`] is called.
45    fn read_to_image(&self, source_rectangle: DeviceIntRect) -> Option<RgbaImage>;
46    /// Get the current size of this [`RenderingContext`].
47    fn size(&self) -> PhysicalSize<u32>;
48    /// Get the current size of this [`RenderingContext`] as [`Size2D`].
49    fn size2d(&self) -> Size2D<u32, DevicePixel> {
50        let size = self.size();
51        Size2D::new(size.width, size.height)
52    }
53    /// Resizes the rendering surface to the given size.
54    fn resize(&self, size: PhysicalSize<u32>);
55    /// Presents the rendered frame to the screen. In a double-buffered context, this would
56    /// swap buffers.
57    fn present(&self);
58    /// Makes the context the current OpenGL context for this thread.
59    /// After calling this function, it is valid to use OpenGL rendering
60    /// commands.
61    fn make_current(&self) -> Result<(), Error>;
62    /// Returns the `gleam` version of the OpenGL or GLES API.
63    fn gleam_gl_api(&self) -> Rc<dyn gleam::gl::Gl>;
64    /// Returns the OpenGL or GLES API.
65    fn glow_gl_api(&self) -> Arc<glow::Context>;
66    /// Creates a texture from a given surface and returns the surface texture,
67    /// the OpenGL texture object, and the size of the surface. Default to `None`.
68    fn create_texture(
69        &self,
70        _surface: Surface,
71    ) -> Option<(SurfaceTexture, u32, UntypedSize2D<i32>)> {
72        None
73    }
74    /// Destroys the texture and returns the surface. Default to `None`.
75    fn destroy_texture(&self, _surface_texture: SurfaceTexture) -> Option<Surface> {
76        None
77    }
78    /// The connection to the display server for WebGL. Default to `None`.
79    fn connection(&self) -> Option<Connection> {
80        None
81    }
82    /// Return the [`RefreshDriver`] for this [`RenderingContext`]. If `None` is returned,
83    /// then the default timer-based [`RefreshDriver`] will be used.
84    fn refresh_driver(&self) -> Option<Rc<dyn RefreshDriver>> {
85        None
86    }
87    /// The associated adapter to use for WebGL. Default to `None`.
88    fn adapter(&self) -> Option<Adapter> {
89        None
90    }
91}
92
93/// A rendering context that uses the Surfman library to create and manage
94/// the OpenGL context and surface. This struct provides the default implementation
95/// of the `RenderingContext` trait, handling the creation, management, and destruction
96/// of the rendering context and its associated resources.
97///
98/// The `SurfmanRenderingContext` struct encapsulates the necessary data and methods
99/// to interact with the Surfman library, including creating surfaces, binding surfaces,
100/// resizing surfaces, presenting rendered frames, and managing the OpenGL context state.
101struct SurfmanRenderingContext {
102    gleam_gl: Rc<dyn Gl>,
103    glow_gl: Arc<glow::Context>,
104    device: RefCell<Device>,
105    context: RefCell<Context>,
106    refresh_driver: Option<Rc<dyn RefreshDriver>>,
107}
108
109impl Drop for SurfmanRenderingContext {
110    fn drop(&mut self) {
111        let device = &mut self.device.borrow_mut();
112        let context = &mut self.context.borrow_mut();
113        let _ = device.destroy_context(context);
114    }
115}
116
117impl SurfmanRenderingContext {
118    fn new(
119        connection: &Connection,
120        adapter: &Adapter,
121        refresh_driver: Option<Rc<dyn RefreshDriver>>,
122    ) -> Result<Self, Error> {
123        let device = connection.create_device(adapter)?;
124
125        let flags = ContextAttributeFlags::ALPHA |
126            ContextAttributeFlags::DEPTH |
127            ContextAttributeFlags::STENCIL;
128        let gl_api = connection.gl_api();
129        let version = match &gl_api {
130            GLApi::GLES => surfman::GLVersion { major: 3, minor: 0 },
131            GLApi::GL => surfman::GLVersion { major: 3, minor: 2 },
132        };
133        let context_descriptor =
134            device.create_context_descriptor(&ContextAttributes { flags, version })?;
135
136        let mut context = device
137            .create_context(&context_descriptor, None)
138            .inspect_err(|_| {
139                print_diagnostics_information_on_context_creation_failure(&device, gl_api, version)
140            })?;
141
142        // `glow::Context::from_loader_function` immediately queries `GL_VERSION`, so the
143        // context must be current.
144        if let Err(error) = device.make_context_current(&context) {
145            let _ = device.destroy_context(&mut context);
146            return Err(error);
147        }
148
149        #[expect(unsafe_code)]
150        let gleam_gl = {
151            match gl_api {
152                GLApi::GL => unsafe {
153                    gl::GlFns::load_with(|func_name| device.get_proc_address(&context, func_name))
154                },
155                GLApi::GLES => unsafe {
156                    gl::GlesFns::load_with(|func_name| device.get_proc_address(&context, func_name))
157                },
158            }
159        };
160
161        #[expect(unsafe_code)]
162        let glow_gl = unsafe {
163            glow::Context::from_loader_function(|function_name| {
164                device.get_proc_address(&context, function_name)
165            })
166        };
167
168        Ok(SurfmanRenderingContext {
169            gleam_gl,
170            glow_gl: Arc::new(glow_gl),
171            device: RefCell::new(device),
172            context: RefCell::new(context),
173            refresh_driver,
174        })
175    }
176
177    fn create_surface(&self, surface_type: SurfaceType<NativeWidget>) -> Result<Surface, Error> {
178        let device = &mut self.device.borrow_mut();
179        let context = &self.context.borrow();
180        device.create_surface(context, SurfaceAccess::GPUOnly, surface_type)
181    }
182
183    fn bind_surface(&self, surface: Surface) -> Result<(), Error> {
184        let device = &self.device.borrow();
185        let context = &mut self.context.borrow_mut();
186        device
187            .bind_surface_to_context(context, surface)
188            .map_err(|(err, mut surface)| {
189                let _ = device.destroy_surface(context, &mut surface);
190                err
191            })?;
192        Ok(())
193    }
194
195    fn create_attached_swap_chain(&self) -> Result<SwapChain<Device>, Error> {
196        let device = &mut self.device.borrow_mut();
197        let context = &mut self.context.borrow_mut();
198        SwapChain::create_attached(device, context, SurfaceAccess::GPUOnly)
199    }
200
201    fn resize_bound_surface(&self, size: PhysicalSize<u32>) -> Result<(), Error> {
202        if size.width == 0 || size.height == 0 {
203            log::error!("Unable to resize to size under 1x1 ({size:?} provided)");
204            return Err(Error::Failed);
205        }
206
207        let size = Size2D::new(size.width as i32, size.height as i32);
208        self.device
209            .borrow()
210            .resize_bound_surface(&mut self.context.borrow_mut(), size)
211    }
212
213    fn present_bound_surface(&self) -> Result<(), Error> {
214        self.device
215            .borrow()
216            .present_bound_surface(&mut self.context.borrow_mut())
217    }
218
219    fn framebuffer(&self) -> Option<NativeFramebuffer> {
220        let device = &self.device.borrow();
221        let context = &self.context.borrow();
222        device
223            .context_surface_info(context)
224            .unwrap_or(None)
225            .and_then(|info| info.framebuffer_object)
226    }
227
228    fn prepare_for_rendering(&self) {
229        let framebuffer_id = self
230            .framebuffer()
231            .map_or(0, |framebuffer| framebuffer.0.into());
232        self.gleam_gl
233            .bind_framebuffer(gleam::gl::FRAMEBUFFER, framebuffer_id);
234    }
235
236    fn read_to_image(&self, source_rectangle: DeviceIntRect) -> Option<RgbaImage> {
237        let framebuffer_id = self
238            .framebuffer()
239            .map_or(0, |framebuffer| framebuffer.0.into());
240        Framebuffer::read_framebuffer_to_image(&self.gleam_gl, framebuffer_id, source_rectangle)
241    }
242
243    fn make_current(&self) -> Result<(), Error> {
244        let device = &self.device.borrow();
245        let context = &mut self.context.borrow();
246        device.make_context_current(context)
247    }
248
249    fn create_texture(
250        &self,
251        surface: Surface,
252    ) -> Option<(SurfaceTexture, u32, UntypedSize2D<i32>)> {
253        let device = &self.device.borrow();
254        let context = &mut self.context.borrow_mut();
255        let SurfaceInfo {
256            id: front_buffer_id,
257            size,
258            ..
259        } = device.surface_info(&surface);
260        debug!("... getting texture for surface {:?}", front_buffer_id);
261        let surface_texture = device.create_surface_texture(context, surface).unwrap();
262        let gl_texture = device
263            .surface_texture_object(&surface_texture)
264            .map(|tex| tex.0.get())
265            .unwrap_or(0);
266        Some((surface_texture, gl_texture, size))
267    }
268
269    fn destroy_texture(&self, surface_texture: SurfaceTexture) -> Option<Surface> {
270        let device = &self.device.borrow();
271        let context = &mut self.context.borrow_mut();
272        device
273            .destroy_surface_texture(context, surface_texture)
274            .map_err(|(error, _)| error)
275            .ok()
276    }
277
278    fn connection(&self) -> Option<Connection> {
279        Some(self.device.borrow().connection())
280    }
281
282    fn refresh_driver(&self) -> Option<Rc<dyn RefreshDriver>> {
283        self.refresh_driver.clone()
284    }
285
286    fn adapter(&self) -> Option<Adapter> {
287        Some(self.device.borrow().adapter())
288    }
289}
290
291/// A software rendering context that uses a software OpenGL implementation to render
292/// Servo. This will generally have bad performance, but can be used in situations where
293/// it is more convenient to have consistent, but slower display output.
294///
295/// The results of the render can be accessed via [`RenderingContext::read_to_image`].
296pub struct SoftwareRenderingContext {
297    size: Cell<PhysicalSize<u32>>,
298    surfman_rendering_info: SurfmanRenderingContext,
299    swap_chain: SwapChain<Device>,
300}
301
302impl SoftwareRenderingContext {
303    pub fn new(size: PhysicalSize<u32>) -> Result<Self, Error> {
304        if size.width == 0 || size.height == 0 {
305            log::error!(
306                "Unable to create SoftwareRenderingContext with size under 1x1 ({size:?} provided)"
307            );
308            return Err(Error::Failed);
309        }
310
311        let connection = Connection::new()?;
312        let adapter = connection.create_software_adapter()?;
313        let surfman_rendering_info = SurfmanRenderingContext::new(&connection, &adapter, None)?;
314
315        let surfman_size = Size2D::new(size.width as i32, size.height as i32);
316        let surface =
317            surfman_rendering_info.create_surface(SurfaceType::Generic { size: surfman_size })?;
318        surfman_rendering_info.bind_surface(surface)?;
319        surfman_rendering_info.make_current()?;
320
321        let swap_chain = surfman_rendering_info.create_attached_swap_chain()?;
322        Ok(SoftwareRenderingContext {
323            size: Cell::new(size),
324            surfman_rendering_info,
325            swap_chain,
326        })
327    }
328}
329
330impl Drop for SoftwareRenderingContext {
331    fn drop(&mut self) {
332        let device = &mut self.surfman_rendering_info.device.borrow_mut();
333        let context = &mut self.surfman_rendering_info.context.borrow_mut();
334        let _ = self.swap_chain.destroy(device, context);
335    }
336}
337
338impl RenderingContext for SoftwareRenderingContext {
339    fn prepare_for_rendering(&self) {
340        self.surfman_rendering_info.prepare_for_rendering();
341    }
342
343    fn read_to_image(&self, source_rectangle: DeviceIntRect) -> Option<RgbaImage> {
344        self.surfman_rendering_info.read_to_image(source_rectangle)
345    }
346
347    fn size(&self) -> PhysicalSize<u32> {
348        self.size.get()
349    }
350
351    fn resize(&self, size: PhysicalSize<u32>) {
352        assert!(
353            size.width > 0 && size.height > 0,
354            "Dimensions must be at least 1x1, got {size:?}",
355        );
356
357        if self.size.get() == size {
358            return;
359        }
360
361        self.size.set(size);
362
363        let device = &mut self.surfman_rendering_info.device.borrow_mut();
364        let context = &mut self.surfman_rendering_info.context.borrow_mut();
365        let size = Size2D::new(size.width as i32, size.height as i32);
366        let _ = self.swap_chain.resize(device, context, size);
367    }
368
369    #[servo_tracing::instrument(skip_all, name = "SoftwareRenderingContext::present")]
370    fn present(&self) {
371        let device = &mut self.surfman_rendering_info.device.borrow_mut();
372        let context = &mut self.surfman_rendering_info.context.borrow_mut();
373        let _ = self
374            .swap_chain
375            .swap_buffers(device, context, PreserveBuffer::No);
376    }
377
378    fn make_current(&self) -> Result<(), Error> {
379        self.surfman_rendering_info.make_current()
380    }
381
382    fn gleam_gl_api(&self) -> Rc<dyn gleam::gl::Gl> {
383        self.surfman_rendering_info.gleam_gl.clone()
384    }
385
386    fn glow_gl_api(&self) -> Arc<glow::Context> {
387        self.surfman_rendering_info.glow_gl.clone()
388    }
389
390    fn create_texture(
391        &self,
392        surface: Surface,
393    ) -> Option<(SurfaceTexture, u32, UntypedSize2D<i32>)> {
394        self.surfman_rendering_info.create_texture(surface)
395    }
396
397    fn destroy_texture(&self, surface_texture: SurfaceTexture) -> Option<Surface> {
398        self.surfman_rendering_info.destroy_texture(surface_texture)
399    }
400
401    fn connection(&self) -> Option<Connection> {
402        self.surfman_rendering_info.connection()
403    }
404
405    fn adapter(&self) -> Option<Adapter> {
406        self.surfman_rendering_info.adapter()
407    }
408}
409
410/// A [`RenderingContext`] that uses the `surfman` library to render to a
411/// `raw-window-handle` identified window. `surfman` will attempt to create an
412/// OpenGL context and surface for this window. This is a simple implementation
413/// of the [`RenderingContext`] trait, but by default it paints to the entire
414/// window surface.
415///
416/// If you would like to paint to only a portion of the window, consider using
417/// [`OffscreenRenderingContext`] by calling [`WindowRenderingContext::offscreen_context`].
418pub struct WindowRenderingContext {
419    /// The inner size of the window in physical pixels which excludes OS decorations.
420    size: Cell<PhysicalSize<u32>>,
421    surfman_context: SurfmanRenderingContext,
422}
423
424impl WindowRenderingContext {
425    pub fn new(
426        display_handle: DisplayHandle,
427        window_handle: WindowHandle,
428        size: PhysicalSize<u32>,
429    ) -> Result<Self, Error> {
430        Self::new_with_optional_refresh_driver(display_handle, window_handle, size, None)
431    }
432
433    pub fn new_with_refresh_driver(
434        display_handle: DisplayHandle,
435        window_handle: WindowHandle,
436        size: PhysicalSize<u32>,
437        refresh_driver: Rc<dyn RefreshDriver>,
438    ) -> Result<Self, Error> {
439        Self::new_with_optional_refresh_driver(
440            display_handle,
441            window_handle,
442            size,
443            Some(refresh_driver),
444        )
445    }
446
447    fn new_with_optional_refresh_driver(
448        display_handle: DisplayHandle,
449        window_handle: WindowHandle,
450        size: PhysicalSize<u32>,
451        refresh_driver: Option<Rc<dyn RefreshDriver>>,
452    ) -> Result<Self, Error> {
453        if size.width == 0 || size.height == 0 {
454            log::error!(
455                "Unable to create WindowRenderingContext with size under 1x1 ({size:?} provided)"
456            );
457            return Err(Error::Failed);
458        }
459
460        let connection = Connection::from_display_handle(display_handle)?;
461        let adapter = connection.create_adapter()?;
462        let surfman_context = SurfmanRenderingContext::new(&connection, &adapter, refresh_driver)?;
463
464        let native_widget = connection
465            .create_native_widget_from_window_handle(
466                window_handle,
467                Size2D::new(size.width as i32, size.height as i32),
468            )
469            .expect("Failed to create native widget");
470
471        let surface = surfman_context.create_surface(SurfaceType::Widget { native_widget })?;
472        surfman_context.bind_surface(surface)?;
473        surfman_context.make_current()?;
474
475        Ok(Self {
476            size: Cell::new(size),
477            surfman_context,
478        })
479    }
480
481    pub fn offscreen_context(
482        self: &Rc<Self>,
483        size: PhysicalSize<u32>,
484    ) -> OffscreenRenderingContext {
485        OffscreenRenderingContext::new(self.clone(), size)
486    }
487
488    /// Stop rendering to the window that was used to create this `WindowRenderingContext`
489    /// or last set with [`Self::set_window`].
490    ///
491    /// TODO: This should be removed once `WebView`s can replace their `RenderingContext`s.
492    pub fn take_window(&self) -> Result<(), Error> {
493        let device = self.surfman_context.device.borrow_mut();
494        let mut context = self.surfman_context.context.borrow_mut();
495        let mut surface = device.unbind_surface_from_context(&mut context)?.unwrap();
496        device.destroy_surface(&mut context, &mut surface)?;
497        Ok(())
498    }
499
500    /// Replace the window that this [`WindowRenderingContext`] renders to and give it a new
501    /// size.
502    ///
503    /// TODO: This should be removed once `WebView`s can replace their `RenderingContext`s.
504    pub fn set_window(
505        &self,
506        window_handle: WindowHandle,
507        size: PhysicalSize<u32>,
508    ) -> Result<(), Error> {
509        let device = self.surfman_context.device.borrow_mut();
510        let mut context = self.surfman_context.context.borrow_mut();
511
512        let native_widget = device
513            .connection()
514            .create_native_widget_from_window_handle(
515                window_handle,
516                Size2D::new(size.width as i32, size.height as i32),
517            )
518            .expect("Failed to create native widget");
519
520        let surface_access = SurfaceAccess::GPUOnly;
521        let surface_type = SurfaceType::Widget { native_widget };
522        let surface = device.create_surface(&context, surface_access, surface_type)?;
523
524        device
525            .bind_surface_to_context(&mut context, surface)
526            .map_err(|(err, mut surface)| {
527                let _ = device.destroy_surface(&mut context, &mut surface);
528                err
529            })?;
530        device.make_context_current(&context)?;
531        Ok(())
532    }
533
534    pub fn surfman_details(&self) -> (RefMut<'_, Device>, RefMut<'_, Context>) {
535        (
536            self.surfman_context.device.borrow_mut(),
537            self.surfman_context.context.borrow_mut(),
538        )
539    }
540}
541
542impl RenderingContext for WindowRenderingContext {
543    fn prepare_for_rendering(&self) {
544        self.surfman_context.prepare_for_rendering();
545    }
546
547    fn read_to_image(&self, source_rectangle: DeviceIntRect) -> Option<RgbaImage> {
548        self.surfman_context.read_to_image(source_rectangle)
549    }
550
551    fn size(&self) -> PhysicalSize<u32> {
552        self.size.get()
553    }
554
555    fn resize(&self, size: PhysicalSize<u32>) {
556        match self.surfman_context.resize_bound_surface(size) {
557            Ok(..) => self.size.set(size),
558            Err(error) => warn!("Error resizing surface: {error:?}"),
559        }
560    }
561
562    #[servo_tracing::instrument(skip_all, name = "WindowRenderingContext::present")]
563    fn present(&self) {
564        if let Err(error) = self.surfman_context.present_bound_surface() {
565            warn!("Error presenting surface: {error:?}");
566        }
567    }
568
569    fn make_current(&self) -> Result<(), Error> {
570        self.surfman_context.make_current()
571    }
572
573    fn gleam_gl_api(&self) -> Rc<dyn gleam::gl::Gl> {
574        self.surfman_context.gleam_gl.clone()
575    }
576
577    fn glow_gl_api(&self) -> Arc<glow::Context> {
578        self.surfman_context.glow_gl.clone()
579    }
580
581    fn create_texture(
582        &self,
583        surface: Surface,
584    ) -> Option<(SurfaceTexture, u32, UntypedSize2D<i32>)> {
585        self.surfman_context.create_texture(surface)
586    }
587
588    fn destroy_texture(&self, surface_texture: SurfaceTexture) -> Option<Surface> {
589        self.surfman_context.destroy_texture(surface_texture)
590    }
591
592    fn connection(&self) -> Option<Connection> {
593        self.surfman_context.connection()
594    }
595
596    fn refresh_driver(&self) -> Option<Rc<dyn RefreshDriver>> {
597        self.surfman_context.refresh_driver()
598    }
599
600    fn adapter(&self) -> Option<Adapter> {
601        self.surfman_context.adapter()
602    }
603}
604
605struct Framebuffer {
606    gl: Rc<dyn Gl>,
607    framebuffer_id: gl::GLuint,
608    renderbuffer_id: gl::GLuint,
609    texture_id: gl::GLuint,
610}
611
612impl Framebuffer {
613    fn bind(&self) {
614        trace!("Binding FBO {}", self.framebuffer_id);
615        self.gl
616            .bind_framebuffer(gl::FRAMEBUFFER, self.framebuffer_id)
617    }
618}
619
620impl Drop for Framebuffer {
621    fn drop(&mut self) {
622        self.gl.bind_framebuffer(gl::FRAMEBUFFER, 0);
623        self.gl.delete_textures(&[self.texture_id]);
624        self.gl.delete_renderbuffers(&[self.renderbuffer_id]);
625        self.gl.delete_framebuffers(&[self.framebuffer_id]);
626    }
627}
628
629impl Framebuffer {
630    fn new(gl: Rc<dyn Gl>, size: PhysicalSize<u32>) -> Self {
631        let framebuffer_ids = gl.gen_framebuffers(1);
632        gl.bind_framebuffer(gl::FRAMEBUFFER, framebuffer_ids[0]);
633
634        let texture_ids = gl.gen_textures(1);
635        gl.bind_texture(gl::TEXTURE_2D, texture_ids[0]);
636        gl.tex_image_2d(
637            gl::TEXTURE_2D,
638            0,
639            gl::RGBA as gl::GLint,
640            size.width as gl::GLsizei,
641            size.height as gl::GLsizei,
642            0,
643            gl::RGBA,
644            gl::UNSIGNED_BYTE,
645            None,
646        );
647        gl.tex_parameter_i(
648            gl::TEXTURE_2D,
649            gl::TEXTURE_MAG_FILTER,
650            gl::NEAREST as gl::GLint,
651        );
652        gl.tex_parameter_i(
653            gl::TEXTURE_2D,
654            gl::TEXTURE_MIN_FILTER,
655            gl::NEAREST as gl::GLint,
656        );
657
658        gl.framebuffer_texture_2d(
659            gl::FRAMEBUFFER,
660            gl::COLOR_ATTACHMENT0,
661            gl::TEXTURE_2D,
662            texture_ids[0],
663            0,
664        );
665
666        gl.bind_texture(gl::TEXTURE_2D, 0);
667
668        let renderbuffer_ids = gl.gen_renderbuffers(1);
669        let depth_rb = renderbuffer_ids[0];
670        gl.bind_renderbuffer(gl::RENDERBUFFER, depth_rb);
671        gl.renderbuffer_storage(
672            gl::RENDERBUFFER,
673            gl::DEPTH_COMPONENT24,
674            size.width as gl::GLsizei,
675            size.height as gl::GLsizei,
676        );
677        gl.framebuffer_renderbuffer(
678            gl::FRAMEBUFFER,
679            gl::DEPTH_ATTACHMENT,
680            gl::RENDERBUFFER,
681            depth_rb,
682        );
683
684        Self {
685            gl,
686            framebuffer_id: *framebuffer_ids
687                .first()
688                .expect("Guaranteed by GL operations"),
689            renderbuffer_id: *renderbuffer_ids
690                .first()
691                .expect("Guaranteed by GL operations"),
692            texture_id: *texture_ids.first().expect("Guaranteed by GL operations"),
693        }
694    }
695
696    fn read_to_image(&self, source_rectangle: DeviceIntRect) -> Option<RgbaImage> {
697        Self::read_framebuffer_to_image(&self.gl, self.framebuffer_id, source_rectangle)
698    }
699
700    fn read_framebuffer_to_image(
701        gl: &Rc<dyn Gl>,
702        framebuffer_id: u32,
703        source_rectangle: DeviceIntRect,
704    ) -> Option<RgbaImage> {
705        gl.bind_framebuffer(gl::FRAMEBUFFER, framebuffer_id);
706
707        // For some reason, OSMesa fails to render on the 3rd
708        // attempt in headless mode, under some conditions.
709        // I think this can only be some kind of synchronization
710        // bug in OSMesa, but explicitly un-binding any vertex
711        // array here seems to work around that bug.
712        // See https://github.com/servo/servo/issues/18606.
713        gl.bind_vertex_array(0);
714
715        let mut pixels = gl.read_pixels(
716            source_rectangle.min.x,
717            source_rectangle.min.y,
718            source_rectangle.width(),
719            source_rectangle.height(),
720            gl::RGBA,
721            gl::UNSIGNED_BYTE,
722        );
723        let gl_error = gl.get_error();
724        if gl_error != gl::NO_ERROR {
725            warn!("GL error code 0x{gl_error:x} set after read_pixels");
726        }
727
728        // flip image vertically (texture is upside down)
729        let source_rectangle = source_rectangle.to_usize();
730        let stride = source_rectangle.width() * 4;
731        let height = source_rectangle.height();
732        for y in 0..height / 2 {
733            let (top, bottom) = pixels.split_at_mut((height - y - 1) * stride);
734            top[y * stride..(y + 1) * stride].swap_with_slice(&mut bottom[..stride]);
735        }
736
737        RgbaImage::from_raw(
738            source_rectangle.width() as u32,
739            source_rectangle.height() as u32,
740            pixels,
741        )
742    }
743}
744
745pub struct OffscreenRenderingContext {
746    parent_context: Rc<WindowRenderingContext>,
747    size: Cell<PhysicalSize<u32>>,
748    framebuffer: RefCell<Framebuffer>,
749}
750
751type RenderToParentCallback = Box<dyn Fn(&glow::Context, Rect<i32>) + Send + Sync>;
752
753impl OffscreenRenderingContext {
754    fn new(parent_context: Rc<WindowRenderingContext>, size: PhysicalSize<u32>) -> Self {
755        assert!(
756            size.width != 0 && size.height != 0,
757            "Dimensions must be at least 1x1, got {size:?}",
758        );
759
760        let framebuffer = RefCell::new(Framebuffer::new(parent_context.gleam_gl_api(), size));
761        Self {
762            parent_context,
763            size: Cell::new(size),
764            framebuffer,
765        }
766    }
767
768    pub fn parent_context(&self) -> &WindowRenderingContext {
769        &self.parent_context
770    }
771
772    pub fn render_to_parent_callback(&self) -> Option<RenderToParentCallback> {
773        // Don't accept a `None` context for the source framebuffer.
774        let front_framebuffer_id =
775            NonZeroU32::new(self.framebuffer.borrow().framebuffer_id).map(NativeFramebuffer)?;
776        let parent_context_framebuffer_id = self.parent_context.surfman_context.framebuffer();
777        let size = self.size.get();
778        let size = Size2D::new(size.width as i32, size.height as i32);
779        Some(Box::new(move |gl, target_rect| {
780            Self::blit_framebuffer(
781                gl,
782                Rect::new(Point2D::origin(), size.to_i32()),
783                front_framebuffer_id,
784                target_rect,
785                parent_context_framebuffer_id,
786            );
787        }))
788    }
789
790    #[expect(unsafe_code)]
791    fn blit_framebuffer(
792        gl: &glow::Context,
793        source_rect: Rect<i32>,
794        source_framebuffer_id: NativeFramebuffer,
795        target_rect: Rect<i32>,
796        target_framebuffer_id: Option<NativeFramebuffer>,
797    ) {
798        use glow::HasContext as _;
799        unsafe {
800            gl.clear_color(0.0, 0.0, 0.0, 0.0);
801            gl.scissor(
802                target_rect.origin.x,
803                target_rect.origin.y,
804                target_rect.width(),
805                target_rect.height(),
806            );
807            gl.enable(gl::SCISSOR_TEST);
808            gl.clear(gl::COLOR_BUFFER_BIT);
809            gl.disable(gl::SCISSOR_TEST);
810
811            gl.bind_framebuffer(gl::READ_FRAMEBUFFER, Some(source_framebuffer_id));
812            gl.bind_framebuffer(gl::DRAW_FRAMEBUFFER, target_framebuffer_id);
813
814            gl.blit_framebuffer(
815                source_rect.origin.x,
816                source_rect.origin.y,
817                source_rect.origin.x + source_rect.width(),
818                source_rect.origin.y + source_rect.height(),
819                target_rect.origin.x,
820                target_rect.origin.y,
821                target_rect.origin.x + target_rect.width(),
822                target_rect.origin.y + target_rect.height(),
823                gl::COLOR_BUFFER_BIT,
824                gl::NEAREST,
825            );
826            gl.bind_framebuffer(gl::FRAMEBUFFER, target_framebuffer_id);
827        }
828    }
829}
830
831impl RenderingContext for OffscreenRenderingContext {
832    fn size(&self) -> PhysicalSize<u32> {
833        self.size.get()
834    }
835
836    fn resize(&self, new_size: PhysicalSize<u32>) {
837        assert!(
838            new_size.width != 0 && new_size.height != 0,
839            "Dimensions must be at least 1x1, got {new_size:?}",
840        );
841
842        let old_size = self.size.get();
843        if old_size == new_size {
844            return;
845        }
846
847        let gl = self.parent_context.gleam_gl_api();
848        let new_framebuffer = Framebuffer::new(gl.clone(), new_size);
849
850        let old_framebuffer =
851            std::mem::replace(&mut *self.framebuffer.borrow_mut(), new_framebuffer);
852        self.size.set(new_size);
853
854        let blit_size = new_size.min(old_size);
855        let rect = Rect::new(
856            Point2D::origin(),
857            Size2D::new(blit_size.width, blit_size.height),
858        )
859        .to_i32();
860
861        let Some(old_framebuffer_id) =
862            NonZeroU32::new(old_framebuffer.framebuffer_id).map(NativeFramebuffer)
863        else {
864            return;
865        };
866        let new_framebuffer_id =
867            NonZeroU32::new(self.framebuffer.borrow().framebuffer_id).map(NativeFramebuffer);
868        Self::blit_framebuffer(
869            &self.glow_gl_api(),
870            rect,
871            old_framebuffer_id,
872            rect,
873            new_framebuffer_id,
874        );
875    }
876
877    fn prepare_for_rendering(&self) {
878        self.framebuffer.borrow().bind();
879    }
880
881    fn present(&self) {}
882
883    fn make_current(&self) -> Result<(), surfman::Error> {
884        self.parent_context.make_current()
885    }
886
887    fn gleam_gl_api(&self) -> Rc<dyn gleam::gl::Gl> {
888        self.parent_context.gleam_gl_api()
889    }
890
891    fn glow_gl_api(&self) -> Arc<glow::Context> {
892        self.parent_context.glow_gl_api()
893    }
894
895    fn create_texture(
896        &self,
897        surface: Surface,
898    ) -> Option<(SurfaceTexture, u32, UntypedSize2D<i32>)> {
899        self.parent_context.create_texture(surface)
900    }
901
902    fn destroy_texture(&self, surface_texture: SurfaceTexture) -> Option<Surface> {
903        self.parent_context.destroy_texture(surface_texture)
904    }
905
906    fn connection(&self) -> Option<Connection> {
907        self.parent_context.connection()
908    }
909
910    fn read_to_image(&self, source_rectangle: DeviceIntRect) -> Option<RgbaImage> {
911        self.framebuffer.borrow().read_to_image(source_rectangle)
912    }
913
914    fn refresh_driver(&self) -> Option<Rc<dyn RefreshDriver>> {
915        self.parent_context().refresh_driver()
916    }
917
918    fn adapter(&self) -> Option<Adapter> {
919        self.parent_context.adapter()
920    }
921}
922
923fn print_diagnostics_information_on_context_creation_failure(
924    device: &Device,
925    desired_api: GLApi,
926    desired_version: GLVersion,
927) {
928    println!("===============================================================");
929    println!(
930        "Could not create a {desired_api:?} {:?}.{:?} context when starting Servo.",
931        desired_version.major, desired_version.minor
932    );
933
934    let version = surfman::GLVersion { major: 1, minor: 0 };
935    match device
936        .create_context_descriptor(&ContextAttributes {
937            flags: ContextAttributeFlags::empty(),
938            version,
939        })
940        .and_then(|context_descriptor| device.create_context(&context_descriptor, None))
941    {
942        Ok(mut context) => {
943            #[expect(unsafe_code)]
944            let glow_gl = unsafe {
945                glow::Context::from_loader_function(|function_name| {
946                    device.get_proc_address(&context, function_name)
947                })
948            };
949
950            println!(
951                "It's likely that your version of OpenGL ({:?}.{:?}) is too old.",
952                glow_gl.version().major,
953                glow_gl.version().minor
954            );
955            println!("If not, please file a bug at https://github.com/servo/servo/issues.");
956            let _ = device.destroy_context(&mut context);
957        },
958        Err(_) => {
959            println!("Could not create any {desired_api:?} context.");
960            println!("Ensure that OpenGL is working on your system.");
961            println!("If it is, please file a bug at https://github.com/servo/servo/issues.");
962        },
963    }
964    println!("===============================================================\n");
965}
966
967#[cfg(test)]
968mod test {
969    use dpi::PhysicalSize;
970    use euclid::{Box2D, Point2D, Size2D};
971    use gleam::gl;
972    use image::Rgba;
973    use surfman::{Connection, ContextAttributeFlags, ContextAttributes, Error, GLApi, GLVersion};
974
975    use super::Framebuffer;
976    use crate::rendering_context::SoftwareRenderingContext;
977
978    #[test]
979    #[expect(unsafe_code)]
980    fn test_read_pixels() -> Result<(), Error> {
981        let connection = Connection::new()?;
982        let adapter = connection.create_software_adapter()?;
983        let device = connection.create_device(&adapter)?;
984        let context_descriptor = device.create_context_descriptor(&ContextAttributes {
985            version: GLVersion::new(3, 0),
986            flags: ContextAttributeFlags::empty(),
987        })?;
988        let mut context = device.create_context(&context_descriptor, None)?;
989
990        let gl = match connection.gl_api() {
991            GLApi::GL => unsafe { gl::GlFns::load_with(|s| device.get_proc_address(&context, s)) },
992            GLApi::GLES => unsafe {
993                gl::GlesFns::load_with(|s| device.get_proc_address(&context, s))
994            },
995        };
996
997        device.make_context_current(&context)?;
998
999        {
1000            const SIZE: u32 = 16;
1001            let framebuffer = Framebuffer::new(gl, PhysicalSize::new(SIZE, SIZE));
1002            framebuffer.bind();
1003            framebuffer
1004                .gl
1005                .clear_color(12.0 / 255.0, 34.0 / 255.0, 56.0 / 255.0, 78.0 / 255.0);
1006            framebuffer.gl.clear(gl::COLOR_BUFFER_BIT);
1007
1008            let rect = Box2D::from_origin_and_size(Point2D::zero(), Size2D::new(SIZE, SIZE));
1009            let img = framebuffer
1010                .read_to_image(rect.to_i32())
1011                .expect("Should have been able to read back image.");
1012            assert_eq!(img.width(), SIZE);
1013            assert_eq!(img.height(), SIZE);
1014
1015            let expected_pixel: Rgba<u8> = Rgba([12, 34, 56, 78]);
1016            assert!(img.pixels().all(|&p| p == expected_pixel));
1017        }
1018
1019        device.destroy_context(&mut context)?;
1020
1021        Ok(())
1022    }
1023
1024    #[test]
1025    fn test_minimum_size_error() {
1026        let result = SoftwareRenderingContext::new(PhysicalSize {
1027            width: 0,
1028            height: 1,
1029        });
1030        match result {
1031            Err(surfman::Error::Failed) => (),
1032            _ => panic!("Expected {:?}", surfman::Error::Failed),
1033        }
1034    }
1035}