Skip to main content

mln_gfx/
renderer_backend.rs

1use std::any::Any;
2use std::cell::RefMut;
3
4use crate::gpu::Gpu;
5
6/// What a renderer draws with on a device: the backend's [`Gpu`]. What it
7/// draws into is a `FrameTarget` built on it.
8pub trait RendererBackend: Any {
9    /// The backend's [`Gpu`], which owns the renderer's resources and runs
10    /// its frames.
11    fn gpu(&self) -> RefMut<'_, dyn Gpu>;
12
13    /// Keeps what the backend's calls need ready across many of them, such
14    /// as OpenGL's context current, until the hold drops, as when a panic
15    /// unwinds. Holds nest. A backend that needs nothing holds nothing.
16    fn hold(&self) -> Hold<'_> {
17        Hold::default()
18    }
19}
20
21impl dyn RendererBackend {
22    /// The concrete type behind this trait object, if it is a `T`.
23    pub fn downcast_ref<T: RendererBackend>(&self) -> Option<&T> {
24        let any: &dyn Any = self;
25        any.downcast_ref()
26    }
27}
28
29/// What a backend keeps ready while a [`RendererBackend::hold`] lasts,
30/// released when it drops.
31#[derive(Default)]
32#[must_use = "the hold ends when dropped"]
33pub struct Hold<'a> {
34    release: Option<Box<dyn FnOnce() + 'a>>,
35}
36
37impl<'a> Hold<'a> {
38    /// A hold that `release` ends.
39    pub fn new(release: impl FnOnce() + 'a) -> Hold<'a> {
40        Hold { release: Some(Box::new(release)) }
41    }
42}
43
44impl Drop for Hold<'_> {
45    fn drop(&mut self) {
46        if let Some(release) = self.release.take() {
47            release();
48        }
49    }
50}