use std::any::Any;
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use mln_gfx::gpu::{ColorAttachment, DepthStencilAttachment, Gpu, GpuError, LoadOp, PassDesc, TargetFormats};
use mln_gfx::stencil_mode::Test;
use mln_gfx::types::{DepthFunctionType, StencilOpType};
use mln_gfx::{DepthMaskType, DepthMode, ScissorRect, StencilMode};
use mln_map_types::{MapDebugOptions, ProjectionData, TransformState, ViewportMode};
use mln_tile_id::UnwrappedTileID;
use mln_util::identity::SimpleIdentity;
use mln_util::logging::{Event, Log};
use mln_util::mat4::Mat4;
use mln_util::range::Range;
use mln_util::size::Size;
use mln_vec_map::VecMap;
use crate::clip_masks::ClipMasks;
use crate::gfx::context::Context;
use crate::layer_composite::LayerComposite;
use crate::line_atlas::LineAtlas;
use crate::pattern_atlas::PatternAtlas;
use crate::render_pass::RenderPass;
use crate::render_static_data::RenderStaticData;
pub(crate) struct TransformParameters {
pub(crate) proj_matrix: Mat4,
pub(crate) aligned_proj_matrix: Mat4,
pub(crate) near_clipped_proj_matrix: Mat4,
pub(crate) near_clipped_near_z: f64,
pub(crate) state: TransformState,
}
impl TransformParameters {
pub(crate) fn new(state: &TransformState) -> Self {
let state = state.clone();
let proj_matrix = state.get_proj_matrix(1, false);
let aligned_proj_matrix = state.get_proj_matrix(1, true);
let near_z = (0.1 * f64::from(state.get_camera_to_center_distance())) as u16;
let near_clipped_proj_matrix = state.get_proj_matrix(near_z, false);
TransformParameters {
proj_matrix,
aligned_proj_matrix,
near_clipped_proj_matrix,
near_clipped_near_z: f64::from(near_z),
state,
}
}
}
#[derive(Clone, Copy)]
pub(crate) struct OpenPass {
pub(crate) label: &'static str,
pub(crate) color: Option<ColorAttachment>,
pub(crate) depth_stencil: Option<DepthStencilAttachment>,
pub(crate) size: Size,
pub(crate) targets: TargetFormats,
}
impl OpenPass {
fn loading(&self, stencil: LoadOp<u32>) -> OpenPass {
OpenPass {
color: self.color.map(|color| ColorAttachment { load: LoadOp::Load, ..color }),
depth_stencil: self.depth_stencil.map(|depth_stencil| DepthStencilAttachment {
depth: LoadOp::Load,
stencil,
..depth_stencil
}),
..*self
}
}
fn desc(&self) -> PassDesc<'static> {
PassDesc { label: self.label, color: self.color, depth_stencil: self.depth_stencil }
}
}
pub(crate) struct PaintParameters<'a> {
pub(crate) context: &'a Context,
open_pass: Cell<Option<OpenPass>>,
pub(crate) transform_params: &'a TransformParameters,
pub(crate) state: &'a TransformState,
pub(crate) evaluated_light: crate::render_light::EvaluatedLight,
pub(crate) static_data: &'a RenderStaticData,
pub(crate) line_atlas: Rc<RefCell<LineAtlas>>,
pub(crate) pattern_atlas: Rc<RefCell<PatternAtlas>>,
pub(crate) pass: RenderPass,
pub(crate) debug_options: MapDebugOptions,
pub(crate) pixel_ratio: f32,
pub(crate) renderable_size: Size,
pub(crate) pixels_to_gl_units: [f32; 2],
pub(crate) clip_masks: ClipMasks,
pub(crate) layer_composite: LayerComposite,
tile_clipping_mask_ids: VecMap<UnwrappedTileID, i32>,
next_stencil_id: i32,
pub(crate) current_layer: u32,
pub(crate) depth_range_size: f32,
pub(crate) opaque_pass_cutoff: u32,
pub(crate) symbol_fade_change: f32,
pub(crate) scissor_rect: ScissorRect,
pub(crate) custom_layer_frame: Option<mln_style::layers::CustomLayerFrame>,
}
impl<'a> PaintParameters<'a> {
pub(crate) const NUM_SUBLAYERS: i32 = 3;
pub(crate) const DEPTH_EPSILON: f32 = 1.0 / (1 << 16) as f32;
pub(crate) const MAX_STENCIL_VALUE: i32 = 255;
#[expect(clippy::too_many_arguments, reason = "each argument is a field of the paint parameters")]
pub(crate) fn new(
context: &'a Context,
pixel_ratio: f32,
debug_options: MapDebugOptions,
transform_params: &'a TransformParameters,
static_data: &'a RenderStaticData,
pattern_atlas: Rc<RefCell<PatternAtlas>>,
renderable_size: Size,
scissor_rect: ScissorRect,
) -> Self {
let state = &transform_params.state;
let mut pixels_to_gl_units = [2.0f32 / state.get_size().width as f32, -2.0f32 / state.get_size().height as f32];
if state.get_viewport_mode() == ViewportMode::FlippedY {
pixels_to_gl_units[1] *= -1.0;
}
PaintParameters {
context,
open_pass: Cell::new(None),
transform_params,
state,
static_data,
evaluated_light: crate::render_light::EvaluatedLight::default(),
line_atlas: Rc::new(RefCell::new(LineAtlas::new())),
pattern_atlas,
pass: RenderPass::Opaque,
debug_options,
pixel_ratio,
renderable_size,
pixels_to_gl_units,
clip_masks: ClipMasks::default(),
layer_composite: LayerComposite::default(),
tile_clipping_mask_ids: VecMap::new(),
next_stencil_id: 1,
current_layer: 0,
depth_range_size: 1.0,
opaque_pass_cutoff: 0,
symbol_fade_change: 0.0,
scissor_rect,
custom_layer_frame: None,
}
}
pub(crate) fn pass_target(&self) -> Option<(Size, TargetFormats)> {
self.open_pass.get().map(|pass| (pass.size, pass.targets))
}
pub(crate) fn begin_pass(&self, gpu: &mut dyn Gpu, pass: OpenPass) -> Result<(), GpuError> {
gpu.begin_pass(&pass.desc())?;
self.open_pass.set(Some(pass));
Ok(())
}
pub(crate) fn end_pass(&self, gpu: &mut dyn Gpu) -> Result<(), GpuError> {
match self.open_pass.take() {
Some(_) => gpu.end_pass(),
None => Ok(()),
}
}
fn restart_pass(&self, gpu: &mut dyn Gpu, stencil: LoadOp<u32>) {
let Some(pass) = self.open_pass.get() else {
return;
};
let restarted = self.end_pass(gpu).and_then(|()| self.begin_pass(gpu, pass.loading(stencil)));
if let Err(error) = restarted {
Log::error(Event::Render, format!("Restarting the {} pass failed: {error}", pass.label));
}
}
pub(crate) fn draw_composited(
&mut self,
gpu: &mut dyn Gpu,
group: SimpleIdentity,
draw: impl FnOnce(&mut dyn Gpu, &mut Self),
) {
let Some((frame, composite)) =
self.open_pass.get().zip(self.layer_composite.pass()).filter(|_| self.layer_composite.composites(group))
else {
return draw(gpu, self);
};
let mut layer_composite = std::mem::take(&mut self.layer_composite);
let mut drawn = self.end_pass(gpu);
if drawn.is_ok()
&& let Some(backdrop) = layer_composite.backdrop_pass(group)
{
drawn = self
.begin_pass(gpu, backdrop)
.map(|()| layer_composite.copy_frame(gpu, self))
.and_then(|()| self.end_pass(gpu));
}
drawn = drawn.and_then(|()| self.begin_pass(gpu, composite));
if let Err(error) = &drawn {
Log::error(Event::Render, format!("Beginning the layer composite's pass failed: {error}"));
} else {
let tile_clipping_mask_ids = std::mem::take(&mut self.tile_clipping_mask_ids);
let next_stencil_id = std::mem::replace(&mut self.next_stencil_id, 1);
draw(gpu, self);
self.tile_clipping_mask_ids = tile_clipping_mask_ids;
self.next_stencil_id = next_stencil_id;
if let Err(error) = self.end_pass(gpu) {
Log::error(Event::Render, format!("Ending the layer composite's pass failed: {error}"));
}
}
if let Err(error) = self.begin_pass(gpu, frame.loading(LoadOp::Load)) {
Log::error(Event::Render, format!("Resuming the {} pass failed: {error}", frame.label));
} else if drawn.is_ok() {
layer_composite.draw(gpu, self, group);
}
self.layer_composite = layer_composite;
}
pub(crate) fn present_frame(&mut self, gpu: &mut dyn Gpu, present: OpenPass) {
if self.layer_composite.frame_texture().is_none() {
return;
}
if let Err(error) = self.end_pass(gpu).and_then(|()| self.begin_pass(gpu, present)) {
Log::error(Event::Render, format!("Beginning the frame's copy failed: {error}"));
return;
}
let mut layer_composite = std::mem::take(&mut self.layer_composite);
layer_composite.copy_frame(gpu, self);
self.layer_composite = layer_composite;
}
pub(crate) fn lend_pass(&self, gpu: &mut dyn Gpu, f: &mut dyn FnMut(&mut dyn Any)) -> Result<bool, GpuError> {
if self.open_pass.get().is_none() {
return Ok(false);
}
gpu.lend(f).map(|()| true)
}
#[must_use]
pub(crate) fn projection_data_for_tile(&self, tile_id: &UnwrappedTileID, aligned: bool) -> ProjectionData {
self.state.get_projection_data_with(
tile_id,
if aligned { &self.transform_params.aligned_proj_matrix } else { &self.transform_params.proj_matrix },
)
}
#[must_use]
pub(crate) fn depth_mode_for_sublayer(&self, n: u8, mask: DepthMaskType) -> DepthMode {
if self.current_layer < self.opaque_pass_cutoff || self.state.is_globe_rendering() {
return DepthMode::disabled();
}
let steps =
(1u32.wrapping_add(self.current_layer)).wrapping_mul(Self::NUM_SUBLAYERS as u32).wrapping_add(u32::from(n));
let depth = self.depth_range_size + steps as f32 * Self::DEPTH_EPSILON;
DepthMode { func: DepthFunctionType::LessEqual, mask, range: Range::new(depth, depth) }
}
#[must_use]
pub(crate) fn layer_depth(&self) -> f32 {
let steps = (1u32.wrapping_add(self.current_layer)).wrapping_mul(Self::NUM_SUBLAYERS as u32);
self.depth_range_size + steps as f32 * Self::DEPTH_EPSILON
}
#[must_use]
pub(crate) fn depth_mode_for_3d(&self, mask: DepthMaskType) -> DepthMode {
DepthMode { func: DepthFunctionType::LessEqual, mask, range: Range::new(0.0, self.depth_range_size) }
}
pub(crate) fn clear_stencil(&mut self, gpu: &mut dyn Gpu) {
self.next_stencil_id = 1;
self.tile_clipping_mask_ids.clear();
match self.stencil_clear_tile() {
Some(tile) => self.draw_clip_masks(gpu, &[(tile, 0)]),
None => self.restart_pass(gpu, LoadOp::Clear(0)),
}
self.context.rendering_stats().stencil_clears += 1;
}
#[must_use]
pub(crate) fn stencil_clear_tile(&self) -> Option<UnwrappedTileID> {
(!self.context.caps().clear_stencil_with_pass).then(|| UnwrappedTileID::new(0, 0, 0))
}
fn draw_clip_masks(&mut self, gpu: &mut dyn Gpu, masks: &[(UnwrappedTileID, i32)]) {
let mut clip_masks = std::mem::take(&mut self.clip_masks);
clip_masks.draw(gpu, masks, self);
self.clip_masks = clip_masks;
}
pub(crate) fn render_tile_clipping_masks(&mut self, gpu: &mut dyn Gpu, tile_ids: &[UnwrappedTileID]) {
let covered = self.tile_clipping_mask_ids.len() == tile_ids.len()
&& self.tile_clipping_mask_ids.keys().zip(tile_ids.iter()).all(|(a, b)| a == b);
if covered || self.pass_target().is_none() {
return;
}
self.tile_clipping_mask_ids.clear();
if self.next_stencil_id as usize + tile_ids.len() > Self::MAX_STENCIL_VALUE as usize {
self.clear_stencil(gpu);
}
let mut masks = Vec::with_capacity(tile_ids.len());
for tile_id in tile_ids {
if self.tile_clipping_mask_ids.contains_key(tile_id) {
continue;
}
self.tile_clipping_mask_ids.insert(*tile_id, self.next_stencil_id);
masks.push((*tile_id, self.next_stencil_id));
self.next_stencil_id += 1;
}
if !masks.is_empty() {
self.draw_clip_masks(gpu, &masks);
self.context.rendering_stats().stencil_updates += 1;
}
}
#[must_use]
pub(crate) fn stencil_mode_for_clipping(&self, tile_id: &UnwrappedTileID) -> StencilMode {
let it = self.tile_clipping_mask_ids.get(tile_id);
debug_assert!(it.is_some());
let id = it.copied().unwrap_or(0b0000_0000);
StencilMode {
test: Test::Equal { mask: 0b1111_1111 },
ref_: id,
mask: 0b0000_0000,
fail: StencilOpType::Keep,
depth_fail: StencilOpType::Keep,
pass: StencilOpType::Replace,
}
}
pub(crate) fn stencil_mode_for_3d(&mut self, gpu: &mut dyn Gpu) -> StencilMode {
if self.next_stencil_id + 1 > Self::MAX_STENCIL_VALUE {
self.clear_stencil(gpu);
}
self.tile_clipping_mask_ids.clear();
let id = self.next_stencil_id;
self.next_stencil_id += 1;
StencilMode {
test: Test::NotEqual { mask: 0b1111_1111 },
ref_: id,
mask: 0b1111_1111,
fail: StencilOpType::Keep,
depth_fail: StencilOpType::Keep,
pass: StencilOpType::Replace,
}
}
pub(crate) fn stencil_modes_for_3d(&mut self, gpu: &mut dyn Gpu, modes: &mut [StencilMode]) -> bool {
if modes.len() >= Self::MAX_STENCIL_VALUE as usize {
return false;
}
if self.next_stencil_id as usize + modes.len() > Self::MAX_STENCIL_VALUE as usize {
self.clear_stencil(gpu);
}
for mode in modes.iter_mut() {
*mode = self.stencil_mode_for_3d(gpu);
}
true
}
}