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