use std::any::Any;
use std::sync::{Arc, Weak};
use mln_gfx::gpu::Gpu;
use mln_style::StyleRegistry;
use mln_style::layer::{Layer, LayerStyle, LayerTypeInfo, NoProperties, SourceKind, StyleLayerType};
use mln_style::property::table::{PropertyTable, PropertyVisitor};
use crate::camera::{FrameProjection, MapView};
use crate::draw::context::Context;
use crate::layer::bucket::NoBucket;
use crate::layer::layer_drawing::{DrawGroup, DrawOrder, LayerDrawing, TileMap};
use crate::layer::layer_type::{EvaluatedLayer, LayerType};
use crate::layer::layout::NoLayout;
use crate::layer::render_layer::{LayerValues, Parts, PartsMut, RenderLayer, RenderLayerBase, TypedLayer};
use crate::log_target;
use crate::render::paint_parameters::PaintParameters;
use crate::render::pass::RenderPass;
use crate::render::tile::NoTileBucket;
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct CustomLayerFrame {
pub view: MapView,
pub projection: FrameProjection,
pub width: u32,
pub height: u32,
}
pub struct CustomLayerPrerenderParameters<'a> {
pub encoder: &'a mut dyn Any,
pub frame: &'a CustomLayerFrame,
}
pub struct CustomLayerRenderParameters<'a> {
pub pass: &'a mut dyn Any,
pub frame: &'a CustomLayerFrame,
pub layer_depth: f64,
}
pub trait CustomLayerHost: Send + Sync {
fn prerender(&self, _parameters: &mut CustomLayerPrerenderParameters<'_>) {}
fn render(&self, _parameters: &mut CustomLayerRenderParameters<'_>) {}
fn deinitialize(&self) {}
fn context_lost(&self) {}
}
pub struct Custom;
static PROPERTIES: PropertyTable = PropertyTable::new(&[], &[]);
impl StyleLayerType for Custom {
const INFO: LayerTypeInfo = LayerTypeInfo {
name: "custom",
source: SourceKind::None,
pass_3d: false,
fading_tiles: false,
cross_tile_index: false,
from_json: false,
};
const PROPERTIES: &'static PropertyTable = &PROPERTIES;
type LayoutProperties = NoProperties;
type PaintProperties = NoProperties;
type Extra = CustomHost;
fn visit_property<V: PropertyVisitor<LayerStyle<Self>>>(_slot: usize, _visitor: V) -> Option<V::Output> {
None
}
}
impl Custom {
#[must_use]
pub fn layer(registry: &StyleRegistry, id: &str, host: Arc<dyn CustomLayerHost>) -> Layer {
let mut style = LayerStyle::<Custom>::new(id.to_owned(), String::new());
style.extra = CustomHost(Arc::downgrade(&host));
Layer::from_style_holding(Arc::new(style), Arc::clone(registry.functions()), Arc::new(host))
}
}
#[derive(Clone)]
pub struct CustomHost(Weak<dyn CustomLayerHost>);
impl Default for CustomHost {
fn default() -> Self {
struct NoHost;
impl CustomLayerHost for NoHost {}
CustomHost(Weak::<NoHost>::new())
}
}
impl CustomHost {
#[must_use]
pub fn get(&self) -> Option<Arc<dyn CustomLayerHost>> {
self.0.upgrade()
}
#[must_use]
pub fn is(&self, host: &Arc<dyn CustomLayerHost>) -> bool {
std::ptr::addr_eq(self.0.as_ptr(), Arc::as_ptr(host))
}
}
impl LayerType for Custom {
type Layout = NoLayout;
type Bucket = NoBucket;
type TileBucket<'a> = NoTileBucket;
fn render_layer(style: Arc<LayerStyle<Custom>>) -> Box<dyn RenderLayer> {
Box::new(RenderCustomLayer::new(style))
}
}
pub(crate) struct RenderCustomLayer {
base: RenderLayerBase,
values: LayerValues<Custom>,
drawing: CustomDrawing,
}
#[derive(Default)]
pub(crate) struct CustomDrawing {
host: Option<Arc<dyn CustomLayerHost>>,
frame: Option<CustomLayerFrame>,
used: bool,
updated: bool,
}
impl RenderCustomLayer {
pub(crate) fn new(impl_: Arc<LayerStyle<Custom>>) -> Self {
let host = impl_.extra.get();
let (mut base, values) = LayerValues::new(impl_);
base.passes = RenderPass::Translucent;
let drawing = CustomDrawing { host, frame: None, used: false, updated: false };
RenderCustomLayer { base, values, drawing }
}
}
pub(crate) type EndedHosts = Vec<Arc<dyn CustomLayerHost>>;
pub(crate) fn end_hosts(gpu: &mut dyn Gpu, hosts: EndedHosts) {
if hosts.is_empty() {
return;
}
if let Err(error) = gpu.flush(true) {
log::error!(target: log_target::RENDER, "Waiting for a custom layer's frames failed: {error}");
}
for host in hosts {
host.deinitialize();
}
}
impl CustomDrawing {
fn take_host(&mut self) -> Option<Arc<dyn CustomLayerHost>> {
self.host.take().filter(|_| std::mem::take(&mut self.used))
}
fn lose(&mut self) {
if let Some(host) = self.take_host() {
host.context_lost();
}
}
fn lend_pass(&mut self, gpu: &mut dyn Gpu, parameters: &mut PaintParameters<'_>) {
if parameters.pass_target().is_none() || parameters.pass != RenderPass::Translucent {
return;
}
let (Some(host), Some(frame)) = (&self.host, self.frame) else {
return;
};
let layer_depth = f64::from(parameters.layer_depth());
let lent = parameters.lend_pass(gpu, &mut |pass| {
host.render(&mut CustomLayerRenderParameters { pass, frame: &frame, layer_depth });
});
match lent {
Ok(lent) => {
self.used |= lent;
}
Err(error) => parameters.context.fail(format!("Lending a custom layer the pass failed: {error}")),
}
}
}
impl Drop for CustomDrawing {
fn drop(&mut self) {
self.lose();
}
}
impl LayerDrawing for CustomDrawing {
type Tile = ();
fn tiles(&mut self) -> Option<&mut TileMap<()>> {
None
}
fn visit_groups<'a>(&'a self, visit: &mut dyn FnMut(DrawGroup<'a>)) {
if self.updated {
visit(DrawGroup::Custom);
}
}
fn clear(&mut self) {}
fn begin_frame(&mut self) {
self.updated = true;
}
fn clear_frame(&mut self) {}
fn upload(&mut self, _gpu: &mut dyn Gpu, _context: &mut Context) {}
fn render(&mut self, gpu: &mut dyn Gpu, parameters: &mut PaintParameters<'_>, order: DrawOrder) {
if self.updated {
self.lend_pass(gpu, parameters);
order.step(parameters);
}
}
}
impl TypedLayer for RenderCustomLayer {
type Type = Custom;
type Drawing = CustomDrawing;
fn parts(&self) -> Parts<'_, Self> {
Parts { base: &self.base, values: &self.values, drawing: &self.drawing }
}
fn parts_mut(&mut self) -> PartsMut<'_, Self> {
PartsMut { base: &mut self.base, values: &mut self.values, drawing: &mut self.drawing }
}
fn passes(&self, _evaluated: &EvaluatedLayer<Custom>) -> RenderPass {
RenderPass::Translucent
}
fn style_changed(&mut self, ended: &mut EndedHosts) {
let drawing = &mut self.drawing;
let same = drawing.host.as_ref().is_some_and(|host| self.values.style.extra.is(host));
if !same {
ended.extend(drawing.take_host());
drawing.host = self.values.style.extra.get();
}
}
}
impl RenderLayer for RenderCustomLayer {
fn prerender(&mut self, gpu: &mut dyn Gpu, parameters: &mut PaintParameters<'_>) {
let Some(frame) = parameters.custom_layer_frame else {
return;
};
let drawing = &mut self.drawing;
drawing.frame = Some(frame);
let Some(host) = &drawing.host else { return };
let lent = gpu.lend(&mut |encoder| {
host.prerender(&mut CustomLayerPrerenderParameters { encoder, frame: &frame });
});
match lent {
Ok(()) => drawing.used = true,
Err(error) => parameters.context.fail(format!("Lending a custom layer the commands failed: {error}")),
}
}
fn leave(&mut self, ended: &mut EndedHosts) {
ended.extend(self.drawing.take_host());
}
fn lose_context(&mut self) {
self.drawing.lose();
}
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use mln_style::layer::LayerStyle;
use super::{Custom, CustomLayerHost};
use crate::Registry;
struct Host;
impl CustomLayerHost for Host {}
#[test]
fn the_style_data_of_a_removed_layer_doesnt_keep_its_host() {
let host: Arc<dyn CustomLayerHost> = Arc::new(Host);
let layer = Custom::layer(Registry::with_builtins().style(), "custom", Arc::clone(&host));
let style = LayerStyle::<Custom>::recover(layer.style()).unwrap();
assert!(style.extra.is(&host));
assert!(style.extra.get().is_some());
drop(layer);
assert!(style.extra.get().is_some(), "the caller still holds the host");
drop(host);
assert!(style.extra.get().is_none());
}
}