mln-rs-runtime 0.0.22

Part of mln-rs, a MapLibre map renderer written in Rust. Depend on mln-rs instead.
Documentation
use std::any::Any;
use std::sync::Arc;

use mln_engine::exec::event_queue::Waker;
use mln_engine::exec::pool::Pool;
use mln_engine::text::GlyphCache;
use mln_engine::text::font_face_engine::FontFaceEngine;
use mln_engine::text::local_fonts::LocalGlyphs;
use mln_engine::{Registry, Renderer, RendererEvent, RendererEvents};
use mln_gfx::SyncKind;
use mln_style::error::Error;
use mln_style::size::Size;

use super::Worker;
use crate::render::local::LocalTarget;
use crate::render::session::{SessionShared, physical_size};
use crate::render::target::{BorrowedRing, Device, DeviceLease, ExportKind, ExportedRing, SentSurface, SurfaceOverlay};
use crate::runtime::Outbox;

/// What a session's thread needs to build its renderer.
pub(crate) struct Init {
    pub(crate) target: TargetInit,
    pub(crate) size: Size,
    pub(crate) scale_factor: f64,
    pub(crate) glyph_cache: Arc<GlyphCache>,
    /// What the renderer loads a style's font faces with.
    pub(crate) font_face_engine: Arc<dyn FontFaceEngine>,
    /// What the renderer's tile workers lay out with.
    pub(crate) registry: Arc<Registry>,
    /// Whether the renderer keeps tiles that left the view.
    pub(crate) tile_cache_enabled: bool,
    /// How many worker instances behind the worker codec the renderer's
    /// tile workers run in, or 0 for `pool`.
    pub(crate) tile_worker_instances: usize,
    /// How the renderer draws glyphs from local fonts.
    pub(crate) local_glyphs: LocalGlyphs,
    /// Why the session's device couldn't be made before the build: in the
    /// browser, whose WebGPU makes devices asynchronously.
    pub(crate) failure: Option<Error>,
    /// Where the renderer's background work runs: the runtime's pool.
    pub(crate) pool: Pool,
}

/// What a session renders into, before its thread builds it.
pub(crate) enum TargetInit {
    Offscreen(Option<Device>),
    Surface { surface: SentSurface, device: Option<Device> },
    Borrowed { ring: BorrowedRing, device: Device, producer: SyncKind },
    Exported { ring: ExportedRing, device: Device, kind: ExportKind, producer: SyncKind },
}

impl TargetInit {
    /// In the browser, whether the target renders with WebGPU without the
    /// host's device: the session asks the browser for one before it builds.
    #[cfg(target_family = "wasm")]
    fn needs_web_gpu_device(&self) -> bool {
        match self {
            TargetInit::Offscreen(None) => cfg!(feature = "webgpu"),
            TargetInit::Surface { device: None, surface } => surface.presents_with_web_gpu(),
            _ => false,
        }
    }

    #[cfg(has_wasm_webgpu)]
    fn set_device(&mut self, made: Device) {
        match self {
            TargetInit::Offscreen(device @ None) | TargetInit::Surface { device: device @ None, .. } => {
                *device = Some(made);
            }
            _ => {}
        }
    }

    /// The target on the session's lease of the host's device, and the
    /// lease, as [`Device::lease`] makes them.
    pub(crate) fn lease(self) -> (TargetInit, DeviceLease) {
        let lease_some = |device: Option<Device>| match device.map(Device::lease) {
            Some((device, lease)) => (Some(device), lease),
            None => (None, DeviceLease::default()),
        };
        match self {
            TargetInit::Offscreen(device) => {
                let (device, lease) = lease_some(device);
                (TargetInit::Offscreen(device), lease)
            }
            TargetInit::Surface { surface, device } => {
                let (device, lease) = lease_some(device);
                (TargetInit::Surface { surface, device }, lease)
            }
            TargetInit::Borrowed { ring, device, producer } => {
                let (device, lease) = device.lease();
                (TargetInit::Borrowed { ring, device, producer }, lease)
            }
            TargetInit::Exported { ring, device, kind, producer } => {
                let (device, lease) = device.lease();
                (TargetInit::Exported { ring, device, kind, producer }, lease)
            }
        }
    }
}

/// In the browser, makes the device that the session's build needs, if
/// any: the browser's WebGPU makes one asynchronously. The future resolves
/// once it is in the session's [`Init`], or its failure is.
#[cfg(target_family = "wasm")]
pub(crate) fn prepare(shared: &Arc<SessionShared>) -> impl Future<Output = ()> + 'static {
    let needs_device = shared
        .state
        .lock()
        .init
        .as_ref()
        .and_then(|init| init.downcast_ref::<Init>())
        .is_some_and(|init| init.target.needs_web_gpu_device());
    let shared = Arc::clone(shared);
    async move {
        if !needs_device {
            return;
        }
        #[cfg(feature = "webgpu")]
        let made = Device::request_web_gpu().await;
        #[cfg(not(feature = "webgpu"))]
        let made: Result<Device, Error> = Err(Error::unsupported("this build has no WebGPU"));
        let mut state = shared.state.lock();
        if let Some(init) = state.init.as_mut().and_then(|init| init.downcast_mut::<Init>()) {
            match made {
                #[cfg(feature = "webgpu")]
                Ok(device) => init.target.set_device(device),
                #[cfg(not(feature = "webgpu"))]
                Ok(_) => {}
                Err(error) => init.failure = Some(error),
            }
        }
    }
}

/// Builds the session's renderer into `slot`, on the thread that runs the
/// session's work, before any other work. The build takes `overlay` for
/// the session's first surface, if it builds.
pub(crate) fn build(shared: &Arc<SessionShared>, slot: &mut Option<Worker>, overlay: &mut Option<SurfaceOverlay>) {
    let Some(Ok(init)) = shared.state.lock().init.take().map(<Box<dyn Any + Send>>::downcast::<Init>) else {
        return;
    };
    let _call = shared.enter_call();
    let mut outbox = Outbox::default();
    let gate = shared.gate.lock();
    let worker = Worker::new(Arc::clone(shared), *init, overlay.take(), &mut outbox);
    *slot = Some(worker);
    drop(gate);
    shared.wait_for_senders();
    outbox.deliver();
}

/// What the session draws into, with the renderer that the target owns, and
/// what the session makes a renderer with.
pub(super) struct Gfx {
    pub(super) target: LocalTarget,
    glyph_cache: Arc<GlyphCache>,
    font_face_engine: Arc<dyn FontFaceEngine>,
    /// What the renderer's tile workers lay out with (`Init`).
    registry: Arc<Registry>,
    /// How the renderer draws glyphs from local fonts (`Init`).
    local_glyphs: LocalGlyphs,
    /// Where the renderer's background work runs (`Init`).
    pool: Pool,
    /// The worker instances of the renderer's tile workers (`Init`).
    tile_worker_instances: usize,
}

impl Gfx {
    /// How many graphics objects a `Gfx` holds: its target, and its
    /// renderer's, which the renderer makes when it first draws.
    pub(super) const OBJECTS: u32 = 2;

    /// A renderer on `init`'s target, which reports to `events`, with
    /// `overlay` drawn over the frames that a surface target presents.
    pub(super) fn new(init: Init, overlay: Option<SurfaceOverlay>, events: &RendererEvents) -> Result<Gfx, Error> {
        let Init {
            target,
            size,
            scale_factor,
            glyph_cache,
            font_face_engine,
            registry,
            tile_cache_enabled,
            tile_worker_instances,
            local_glyphs,
            failure,
            pool,
        } = init;
        if let Some(failure) = failure {
            return Err(failure);
        }
        let pixel_ratio = scale_factor as f32;
        let size = physical_size(size, scale_factor)?;
        let target = match target {
            TargetInit::Offscreen(device) => LocalTarget::offscreen(device, size)?,
            TargetInit::Surface { surface, device } => LocalTarget::surface(surface.receive()?, overlay, device, size)?,
            TargetInit::Borrowed { ring, device, producer } => LocalTarget::borrowed(device, ring, producer)?,
            TargetInit::Exported { ring, device, kind, producer } => {
                LocalTarget::exported(device, &ring, kind, size, producer)?
            }
        };
        let mut gfx =
            Gfx { target, glyph_cache, font_face_engine, registry, local_glyphs, pool, tile_worker_instances };
        gfx.make_renderer(events, pixel_ratio, tile_cache_enabled);
        Ok(gfx)
    }

    /// Makes the target's renderer, on its backend, which reports to
    /// `events`, draws at `pixel_ratio` and keeps tiles that left the view
    /// when `tile_cache_enabled` says so.
    pub(super) fn make_renderer(&mut self, events: &RendererEvents, pixel_ratio: f32, tile_cache_enabled: bool) {
        let Gfx { target, glyph_cache, font_face_engine, registry, local_glyphs, pool, tile_worker_instances } = self;
        target.renderer_or(|gpu| {
            let mut renderer = Renderer::with_fonts(
                gpu,
                pixel_ratio,
                local_glyphs.clone(),
                Arc::clone(glyph_cache),
                Arc::clone(font_face_engine),
                Arc::clone(registry),
                invalidate(events),
                pool,
            );
            renderer.set_tile_cache_enabled(tile_cache_enabled);
            renderer.set_event_queue(Some(events.clone()));
            set_tile_workers(&mut renderer, registry, *tile_worker_instances);
            renderer
        });
    }
}

/// The renderer's waker: it asks the map for an update through `events`,
/// the queue the renderer reports to.
fn invalidate(events: &RendererEvents) -> Waker {
    let events = events.clone();
    Arc::new(move || events.push(RendererEvent::Invalidate))
}

/// In the browser, puts the renderer's tile workers in the instance's Web
/// Workers, which lay out with `registry`. Elsewhere they stay on the
/// background threads, unless `instances` puts them in that many worker
/// instances behind the worker codec, as the browser's are.
fn set_tile_workers(renderer: &mut Renderer, registry: &Arc<Registry>, instances: usize) {
    #[cfg(target_family = "wasm")]
    {
        let _ = instances;
        if let Some(workers) = crate::web::tile_workers(registry) {
            renderer.set_tile_workers(workers);
        }
    }
    #[cfg(not(target_family = "wasm"))]
    if instances > 0 {
        use mln_engine::worker::worker_codec::{RemoteWorkers, ThreadWorkerInstances};
        let layout = Arc::clone(registry);
        renderer.set_tile_workers(RemoteWorkers::new(Arc::clone(registry), move |replies| {
            Box::new(ThreadWorkerInstances::new(instances, layout, &replies))
        }));
    }
}