Skip to main content

mln_gfx/
renderer_backend.rs

1// Ports include/mln/gfx/renderer_backend.hpp and src/mln/gfx/renderer_backend.cpp
2//
3// TODO(port): `TaggedScheduler threadPool` / `getThreadPool()` (render jobs
4// scheduled by background workers) arrives with the first user; the WebGPU
5// context calls `runRenderJobs()` in begin/endFrame, a no-op until then.
6
7use crate::backend_scope::BackendScope;
8use crate::context::Context;
9use crate::renderable::Renderable;
10use crate::shader_registry::ShaderRegistry;
11use crate::shaders::program_parameters::ProgramParameters;
12use mln_util::identity::SimpleIdentity;
13use std::any::Any;
14use std::cell::OnceCell;
15use std::rc::Rc;
16
17#[derive(Clone, Copy, Debug, PartialEq, Eq)]
18pub enum ContextMode {
19    Unique,
20    Shared,
21}
22
23/// The data members of `gfx::RendererBackend`.
24pub struct RendererBackendBase {
25    pub unique_id: SimpleIdentity,
26    context: OnceCell<Rc<dyn Context>>,
27    context_mode: ContextMode,
28}
29
30impl RendererBackendBase {
31    pub fn new(context_mode: ContextMode) -> Self {
32        RendererBackendBase { unique_id: SimpleIdentity::new(), context: OnceCell::new(), context_mode }
33    }
34
35    /// `context.reset()` in the backend destructors. Returns the context, so
36    /// a backend can release what it caches before dropping it.
37    pub fn reset_context(&mut self) -> Option<Rc<dyn Context>> {
38        self.context.take()
39    }
40}
41
42pub trait RendererBackend: Any {
43    fn renderer_backend_base(&self) -> &RendererBackendBase;
44    fn as_any(&self) -> &dyn Any;
45
46    /// Returns the device's context, created on first use (`std::call_once`).
47    /// Must be called inside a `BackendScope`.
48    fn get_context(&self) -> &dyn Context {
49        &**self.get_context_ptr()
50    }
51
52    /// The context as a shared pointer (the C++ context is owned by the
53    /// backend; passes and resources in the port hold `Rc`s instead of
54    /// references).
55    fn get_context_ptr(&self) -> &Rc<dyn Context> {
56        debug_assert!(BackendScope::exists());
57        self.renderer_backend_base().context.get_or_init(|| self.create_context())
58    }
59
60    fn context_is_shared(&self) -> bool {
61        self.renderer_backend_base().context_mode == ContextMode::Shared
62    }
63
64    fn unique_id(&self) -> SimpleIdentity {
65        self.renderer_backend_base().unique_id
66    }
67
68    /// Returns a reference to the default surface that should be rendered on.
69    fn get_default_renderable(&self) -> &dyn Renderable;
70
71    /// One-time shader initialization
72    fn init_shaders(&self, registry: &ShaderRegistry, parameters: &ProgramParameters);
73
74    /// Called when the backend's GL context needs to be made active or
75    /// inactive (protected + `friend class BackendScope` in C++).
76    fn create_context(&self) -> Rc<dyn Context>;
77    fn activate(&self);
78    fn deactivate(&self);
79}