use std::sync::Arc;
use mln_gfx::shaders::hillshade_layer_ubo::{
HillshadeDrawableUBO, HillshadeEvaluatedPropsUBO, HillshadeTilePropsUBO, MAX_ILLUMINATION_SOURCES,
};
use mln_gfx::shaders::layer_ubo::ProjectionUBO;
use mln_gfx::shaders::shader_defines::{
ID_HILLSHADE_DRAWABLE_UBO, ID_HILLSHADE_EVALUATED_PROPS_UBO, ID_HILLSHADE_TILE_PROPS_UBO,
};
use mln_math::deg2radf;
use mln_style::layers::Hillshade;
use mln_style::layers::hillshade_layer_properties::HillshadePaintProperties;
use mln_style_types::{HillshadeIlluminationAnchorType, HillshadeMethodType, TranslateAnchorType};
use mln_tile_id::UnwrappedTileID;
use mln_util::Color;
use mln_util::geo::LatLng;
use super::{cast_matrix, check_tweak_drawable_ptr};
use crate::gfx::uniform_buffer::UniformBufferPtr;
use crate::layer_group::LayerGroup;
use crate::layer_tweaker::{LayerTweaker, LayerTweakerBase, get_projection_data, to_projection_ubo};
use crate::layer_type::{ErasedEvaluatedLayer, evaluated};
use crate::paint_parameters::PaintParameters;
struct IlluminationProperties {
direction_radians: Vec<f32>,
altitude_radians: Vec<f32>,
shadow_colors: Vec<Color>,
highlight_colors: Vec<Color>,
}
impl IlluminationProperties {
fn num_sources(&self) -> usize {
self.direction_radians.len()
}
}
fn pad_array<T: Clone + Default>(arr: &mut Vec<T>, max_length: usize) {
let last = arr.last().cloned().unwrap_or_default();
let length = max_length.max(arr.len()).max(1);
arr.resize(length, last);
}
fn get_illumination_properties(evaluated: &HillshadePaintProperties::PossiblyEvaluated) -> IlluminationProperties {
let mut directions: Vec<f32> = evaluated.hillshade_illumination_direction.clone().uniform().clone();
let mut altitudes: Vec<f32> = evaluated.hillshade_illumination_altitude.clone().uniform().clone();
let mut highlights: Vec<Color> = evaluated.hillshade_highlight_color.clone().uniform().clone();
let mut shadows: Vec<Color> = evaluated.hillshade_shadow_color.clone().uniform().clone();
let mut max_length = directions.len().max(altitudes.len()).max(highlights.len()).max(shadows.len());
max_length = max_length.min(MAX_ILLUMINATION_SOURCES);
pad_array(&mut directions, max_length);
pad_array(&mut altitudes, max_length);
pad_array(&mut highlights, max_length);
pad_array(&mut shadows, max_length);
IlluminationProperties {
direction_radians: directions.iter().map(|°| deg2radf(deg)).collect(),
altitude_radians: altitudes.iter().map(|°| deg2radf(deg)).collect(),
shadow_colors: shadows,
highlight_colors: highlights,
}
}
fn pack_evaluated_props(illumination: &IlluminationProperties, accent_color: &Color) -> HillshadeEvaluatedPropsUBO {
let mut ubo = HillshadeEvaluatedPropsUBO {
accent: [accent_color.r, accent_color.g, accent_color.b, accent_color.a],
..HillshadeEvaluatedPropsUBO::default()
};
for (i, &altitude) in illumination.altitude_radians.iter().take(4).enumerate() {
ubo.altitudes[i] = altitude;
}
for (i, &azimuth) in illumination.direction_radians.iter().take(4).enumerate() {
ubo.azimuths[i] = azimuth;
}
for (i, color) in illumination.shadow_colors.iter().take(4).enumerate() {
ubo.shadows[i * 4] = color.r;
ubo.shadows[i * 4 + 1] = color.g;
ubo.shadows[i * 4 + 2] = color.b;
ubo.shadows[i * 4 + 3] = color.a;
}
for (i, color) in illumination.highlight_colors.iter().take(4).enumerate() {
ubo.highlights[i * 4] = color.r;
ubo.highlights[i * 4 + 1] = color.g;
ubo.highlights[i * 4 + 2] = color.b;
ubo.highlights[i * 4 + 3] = color.a;
}
ubo
}
fn method_to_int(method: HillshadeMethodType) -> i32 {
method as i32
}
pub(crate) fn get_lat_range(id: &UnwrappedTileID) -> [f32; 2] {
let latlng0 = LatLng::from_unwrapped_tile(id.canonical.z, id.canonical.x, id.canonical.y, id.wrap);
let below = UnwrappedTileID::new(id.canonical.z, i64::from(id.canonical.x), i64::from(id.canonical.y) + 1);
let latlng1 = LatLng::from_unwrapped_tile(below.canonical.z, below.canonical.x, below.canonical.y, below.wrap);
[latlng0.latitude() as f32, latlng1.latitude() as f32]
}
pub(crate) struct HillshadeLayerTweaker {
base: LayerTweakerBase,
evaluated_props_uniform_buffer: Option<UniformBufferPtr>,
drawable_uniform_buffer: Option<UniformBufferPtr>,
tile_props_uniform_buffer: Option<UniformBufferPtr>,
}
impl HillshadeLayerTweaker {
pub(crate) fn new(id: String, properties: Arc<dyn ErasedEvaluatedLayer>) -> Self {
HillshadeLayerTweaker {
base: LayerTweakerBase::new(id, Some(properties)),
evaluated_props_uniform_buffer: None,
drawable_uniform_buffer: None,
tile_props_uniform_buffer: None,
}
}
}
impl LayerTweaker for HillshadeLayerTweaker {
fn base_mut(&mut self) -> &mut LayerTweakerBase {
&mut self.base
}
fn execute(&mut self, layer_group: &mut LayerGroup, parameters: &PaintParameters<'_>) {
if layer_group.empty() {
return;
}
let Some(properties) = self.base.evaluated_properties.clone() else {
return;
};
let evaluated = &evaluated::<Hillshade>(&properties).paint;
let mut illumination = get_illumination_properties(evaluated);
if *evaluated.hillshade_illumination_anchor.uniform() == HillshadeIlluminationAnchorType::Viewport {
let bearing = parameters.state.get_bearing() as f32;
for azimuth in &mut illumination.direction_radians {
*azimuth -= bearing;
}
}
let context = parameters.context;
if self.evaluated_props_uniform_buffer.is_none() || self.base.properties_updated {
let evaluated_props_ubo = pack_evaluated_props(&illumination, evaluated.hillshade_accent_color.uniform());
context.write_uniform_buffer_pod(&mut self.evaluated_props_uniform_buffer, &evaluated_props_ubo);
self.base.properties_updated = false;
}
layer_group
.mutable_uniform_buffers()
.set(ID_HILLSHADE_EVALUATED_PROPS_UBO, self.evaluated_props_uniform_buffer.clone());
let mut i: u32 = 0;
let count = layer_group.drawable_count();
let mut drawable_ubo_vector = vec![HillshadeDrawableUBO::default(); count];
let mut projection_ubo_vector = vec![ProjectionUBO::default(); count];
let mut tile_props_ubo_vector = vec![HillshadeTilePropsUBO::default(); count];
let exaggeration = &evaluated.hillshade_exaggeration;
let method = method_to_int(*evaluated.hillshade_method.uniform());
let num_lights = illumination.num_sources() as i32;
let self_ptr: *const Self = self;
layer_group.visit_drawables(|drawable| {
let Some(tile_id) = drawable.tile_id else {
return;
};
if !check_tweak_drawable_ptr(drawable, self_ptr) {
return;
}
let tile_id = tile_id.to_unwrapped();
let projection = get_projection_data(
&tile_id,
parameters,
[0.0, 0.0],
TranslateAnchorType::Viewport,
false,
false,
drawable,
true,
);
let matrix = projection.fallback_matrix;
projection_ubo_vector[i as usize] = to_projection_ubo(&projection);
drawable_ubo_vector[i as usize] = HillshadeDrawableUBO { matrix: cast_matrix(&matrix) };
tile_props_ubo_vector[i as usize] = HillshadeTilePropsUBO {
latrange: get_lat_range(&tile_id),
exaggeration: *exaggeration.uniform(),
method,
num_lights,
pad0: 0.0,
pad1: 0.0,
pad2: 0.0,
};
drawable.ubo_index = i;
i += 1;
});
let bytes: &[u8] = bytemuck::cast_slice(&drawable_ubo_vector);
context.write_storage_buffer(&mut self.drawable_uniform_buffer, bytes);
let bytes: &[u8] = bytemuck::cast_slice(&tile_props_ubo_vector);
context.write_storage_buffer(&mut self.tile_props_uniform_buffer, bytes);
let layer_uniforms = layer_group.mutable_uniform_buffers();
layer_uniforms.set(ID_HILLSHADE_DRAWABLE_UBO, self.drawable_uniform_buffer.clone());
layer_uniforms.set(ID_HILLSHADE_TILE_PROPS_UBO, self.tile_props_uniform_buffer.clone());
self.base.upload_projection_ubos(layer_uniforms, &projection_ubo_vector, context);
}
}