use std::cmp::Reverse;
use std::collections::BTreeMap;
use std::num::NonZeroU32;
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::{Arc, OnceLock};
use glam::Vec2;
use mln_gfx::shaders::segment::SegmentBase;
use mln_style::StyleValue as _;
use mln_style::expression::EvaluationContext;
use mln_style::layers::Symbol;
use mln_style::layers::symbol_layer::SymbolLayerPaintPropertyOverrides;
use mln_style::layers::symbol_layer_properties::{SymbolLayoutProperties, SymbolPaintProperties};
use mln_style::property_expression::PropertyExpression;
use mln_style::property_value::PropertyValue;
use mln_style_types::TextWritingModeType;
use mln_style_types::image::ImagePositions;
use mln_text::glyph::WritingModeType;
use mln_tile::TileLayer;
use mln_tile_id::geometry_tile_data::{GeometryCoordinate, GeometryCoordinates, GeometryTileFeature};
use mln_util::Color;
use mln_util::range::Range;
use mln_util::serialization::payload::pod;
use mln_vec_map::VecMap;
use parking_lot::{Mutex, MutexGuard, RwLock};
use crate::bucket::{Bucket, BucketBase, FeatureStates};
use crate::bucket_geometry::GeometryVec;
use crate::gfx::context::Context;
use crate::layer_type::EvaluatedLayer;
use crate::layout::symbol_instance::{SymbolInstance, SymbolInstancePools};
use crate::paint_property_binder::PaintPropertyBinder;
use crate::util::pool::PoolRange;
crate::paint_property_binders!(
pub struct SymbolIconBinders for SymbolPaintProperties::PossiblyEvaluated {
icon_opacity => PaintPropertyBinder<f32>,
icon_color => PaintPropertyBinder<Color>,
icon_halo_color => PaintPropertyBinder<Color>,
icon_halo_width => PaintPropertyBinder<f32>,
icon_halo_blur => PaintPropertyBinder<f32>,
}
);
crate::paint_property_binders!(
pub struct SymbolTextBinders for SymbolPaintProperties::PossiblyEvaluated {
text_opacity => PaintPropertyBinder<f32>,
text_color => PaintPropertyBinder<Color>,
text_halo_color => PaintPropertyBinder<Color>,
text_halo_width => PaintPropertyBinder<f32>,
text_halo_blur => PaintPropertyBinder<f32>,
}
);
#[derive(Clone, Copy, Debug, Default, PartialEq, bytemuck::Pod, bytemuck::Zeroable)]
#[repr(C)]
pub(crate) struct SymbolLayoutVertex {
pub(crate) a1: [i16; 4],
pub(crate) a2: [u16; 4],
pub(crate) a3: [i16; 4],
pub(crate) a4: [u16; 2],
pub(crate) a5: f32,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, bytemuck::Pod, bytemuck::Zeroable)]
#[repr(C)]
pub(crate) struct SymbolDynamicLayoutVertex {
pub(crate) a1: [f32; 3],
}
#[derive(Clone, Copy, Debug, Default, PartialEq, bytemuck::Pod, bytemuck::Zeroable)]
#[repr(C)]
pub(crate) struct SymbolOpacityVertex {
pub(crate) a1: [f32; 1],
}
#[derive(Clone, Copy, Debug, Default, PartialEq, bytemuck::Pod, bytemuck::Zeroable)]
#[repr(C)]
pub(crate) struct CollisionBoxLayoutVertex {
pub(crate) a1: [i16; 2],
pub(crate) a2: [i16; 2],
pub(crate) a3: [i16; 2],
pub(crate) a4: f32,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, bytemuck::Pod, bytemuck::Zeroable)]
#[repr(C)]
pub(crate) struct CollisionBoxDynamicVertex {
pub(crate) a1: [u16; 2],
pub(crate) a2: [f32; 2],
}
pub(crate) const MAX_GLYPH_ICON_SIZE: u16 = 255;
pub(crate) const SIZE_PACK_FACTOR: u16 = 128;
pub(crate) const MAX_PACKED_SIZE: u16 = MAX_GLYPH_ICON_SIZE * SIZE_PACK_FACTOR;
#[derive(Clone, Copy, Debug, PartialEq, mln_wire::Wire)]
pub(crate) struct SortKeyRange {
pub(crate) sort_key: f32,
pub(crate) start: usize,
pub(crate) end: usize,
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub(crate) struct ZoomEvaluatedSize {
pub(crate) is_zoom_constant: bool,
pub(crate) is_feature_constant: bool,
pub(crate) size_t: f32,
pub(crate) size: f32,
pub(crate) layout_size: f32,
}
#[derive(Debug, mln_wire::Wire)]
pub(crate) enum SymbolSizeBinder {
Constant {
layout_size: f32,
covering_ranges: Option<(Range<f32>, Range<f32>)>,
expression: Option<PropertyExpression<f32>>,
},
SourceFunction {
expression: PropertyExpression<f32>,
default_value: f32,
},
CompositeFunction {
expression: PropertyExpression<f32>,
default_value: f32,
layout_zoom: f32,
covering_zoom_stops: Range<f32>,
},
}
impl SymbolSizeBinder {
#[must_use]
pub(crate) fn create(tile_zoom: f32, size_property: &PropertyValue<f32>, default_value: f32) -> Self {
if size_property.is_undefined() {
return SymbolSizeBinder::Constant { layout_size: default_value, covering_ranges: None, expression: None };
}
if size_property.is_constant() {
return SymbolSizeBinder::Constant {
layout_size: *size_property.as_constant(),
covering_ranges: None,
expression: None,
};
}
let expression = size_property.as_expression().clone();
if expression.is_feature_constant() {
let layout_size = expression.evaluate(&EvaluationContext::new(tile_zoom + 1.0), 0.0);
let covering_ranges = if expression.is_zoom_constant() {
None
} else {
let zoom_levels = expression.get_covering_stops(tile_zoom, tile_zoom + 1.0);
Some((
zoom_levels,
Range {
min: expression.evaluate(&EvaluationContext::new(zoom_levels.min), 0.0),
max: expression.evaluate(&EvaluationContext::new(zoom_levels.max), 0.0),
},
))
};
SymbolSizeBinder::Constant { layout_size, covering_ranges, expression: Some(expression) }
} else if expression.is_zoom_constant() {
SymbolSizeBinder::SourceFunction { expression, default_value }
} else {
let covering_zoom_stops = expression.get_covering_stops(tile_zoom, tile_zoom + 1.0);
SymbolSizeBinder::CompositeFunction {
expression,
default_value,
layout_zoom: tile_zoom + 1.0,
covering_zoom_stops,
}
}
}
pub(crate) fn get_vertex_size_data(&self, feature: &dyn GeometryTileFeature) -> Range<f32> {
match self {
SymbolSizeBinder::Constant { .. } => Range { min: 0.0, max: 0.0 },
SymbolSizeBinder::SourceFunction { expression, default_value } => {
let size = expression.evaluate(&EvaluationContext::from_feature(Some(feature)), *default_value);
Range { min: size, max: size }
}
SymbolSizeBinder::CompositeFunction { expression, default_value, covering_zoom_stops, .. } => Range {
min: expression.evaluate(
&EvaluationContext::with_zoom_feature(covering_zoom_stops.min, Some(feature)),
*default_value,
),
max: expression.evaluate(
&EvaluationContext::with_zoom_feature(covering_zoom_stops.max, Some(feature)),
*default_value,
),
},
}
}
#[must_use]
pub(crate) fn evaluate_for_zoom(&self, current_zoom: f32) -> ZoomEvaluatedSize {
let unused = 0.0_f32;
match self {
SymbolSizeBinder::Constant { layout_size, covering_ranges, expression } => {
let mut size = *layout_size;
let is_zoom_constant = !(covering_ranges.is_some() || expression.is_some());
if let (Some((zoom_levels, size_levels)), Some(expression)) = (covering_ranges, expression) {
let t = mln_math::clamp_f32(expression.interpolation_factor(*zoom_levels, current_zoom), 0.0, 1.0);
size = size_levels.min + t * (size_levels.max - size_levels.min);
} else if let Some(expression) = expression {
size = expression.evaluate(&EvaluationContext::new(current_zoom), 0.0);
}
ZoomEvaluatedSize {
is_zoom_constant,
is_feature_constant: true,
size_t: unused,
size,
layout_size: *layout_size,
}
}
SymbolSizeBinder::SourceFunction { .. } => ZoomEvaluatedSize {
is_zoom_constant: true,
is_feature_constant: false,
size_t: unused,
size: unused,
layout_size: unused,
},
SymbolSizeBinder::CompositeFunction { expression, covering_zoom_stops, .. } => {
let size_interpolation_t =
mln_math::clamp_f32(expression.interpolation_factor(*covering_zoom_stops, current_zoom), 0.0, 1.0);
ZoomEvaluatedSize {
is_zoom_constant: false,
is_feature_constant: false,
size_t: size_interpolation_t,
size: unused,
layout_size: unused,
}
}
}
}
}
#[derive(Clone, Debug, mln_wire::Wire)]
pub(crate) struct PlacedSymbol {
pub(crate) anchor_point: Vec2,
pub(crate) segment: usize,
pub(crate) lower_size: f32,
pub(crate) upper_size: f32,
pub(crate) line_offset: [f32; 2],
pub(crate) writing_modes: WritingModeType,
pub(crate) line: PoolRange,
pub(crate) tile_distances: PoolRange,
pub(crate) glyph_offsets: PoolRange,
pub(crate) hidden: bool,
pub(crate) start_index: usize,
pub(crate) cross_tile_id: Option<NonZeroU32>,
pub(crate) placed_orientation: Option<TextWritingModeType>,
pub(crate) angle: f32,
pub(crate) placed_icon_index: Option<usize>,
pub(crate) height_offset: f32,
}
impl PlacedSymbol {
#[expect(clippy::too_many_arguments, reason = "each argument is a field of the placed symbol")]
#[must_use]
pub(crate) fn new(
anchor_point: Vec2,
segment: usize,
lower_size: f32,
upper_size: f32,
line_offset: [f32; 2],
writing_modes: WritingModeType,
line: PoolRange,
tile_distances: PoolRange,
glyph_offsets: PoolRange,
placed_icon_index: Option<usize>,
) -> Self {
PlacedSymbol {
anchor_point,
segment,
lower_size,
upper_size,
line_offset,
writing_modes,
line,
tile_distances,
glyph_offsets,
hidden: false,
start_index: 0,
cross_tile_id: None,
placed_orientation: None,
angle: 0.0,
placed_icon_index,
height_offset: 0.0,
}
}
}
#[derive(Debug, Default, mln_wire::Wire)]
pub(crate) struct Buffer {
pub(crate) attribute_data: GeometryVec<SymbolLayoutVertex>,
#[wire(with = "pod")]
pub(crate) dynamic_attribute_data: Vec<SymbolDynamicLayoutVertex>,
#[wire(skip)]
pub(crate) layer_dynamic_attribute_data: BTreeMap<String, Vec<SymbolDynamicLayoutVertex>>,
#[wire(with = "pod")]
pub(crate) opacity_attribute_data: Vec<SymbolOpacityVertex>,
#[wire(with = "pod")]
pub(crate) triangles: Vec<u16>,
pub(crate) segments: Vec<SegmentBase>,
pub(crate) placed_symbols: Vec<PlacedSymbol>,
pub(crate) pools: PlacedSymbolPools,
pub(crate) modified: u64,
}
#[derive(Debug, Default, mln_wire::Wire)]
pub(crate) struct PlacedSymbolPools {
pub(crate) lines: GeometryCoordinates,
#[wire(with = "pod")]
pub(crate) tile_distances: Vec<f32>,
#[wire(with = "pod")]
pub(crate) glyph_offsets: Vec<f32>,
}
impl PlacedSymbolPools {
pub(crate) fn line(&self, symbol: &PlacedSymbol) -> &[GeometryCoordinate] {
symbol.line.of(&self.lines)
}
pub(crate) fn tile_distances(&self, symbol: &PlacedSymbol) -> &[f32] {
symbol.tile_distances.of(&self.tile_distances)
}
pub(crate) fn glyph_offsets(&self, symbol: &PlacedSymbol) -> &[f32] {
symbol.glyph_offsets.of(&self.glyph_offsets)
}
}
impl Buffer {
pub(crate) fn update_modified(&mut self) {
self.modified += 1;
}
pub(crate) fn dynamic_attribute_data_for(&self, layer_id: &str) -> &Vec<SymbolDynamicLayoutVertex> {
self.layer_dynamic_attribute_data.get(layer_id).unwrap_or(&self.dynamic_attribute_data)
}
pub(crate) fn positions_and_symbols(
&mut self,
layer_id: Option<&str>,
) -> (&mut Vec<SymbolDynamicLayoutVertex>, &[PlacedSymbol], &PlacedSymbolPools) {
let positions = match layer_id {
None => &mut self.dynamic_attribute_data,
Some(layer_id) => self.layer_dynamic_attribute_data.entry(layer_id.to_owned()).or_default(),
};
(positions, &self.placed_symbols, &self.pools)
}
pub(crate) fn has_visible_vertices(&self, offset: usize, count: usize) -> bool {
let Some(range) = offset.checked_add(count).and_then(|end| self.opacity_attribute_data.get(offset..end)) else {
return true;
};
range.iter().any(|vertex| vertex.a1[0] != 0.0)
}
pub(crate) fn segment_has_visible_vertices(&self, segment: Option<usize>) -> bool {
match segment {
Some(i) => self
.segments
.get(i)
.is_none_or(|segment| self.has_visible_vertices(segment.vertex_offset, segment.vertex_length)),
None => self.has_visible_vertices(0, self.attribute_data.len()),
}
}
}
#[derive(Debug, Default, mln_wire::Wire)]
pub(crate) struct CollisionBuffer {
#[wire(with = "pod")]
pub(crate) vertices: Vec<CollisionBoxLayoutVertex>,
#[wire(with = "pod")]
pub(crate) dynamic_vertices: Vec<CollisionBoxDynamicVertex>,
pub(crate) segments: Vec<SegmentBase>,
#[wire(with = "pod")]
pub(crate) indices: Vec<u16>,
}
#[derive(Debug, mln_wire::Wire)]
pub(crate) struct PaintProperties {
pub(crate) icon_binders: SymbolIconBinders,
pub(crate) text_binders: SymbolTextBinders,
}
#[derive(Debug, Default, mln_wire::Wire)]
pub(crate) struct SymbolBucketState {
pub(crate) sorted_angle: f32,
pub(crate) just_reloaded: bool,
pub(crate) has_variable_placement: bool,
pub(crate) has_uninitialized_symbols: bool,
pub(crate) dynamic_text_translation: Vec2,
pub(crate) dynamic_icon_translation: Vec2,
pub(crate) symbol_instances: Vec<SymbolInstance>,
pub(crate) symbol_instance_pools: SymbolInstancePools,
pub(crate) text: Buffer,
pub(crate) icon: Buffer,
pub(crate) sdf_icon: Buffer,
pub(crate) icon_collision_box: Option<CollisionBuffer>,
pub(crate) text_collision_box: Option<CollisionBuffer>,
pub(crate) icon_collision_circle: Option<CollisionBuffer>,
pub(crate) text_collision_circle: Option<CollisionBuffer>,
pub(crate) feature_sort_order: Option<Arc<Vec<usize>>>,
}
impl SymbolBucketState {
pub(crate) fn has_layer_dynamic_attribute_data(&self, layer_id: &str) -> bool {
self.text.layer_dynamic_attribute_data.contains_key(layer_id)
|| self.icon.layer_dynamic_attribute_data.contains_key(layer_id)
|| self.sdf_icon.layer_dynamic_attribute_data.contains_key(layer_id)
}
}
static MAX_BUCKET_INSTANCE_ID: AtomicU32 = AtomicU32::new(0);
fn next_bucket_instance_id() -> u32 {
MAX_BUCKET_INSTANCE_ID.fetch_add(1, Ordering::SeqCst) + 1
}
#[derive(mln_wire::Wire)]
pub(crate) struct SymbolBucket {
pub(crate) base: BucketBase,
pub(crate) layout: Arc<SymbolLayoutProperties::PossiblyEvaluated>,
pub(crate) bucket_leader_id: String,
pub(crate) icons_need_linear: bool,
pub(crate) sort_features_by_y: bool,
pub(crate) icons_in_text: bool,
pub(crate) sort_key_ranges: Vec<SortKeyRange>,
pub(crate) paint_properties: VecMap<String, RwLock<PaintProperties>>,
pub(crate) text_size_binder: SymbolSizeBinder,
pub(crate) icon_size_binder: SymbolSizeBinder,
pub(crate) tile_pixel_ratio: f32,
pub(crate) max_height_offset: f32,
#[wire(skip, default = "next_bucket_instance_id")]
pub(crate) bucket_instance_id: u32,
pub(crate) allow_vertical_placement: bool,
pub(crate) placement_modes: Vec<TextWritingModeType>,
#[wire(skip)]
has_format_section_overrides: OnceLock<bool>,
#[wire(skip)]
pub(crate) version: AtomicU32,
#[wire(skip)]
pub(crate) opacity_version: AtomicU32,
#[wire(skip)]
pub(crate) dynamic_version: AtomicU32,
#[wire(skip)]
pub(crate) sort_version: AtomicU32,
#[wire(skip)]
pub(crate) binder_version: AtomicU32,
state: Mutex<SymbolBucketState>,
}
impl std::fmt::Debug for SymbolBucket {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SymbolBucket").field("bucket_leader_id", &self.bucket_leader_id).finish_non_exhaustive()
}
}
impl SymbolBucket {
#[expect(
clippy::too_many_arguments,
reason = "the evaluated layout and sizes, the laid-out symbols and the placement flags that the bucket keeps"
)]
#[must_use]
pub(crate) fn new(
layout: Arc<SymbolLayoutProperties::PossiblyEvaluated>,
paint_properties: &VecMap<String, Arc<EvaluatedLayer<Symbol>>>,
text_size: &PropertyValue<f32>,
icon_size: &PropertyValue<f32>,
zoom: f32,
icons_need_linear: bool,
sort_features_by_y: bool,
bucket_name: String,
symbol_instances: Vec<SymbolInstance>,
symbol_instance_pools: SymbolInstancePools,
sort_key_ranges: Vec<SortKeyRange>,
tile_pixel_ratio: f32,
allow_vertical_placement: bool,
placement_modes: Vec<TextWritingModeType>,
icons_in_text: bool,
) -> Self {
let icon_size_data_driven_or_zoom = icon_size.is_expression()
&& (!icon_size.as_expression().is_feature_constant() || !icon_size.as_expression().is_zoom_constant());
let mut binders = VecMap::new();
for (id, properties) in paint_properties {
let evaluated = &properties.paint;
binders.entry(id.clone()).or_insert_with(|| {
RwLock::new(PaintProperties {
icon_binders: SymbolIconBinders::new(evaluated, zoom),
text_binders: SymbolTextBinders::new(evaluated, zoom),
})
});
}
let max_height_offset = symbol_instances.iter().map(SymbolInstance::height_offset).fold(0.0, f32::max);
SymbolBucket {
base: BucketBase::default(),
layout,
bucket_leader_id: bucket_name,
icons_need_linear: icons_need_linear || icon_size_data_driven_or_zoom,
sort_features_by_y,
icons_in_text,
sort_key_ranges,
paint_properties: binders,
text_size_binder: SymbolSizeBinder::create(zoom, text_size, SymbolLayoutProperties::Defaults::text_size()),
icon_size_binder: SymbolSizeBinder::create(zoom, icon_size, SymbolLayoutProperties::Defaults::icon_size()),
tile_pixel_ratio,
max_height_offset,
bucket_instance_id: next_bucket_instance_id(),
allow_vertical_placement,
placement_modes,
has_format_section_overrides: OnceLock::new(),
version: AtomicU32::new(0),
opacity_version: AtomicU32::new(0),
dynamic_version: AtomicU32::new(0),
sort_version: AtomicU32::new(0),
binder_version: AtomicU32::new(0),
state: Mutex::new(SymbolBucketState {
sorted_angle: f32::MAX,
symbol_instances,
symbol_instance_pools,
..Default::default()
}),
}
}
pub(crate) fn state(&self) -> MutexGuard<'_, SymbolBucketState> {
self.state.lock()
}
pub(crate) fn state_mut(&mut self) -> &mut SymbolBucketState {
self.state.get_mut()
}
pub(crate) fn bump_version(&self) {
self.version.fetch_add(1, Ordering::SeqCst);
}
pub(crate) fn has_text_data(&self) -> bool {
!self.state().text.segments.is_empty()
}
pub(crate) fn has_icon_data(&self) -> bool {
!self.state().icon.segments.is_empty()
}
pub(crate) fn has_sdf_icon_data(&self) -> bool {
!self.state().sdf_icon.segments.is_empty()
}
pub(crate) fn has_icon_collision_box_data(&self) -> bool {
self.state().icon_collision_box.as_ref().is_some_and(|b| !b.segments.is_empty())
}
pub(crate) fn has_icon_collision_circle_data(&self) -> bool {
self.state().icon_collision_circle.as_ref().is_some_and(|b| !b.segments.is_empty())
}
pub(crate) fn has_text_collision_box_data(&self) -> bool {
self.state().text_collision_box.as_ref().is_some_and(|b| !b.segments.is_empty())
}
pub(crate) fn has_text_collision_circle_data(&self) -> bool {
self.state().text_collision_circle.as_ref().is_some_and(|b| !b.segments.is_empty())
}
pub(crate) fn has_format_section_overrides(&self) -> bool {
*self
.has_format_section_overrides
.get_or_init(|| SymbolLayerPaintPropertyOverrides::has_overrides(&self.layout.text_field))
}
pub(crate) fn has_variable_text_anchors(&self) -> bool {
let has_text_variable_anchor_offset =
self.layout.text_variable_anchor_offset.constant().is_none_or(|offsets| !offsets.is_empty());
has_text_variable_anchor_offset || !self.layout.text_variable_anchor.uniform().is_empty()
}
pub(crate) fn sort_features(&self, angle: f32) {
if !self.sort_features_by_y {
return;
}
debug_assert!(angle != f32::MAX);
let mut state = self.state();
if state.sorted_angle == angle {
return;
}
state.sorted_angle = angle;
if state.text.segments.len() > 1 || (state.icon.segments.len() > 1 || state.sdf_icon.segments.len() > 1) {
return;
}
self.base.uploaded.store(false, Ordering::SeqCst);
self.sort_version.fetch_add(1, Ordering::SeqCst);
self.bump_version();
let state = &mut *state;
state.text.triangles.clear();
state.icon.triangles.clear();
state.sdf_icon.triangles.clear();
let mut symbols_sort_order = Vec::with_capacity(state.symbol_instances.len());
for index in get_sorted_symbols(&state.symbol_instances, angle) {
let symbol_instance = &state.symbol_instances[index];
symbols_sort_order.push(symbol_instance.get_data_feature_index());
if let Some(i) = symbol_instance.placed_right_text_index {
add_placed_symbol(&mut state.text.triangles, &state.text.placed_symbols[i]);
}
if let Some(i) = symbol_instance.placed_center_text_index
&& !symbol_instance.get_single_line()
{
add_placed_symbol(&mut state.text.triangles, &state.text.placed_symbols[i]);
}
if let Some(i) = symbol_instance.placed_left_text_index
&& !symbol_instance.get_single_line()
{
add_placed_symbol(&mut state.text.triangles, &state.text.placed_symbols[i]);
}
if let Some(i) = symbol_instance.placed_vertical_text_index {
add_placed_symbol(&mut state.text.triangles, &state.text.placed_symbols[i]);
}
let icon_buffer = if symbol_instance.has_sdf_icon() { &mut state.sdf_icon } else { &mut state.icon };
if let Some(i) = symbol_instance.placed_icon_index {
add_placed_symbol(&mut icon_buffer.triangles, &icon_buffer.placed_symbols[i]);
}
if let Some(i) = symbol_instance.placed_vertical_icon_index {
add_placed_symbol(&mut icon_buffer.triangles, &icon_buffer.placed_symbols[i]);
}
}
state.feature_sort_order = Some(Arc::new(symbols_sort_order));
}
#[expect(clippy::unused_self, reason = "the bucket's view of its sort key ranges")]
pub(crate) fn get_symbols(&self, range: Option<&SortKeyRange>, count: usize) -> std::ops::Range<usize> {
match range {
Some(range) if range.start < range.end && range.end <= count => range.start..range.end,
_ => 0..count,
}
}
pub(crate) fn mark_vertices_updated(&self, update_opacities: bool, dynamic_updated: bool) {
let mut state = self.state();
if update_opacities {
self.base.uploaded.store(false, Ordering::SeqCst);
self.opacity_version.fetch_add(1, Ordering::SeqCst);
}
if dynamic_updated {
self.base.uploaded.store(false, Ordering::SeqCst);
self.dynamic_version.fetch_add(1, Ordering::SeqCst);
}
if !self.base.uploaded.load(Ordering::SeqCst) {
state.text.update_modified();
state.icon.update_modified();
state.sdf_icon.update_modified();
self.bump_version();
}
}
#[expect(clippy::too_many_arguments, reason = "each argument is a component of the packed vertex")]
#[must_use]
pub(crate) fn layout_attributes(
label_anchor: Vec2,
o: Vec2,
glyph_offset_y: f32,
tx: u16,
ty: u16,
tex_origin: [u16; 2],
size_data: Range<f32>,
is_sdf: bool,
pixel_offset: Vec2,
min_font_scale: Vec2,
height_offset: f32,
) -> SymbolLayoutVertex {
let a_size_min = (MAX_PACKED_SIZE.min((size_data.min * f32::from(SIZE_PACK_FACTOR)) as u16) << 1)
.wrapping_add(u16::from(is_sdf));
let a_size_max = MAX_PACKED_SIZE.min((size_data.max * f32::from(SIZE_PACK_FACTOR)) as u16);
SymbolLayoutVertex {
a1: [
label_anchor.x as i16,
label_anchor.y as i16,
(o.x * 32.0).round() as i16, ((o.y + glyph_offset_y) * 32.0).round() as i16,
],
a2: [tx, ty, a_size_min, a_size_max],
a3: [
(pixel_offset.x * 16.0) as i16,
(pixel_offset.y * 16.0) as i16,
(min_font_scale.x * 256.0) as i16,
(min_font_scale.y * 256.0) as i16,
],
a4: tex_origin,
a5: height_offset,
}
}
#[must_use]
pub(crate) fn dynamic_layout_attributes(anchor_point: Vec2, label_angle: f32) -> SymbolDynamicLayoutVertex {
SymbolDynamicLayoutVertex { a1: [anchor_point.x, anchor_point.y, label_angle] }
}
#[must_use]
pub(crate) fn opacity_attributes(placed: bool, opacity: f32) -> SymbolOpacityVertex {
SymbolOpacityVertex { a1: [((u32::from((opacity * 127.0) as u8) << 1) | u32::from(placed)) as f32] }
}
#[must_use]
pub(crate) fn collision_layout_vertex(
a: Vec2,
anchor: Vec2,
o: Vec2,
height_offset: f32,
) -> CollisionBoxLayoutVertex {
CollisionBoxLayoutVertex {
a1: [a.x as i16, a.y as i16],
a2: [anchor.x as i16, anchor.y as i16],
a3: [o.x.round() as i16, o.y.round() as i16],
a4: height_offset,
}
}
#[must_use]
pub(crate) fn collision_dynamic_vertex(placed: bool, not_used: bool, shift: Vec2) -> CollisionBoxDynamicVertex {
CollisionBoxDynamicVertex { a1: [u16::from(placed), u16::from(not_used)], a2: [shift.x, shift.y] }
}
}
fn add_placed_symbol(triangles: &mut Vec<u16>, placed_symbol: &PlacedSymbol) {
let end_index = placed_symbol.start_index + placed_symbol.glyph_offsets.len() * 4;
let mut vertex_index = placed_symbol.start_index;
while vertex_index < end_index {
triangles.extend_from_slice(&[vertex_index as u16, (vertex_index + 1) as u16, (vertex_index + 2) as u16]);
triangles.extend_from_slice(&[(vertex_index + 1) as u16, (vertex_index + 2) as u16, (vertex_index + 3) as u16]);
vertex_index += 4;
}
}
#[must_use]
pub(crate) fn get_sorted_symbols(symbol_instances: &[SymbolInstance], angle: f32) -> Vec<usize> {
let mut result: Vec<usize> = (0..symbol_instances.len()).collect();
let sin = angle.sin();
let cos = angle.cos();
result.sort_by_key(|&i| {
let s = &symbol_instances[i];
let p = s.get_anchor().point;
((sin * p.x + cos * p.y).round() as i64, Reverse(s.get_data_feature_index()))
});
result
}
impl Bucket for SymbolBucket {
fn base(&self) -> &BucketBase {
&self.base
}
fn max_content_elevation(&self) -> f32 {
self.max_height_offset
}
fn upload(&self, _context: &Context) {
self.base.uploaded.store(true, Ordering::SeqCst);
}
fn has_data(&self) -> bool {
self.has_text_data()
|| self.has_icon_data()
|| self.has_sdf_icon_data()
|| self.has_icon_collision_box_data()
|| self.has_text_collision_box_data()
|| self.has_icon_collision_circle_data()
|| self.has_text_collision_circle_data()
}
fn write_wire(&self, w: &mut mln_wire::Writer) {
mln_wire::Wire::write(self, w);
}
fn update(&self, states: &FeatureStates, layer: &TileLayer<'_>, layer_id: &str, image_positions: &ImagePositions) {
if let Some(binders) = self.paint_properties.get(layer_id) {
let mut binders = binders.write();
binders.icon_binders.update_vertex_vectors(states, layer, image_positions);
binders.text_binders.update_vertex_vectors(states, layer, image_positions);
self.base.uploaded.store(false, Ordering::SeqCst);
self.binder_version.fetch_add(1, Ordering::SeqCst);
self.bump_version();
}
}
}
#[cfg(test)]
mod tests {
use mln_gfx::shaders::segment::SegmentBase;
use super::*;
#[test]
fn keep_fading_symbols_visible() {
let mut buffer = Buffer::default();
assert!(buffer.has_visible_vertices(0, 1));
buffer.opacity_attribute_data.extend([
SymbolBucket::opacity_attributes(false, 0.0),
SymbolBucket::opacity_attributes(true, 0.0),
SymbolBucket::opacity_attributes(false, 0.5),
SymbolBucket::opacity_attributes(true, 1.0),
]);
assert!(!buffer.has_visible_vertices(0, 1));
assert!(buffer.has_visible_vertices(1, 1)); assert!(buffer.has_visible_vertices(2, 1)); assert!(buffer.has_visible_vertices(3, 1));
assert!(buffer.has_visible_vertices(0, 4)); assert!(buffer.has_visible_vertices(4, 1)); assert!(buffer.has_visible_vertices(usize::MAX, 2));
}
#[test]
fn segment_visibility_reads_the_segment_range() {
let mut buffer = Buffer::default();
buffer.opacity_attribute_data.extend([
SymbolBucket::opacity_attributes(false, 0.0),
SymbolBucket::opacity_attributes(false, 0.0),
SymbolBucket::opacity_attributes(true, 1.0),
SymbolBucket::opacity_attributes(true, 1.0),
]);
buffer.segments.push(SegmentBase::with_lengths(0, 0, 2, 0));
buffer.segments.push(SegmentBase::with_lengths(2, 0, 2, 0));
assert!(!buffer.segment_has_visible_vertices(Some(0)));
assert!(buffer.segment_has_visible_vertices(Some(1)));
assert!(buffer.segment_has_visible_vertices(Some(2)));
}
}