1use mln_gfx::gfx_types::AttributeDataType;
12use mln_style::collections::VecMap;
13use mln_style::color::Color;
14use mln_style::crs::WorldMapping;
15use mln_style::expression::{Dependency, EvaluationContext, Image, Value, ValueConverter};
16use mln_style::feature::GeometryTileFeature;
17use mln_style::property::evaluated::{Evaluated, Faded};
18use mln_style::property::expression::PropertyExpression;
19use mln_style::range::Range;
20use mln_style::tile_id::CanonicalTileID;
21
22use crate::draw::vertex::{VertexAttribute, VertexBinding};
23use crate::draw::vertex_attribute::Uniforms;
24use crate::draw::vertices::VertexBuffer;
25use crate::layer::bucket_geometry::GeometryVec;
26use crate::layer::paint_property_statistics::{PaintPropertyStatistics, StatisticValue};
27use crate::text::atlas::ImagePositions;
28use crate::tile::TileLayer;
29use crate::tile::feature::feature_id_to_string;
30
31#[derive(Clone, Copy, Debug, PartialEq, Eq, mln_wire::Wire)]
33pub(crate) struct FeatureVertexRange {
34 pub(crate) feature_index: usize,
35 pub(crate) start: usize,
36 pub(crate) end: usize,
37}
38
39pub(crate) type FeatureVertexRangeMap = VecMap<String, Vec<FeatureVertexRange>>;
40
41#[derive(Clone, Debug, Default, PartialEq, mln_wire::Wire)]
45pub struct InterleavedVertexBuffer {
46 pub stride: usize,
47 pub vertex_count: usize,
48 pub shared_vertex_vector: GeometryVec<u8>,
49}
50
51impl InterleavedVertexBuffer {
52 pub fn fill(&mut self, indexes: std::ops::Range<usize>, offset: usize, value: &[u8]) {
54 if indexes.is_empty() {
56 return;
57 }
58 let stride = self.stride;
59 let data = self.shared_vertex_vector.get_mut();
60 for index in indexes {
61 let start = stride * index + offset;
62 debug_assert!(start + value.len() <= data.len());
63 data[start..start + value.len()].copy_from_slice(value);
64 }
65 }
66
67 pub fn extend_vertex_format(&mut self, size: usize, alignment: usize) -> usize {
70 let mut offset = self.stride & (alignment - 1);
71 if offset != 0 {
72 offset = alignment - offset;
73 }
74
75 let vertex_offset = self.stride + offset;
76 self.stride += size + offset;
77
78 vertex_offset
79 }
80}
81
82pub trait BinderValue: Clone + Default + ValueConverter + StatisticValue + std::fmt::Debug {
86 const DIMENSIONS: usize;
88 const BASE_DATA_TYPE: AttributeDataType;
90 const INTERPOLATED_DATA_TYPE: AttributeDataType;
92
93 fn attribute_value(&self) -> [f32; 2];
95}
96
97impl BinderValue for f32 {
98 const DIMENSIONS: usize = 1;
99 const BASE_DATA_TYPE: AttributeDataType = AttributeDataType::Float;
100 const INTERPOLATED_DATA_TYPE: AttributeDataType = AttributeDataType::Float2;
101
102 fn attribute_value(&self) -> [f32; 2] {
103 [*self, 0.0]
104 }
105}
106
107fn pack_uint8_pair(a: f32, b: f32) -> u16 {
110 (i32::from(a as u16) * 256 + i32::from(b as u16)) as u16
111}
112
113impl BinderValue for Color {
114 const DIMENSIONS: usize = 2;
115 const BASE_DATA_TYPE: AttributeDataType = AttributeDataType::Float2;
116 const INTERPOLATED_DATA_TYPE: AttributeDataType = AttributeDataType::Float4;
117
118 fn attribute_value(&self) -> [f32; 2] {
125 let [r, g, b, a] = self.to_premultiplied();
126 [f32::from(pack_uint8_pair(255.0 * r, 255.0 * g)), f32::from(pack_uint8_pair(255.0 * b, 255.0 * a))]
127 }
128}
129
130fn zoom_stop_values<T: BinderValue>(min: &T, max: &T) -> [f32; 4] {
134 let mut values = [0.0; 4];
135 values[..T::DIMENSIONS].copy_from_slice(&min.attribute_value()[..T::DIMENSIONS]);
136 values[T::DIMENSIONS..2 * T::DIMENSIONS].copy_from_slice(&max.attribute_value()[..T::DIMENSIONS]);
137 values
138}
139
140#[derive(Clone, Debug, mln_wire::Wire)]
142pub(crate) enum PaintPropertyBinderKind<T> {
143 Constant {
144 constant: T,
145 },
146 SourceFunction {
147 expression: PropertyExpression<T>,
148 default_value: T,
149 feature_map: FeatureVertexRangeMap,
150 vertex_data: InterleavedVertexData,
151 },
152 CompositeFunction {
153 expression: PropertyExpression<T>,
154 default_value: T,
155 zoom_range: Range<f32>,
156 feature_map: FeatureVertexRangeMap,
157 vertex_data: InterleavedVertexData,
158 },
159}
160
161#[derive(Clone, Debug, mln_wire::Wire, PartialEq, Eq)]
164pub enum InterleavedVertexData {
165 Uninitialized,
166 Interleaved { offset: usize },
167}
168
169impl InterleavedVertexData {
170 #[must_use]
172 pub fn offset(&self) -> Option<usize> {
173 match self {
174 Self::Uninitialized => None,
175 Self::Interleaved { offset } => Some(*offset),
176 }
177 }
178}
179
180impl<T: BinderValue> PaintPropertyBinderKind<T> {
181 fn vertex_offset(&self) -> Option<usize> {
182 match self {
183 Self::Constant { .. } => None,
184 Self::SourceFunction { vertex_data, .. } | Self::CompositeFunction { vertex_data, .. } => {
185 vertex_data.offset()
186 }
187 }
188 }
189
190 fn update_vertex_vector(
191 &self,
192 statistics: &mut PaintPropertyStatistics<T>,
193 buffer: &mut InterleavedVertexBuffer,
194 vertex_offset: usize,
195 range: &FeatureVertexRange,
196 feature: &dyn GeometryTileFeature,
197 state: &mln_style::feature::FeatureState,
198 ) {
199 match self {
200 Self::Constant { .. } => {}
201 Self::SourceFunction { expression, default_value, .. } => {
202 let evaluated = expression.evaluate(
203 &EvaluationContext::from_feature(Some(feature)).with_feature_state(Some(state)),
204 default_value.clone(),
205 );
206 statistics.add(&evaluated);
207 let value = evaluated.attribute_value();
208 buffer.fill(range.start..range.end, vertex_offset, bytemuck::cast_slice(&value[..T::DIMENSIONS]));
209 }
210 Self::CompositeFunction { expression, default_value, zoom_range, .. } => {
211 let min = expression.evaluate(
212 &EvaluationContext::with_zoom_feature_state(f64::from(zoom_range.min), Some(feature), Some(state)),
213 default_value.clone(),
214 );
215 let max = expression.evaluate(
216 &EvaluationContext::with_zoom_feature_state(f64::from(zoom_range.max), Some(feature), Some(state)),
217 default_value.clone(),
218 );
219 statistics.add(&min);
220 statistics.add(&max);
221 let value = zoom_stop_values(&min, &max);
222 buffer.fill(range.start..range.end, vertex_offset, bytemuck::cast_slice(&value[..2 * T::DIMENSIONS]));
223 }
224 }
225 }
226}
227
228#[derive(Clone, Debug, mln_wire::Wire)]
233pub struct PaintPropertyBinder<T> {
234 pub(crate) kind: PaintPropertyBinderKind<T>,
235 pub statistics: PaintPropertyStatistics<T>,
236}
237
238impl<T: BinderValue> PaintPropertyBinder<T> {
239 pub fn create(value: &Evaluated<T>, zoom: f32) -> Self {
241 let kind = match value {
242 Evaluated::Constant(constant) | Evaluated::CrossFaded(Faded { to: constant, .. }) => {
243 PaintPropertyBinderKind::Constant { constant: constant.clone() }
244 }
245 Evaluated::PerFeature { expression, default } => {
246 let default_value = default.clone();
247 if expression.is_zoom_constant() {
248 PaintPropertyBinderKind::SourceFunction {
249 expression: expression.clone(),
250 default_value,
251 feature_map: FeatureVertexRangeMap::new(),
252 vertex_data: InterleavedVertexData::Uninitialized,
253 }
254 } else {
255 PaintPropertyBinderKind::CompositeFunction {
256 expression: expression.clone(),
257 default_value,
258 zoom_range: Range::new(zoom, zoom + 1.0),
259 feature_map: FeatureVertexRangeMap::new(),
260 vertex_data: InterleavedVertexData::Uninitialized,
261 }
262 }
263 }
264 };
265 PaintPropertyBinder { kind, statistics: PaintPropertyStatistics::default() }
266 }
267
268 fn zoom_interpolated_size() -> usize {
271 2 * T::DIMENSIONS * 4
272 }
273
274 pub(crate) fn set_interleaved_buffer(&mut self, buffer: &mut InterleavedVertexBuffer) {
277 let vertex_data = match &mut self.kind {
278 PaintPropertyBinderKind::Constant { .. } => return,
279 PaintPropertyBinderKind::SourceFunction { vertex_data, .. }
280 | PaintPropertyBinderKind::CompositeFunction { vertex_data, .. } => vertex_data,
281 };
282 let new_vertex_offset = buffer.extend_vertex_format(Self::zoom_interpolated_size(), align_of::<f32>());
283 if matches!(vertex_data, InterleavedVertexData::Uninitialized) {
284 *vertex_data = InterleavedVertexData::Interleaved { offset: new_vertex_offset };
285 }
286 }
287
288 pub(crate) fn vertex_count(&self, buffer: &InterleavedVertexBuffer) -> usize {
289 if self.kind.vertex_offset().is_some() { buffer.vertex_count } else { 0 }
290 }
291
292 pub(crate) fn is_interpolated(&self) -> bool {
293 matches!(self.kind, PaintPropertyBinderKind::CompositeFunction { .. })
294 }
295
296 pub(crate) fn populate_vertex_vector(
301 &mut self,
302 buffer: &mut InterleavedVertexBuffer,
303 feature: &dyn GeometryTileFeature,
304 length: usize,
305 index: usize,
306 inputs: &EvaluationContext<'_>,
307 ) {
308 let Some(vertex_offset) = self.kind.vertex_offset() else { return };
309 let elements = self.vertex_count(buffer);
310 let (expression, feature_map) = match &mut self.kind {
311 PaintPropertyBinderKind::Constant { .. } => return,
312 PaintPropertyBinderKind::SourceFunction { expression, default_value, feature_map, .. } => {
313 let evaluated = expression
314 .evaluate(&EvaluationContext { feature: Some(feature), ..*inputs }, default_value.clone());
315 self.statistics.add(&evaluated);
316 let value = evaluated.attribute_value();
317 buffer.fill(elements..length, vertex_offset, bytemuck::cast_slice(&value[..T::DIMENSIONS]));
319 (expression, feature_map)
320 }
321 PaintPropertyBinderKind::CompositeFunction {
322 expression, default_value, zoom_range, feature_map, ..
323 } => {
324 let at =
325 |zoom: f32| EvaluationContext { zoom: Some(f64::from(zoom)), feature: Some(feature), ..*inputs };
326 let min = expression.evaluate(&at(zoom_range.min), default_value.clone());
327 let max = expression.evaluate(&at(zoom_range.max), default_value.clone());
328 self.statistics.add(&min);
329 self.statistics.add(&max);
330 let value = zoom_stop_values(&min, &max);
331 buffer.fill(elements..length, vertex_offset, bytemuck::cast_slice(&value[..2 * T::DIMENSIONS]));
332 (expression, feature_map)
333 }
334 };
335 if expression.expression().has(Dependency::FEATURE_STATE)
338 && let Some(id_str) = feature_id_to_string(&feature.id())
339 {
340 feature_map.entry(id_str).or_default().push(FeatureVertexRange {
341 feature_index: index,
342 start: elements,
343 end: length,
344 });
345 }
346 }
347
348 pub(crate) fn update_vertex_vectors(
349 &mut self,
350 buffer: &mut InterleavedVertexBuffer,
351 states: &crate::layer::bucket::FeatureStates,
352 layer: &TileLayer<'_>,
353 ) {
354 let Self { kind, statistics } = self;
355 let (feature_map, vertex_data) = match &*kind {
356 PaintPropertyBinderKind::Constant { .. } => return,
357 PaintPropertyBinderKind::SourceFunction { feature_map, vertex_data, .. }
358 | PaintPropertyBinderKind::CompositeFunction { feature_map, vertex_data, .. } => (feature_map, vertex_data),
359 };
360 let Some(vertex_offset) = vertex_data.offset() else {
361 return;
362 };
363 for (id, state) in states {
364 let Some(positions) = feature_map.get(id) else {
365 continue;
366 };
367 for pos in positions {
368 let Ok(feature) = layer.feature(pos.feature_index) else {
371 continue;
372 };
373 kind.update_vertex_vector(statistics, buffer, vertex_offset, pos, &feature, state);
374 }
375 }
376 }
377
378 pub fn interpolation_factor(&self, current_zoom: f32) -> f32 {
381 match &self.kind {
382 PaintPropertyBinderKind::Constant { .. } | PaintPropertyBinderKind::SourceFunction { .. } => 0.0,
383 PaintPropertyBinderKind::CompositeFunction { expression, zoom_range, .. } => {
384 let possibly_rounded_zoom =
385 if expression.use_integer_zoom() { current_zoom.floor() } else { current_zoom };
386
387 let zoom_range = Range::new(f64::from(zoom_range.min), f64::from(zoom_range.max));
388 let t = expression.interpolation_factor(zoom_range, f64::from(possibly_rounded_zoom));
389 mln_style::math::fmaxf(0.0, mln_style::math::fminf(1.0, t))
390 }
391 }
392 }
393
394 pub(crate) fn apply_paint_property(&self, buffer: &InterleavedVertexBuffer) -> Option<(AttributeDataType, u32)> {
397 if let Some(vertex_offset) = self.kind.vertex_offset() {
398 let data_type = if self.is_interpolated() { T::INTERPOLATED_DATA_TYPE } else { T::BASE_DATA_TYPE };
399 Some((data_type, vertex_offset as u32))
400 } else {
401 debug_assert_eq!(self.vertex_count(buffer), 0);
403 None
404 }
405 }
406}
407
408#[derive(Clone, Debug, mln_wire::Wire)]
410pub(crate) enum CrossFadedPaintPropertyBinderKind<T> {
411 Constant {
412 constant: Faded<T>,
413 },
414 Composite {
415 expression: PropertyExpression<T>,
416 default_value: T,
417 zoom_range: Range<f32>,
418 vertex_data: InterleavedVertexData,
419 #[wire(skip)]
423 populated_count: usize,
424 },
425}
426
427impl<T> CrossFadedPaintPropertyBinderKind<T> {
428 fn vertex_offset(&self) -> Option<usize> {
429 match self {
430 Self::Constant { .. } => None,
431 Self::Composite { vertex_data, .. } => vertex_data.offset(),
432 }
433 }
434}
435
436#[derive(Clone, Debug, mln_wire::Wire)]
441pub struct CrossFadedPaintPropertyBinder<T> {
442 pub(crate) kind: CrossFadedPaintPropertyBinderKind<T>,
443}
444
445const PATTERN_VERTEX_SIZE: usize = PATTERN_PIXEL_RATIO_OFFSET + size_of::<f32>();
448
449const PATTERN_PIXEL_RATIO_OFFSET: usize = 4 * size_of::<u16>();
451
452fn pattern_vertex(tlbr: [u16; 4], pixel_ratio: f32) -> [u8; PATTERN_VERTEX_SIZE] {
455 let mut vertex = [0; PATTERN_VERTEX_SIZE];
456 vertex[..PATTERN_PIXEL_RATIO_OFFSET].copy_from_slice(bytemuck::cast_slice(&tlbr));
457 vertex[PATTERN_PIXEL_RATIO_OFFSET..].copy_from_slice(&pixel_ratio.to_ne_bytes());
458 vertex
459}
460
461impl CrossFadedPaintPropertyBinder<Image> {
462 #[must_use]
465 pub fn create(value: &Evaluated<Image>, zoom: f32) -> Self {
466 let kind = match value {
467 Evaluated::Constant(constant) => CrossFadedPaintPropertyBinderKind::Constant {
468 constant: Faded { from: constant.clone(), to: constant.clone() },
469 },
470 Evaluated::CrossFaded(constant) => {
471 CrossFadedPaintPropertyBinderKind::Constant { constant: constant.clone() }
472 }
473 Evaluated::PerFeature { expression, default } => CrossFadedPaintPropertyBinderKind::Composite {
474 expression: expression.clone(),
475 default_value: default.clone(),
476 zoom_range: Range::new(zoom, zoom + 1.0),
477 vertex_data: InterleavedVertexData::Uninitialized,
478 populated_count: 0,
479 },
480 };
481 CrossFadedPaintPropertyBinder { kind }
482 }
483
484 pub(crate) fn set_interleaved_buffer(&mut self, buffer: &mut InterleavedVertexBuffer) {
487 let CrossFadedPaintPropertyBinderKind::Composite { vertex_data, .. } = &mut self.kind else {
488 return;
489 };
490 let new_vertex_offset = buffer.extend_vertex_format(PATTERN_VERTEX_SIZE, align_of::<f32>());
491 if matches!(vertex_data, InterleavedVertexData::Uninitialized) {
492 *vertex_data = InterleavedVertexData::Interleaved { offset: new_vertex_offset };
493 }
494 }
495
496 pub(crate) fn vertex_count(&self, buffer: &InterleavedVertexBuffer) -> usize {
497 if self.kind.vertex_offset().is_some() { buffer.vertex_count } else { 0 }
498 }
499
500 pub(crate) fn populate_vertex_vector(
501 &mut self,
502 buffer: &mut InterleavedVertexBuffer,
503 length: usize,
504 pattern_positions: &ImagePositions,
505 pattern_dependencies: Option<&PatternDependency>,
506 ) {
507 let CrossFadedPaintPropertyBinderKind::Composite { populated_count, vertex_data, .. } = &mut self.kind else {
508 return;
509 };
510 let InterleavedVertexData::Interleaved { offset: vertex_offset } = vertex_data else {
511 return;
512 };
513 match pattern_dependencies {
514 Some(dependencies) if !dependencies.mid.is_empty() => {
515 if !pattern_positions.is_empty() {
516 let (Some(_), Some(image_mid), Some(_)) = (
519 pattern_positions.get(&dependencies.min),
520 pattern_positions.get(&dependencies.mid),
521 pattern_positions.get(&dependencies.max),
522 ) else {
523 return;
524 };
525
526 let vertex = pattern_vertex(image_mid.tlbr(), image_mid.pixel_ratio);
527 buffer.fill(*populated_count..length, *vertex_offset, &vertex);
528 *populated_count = (*populated_count).max(length);
529 }
530 }
531 _ => {
532 buffer.fill(*populated_count..length, *vertex_offset, &pattern_vertex([0; 4], 1.0));
540 *populated_count = (*populated_count).max(length);
541 }
542 }
543 }
544
545 #[must_use]
547 #[expect(clippy::unused_self, reason = "the call of every binder, which the others' factors read")]
548 pub fn interpolation_factor(&self, _current_zoom: f32) -> (f32, f32) {
549 (0.0, 0.0)
550 }
551
552 pub(crate) fn apply_paint_property(&self, index: usize) -> Option<(AttributeDataType, u32)> {
557 let vertex_offset = self.kind.vertex_offset()?;
558 Some(match index {
559 0 | 1 => (AttributeDataType::UShort4, vertex_offset as u32),
560 _ => (AttributeDataType::Float, (vertex_offset + PATTERN_PIXEL_RATIO_OFFSET) as u32),
561 })
562 }
563}
564
565pub trait PaintPropertyBinderBase {
568 fn set_interleaved(&mut self, buffer: &mut InterleavedVertexBuffer);
570 #[expect(
571 clippy::too_many_arguments,
572 reason = "the vertex buffer, the feature and its index range, its patterns, the tile and the formatted section that evaluate a property"
573 )]
574 fn populate(
577 &mut self,
578 buffer: &mut InterleavedVertexBuffer,
579 feature: &dyn GeometryTileFeature,
580 length: usize,
581 index: usize,
582 pattern_positions: &ImagePositions,
583 pattern_dependencies: Option<&PatternDependency>,
584 canonical: &CanonicalTileID,
585 world: &WorldMapping,
586 formatted_section: &Value,
587 );
588 fn update_vectors(
591 &mut self,
592 _buffer: &mut InterleavedVertexBuffer,
593 _states: &crate::layer::bucket::FeatureStates,
594 _layer: &TileLayer<'_>,
595 ) {
596 }
597 fn depends_on_feature_state(&self) -> bool {
599 false
600 }
601 fn binder_vertex_count(&self, buffer: &InterleavedVertexBuffer) -> usize;
603 fn attribute(&self, buffer: &InterleavedVertexBuffer, index: usize) -> Option<(AttributeDataType, u32)>;
607}
608
609impl<T: BinderValue> PaintPropertyBinderBase for PaintPropertyBinder<T> {
610 fn set_interleaved(&mut self, buffer: &mut InterleavedVertexBuffer) {
611 self.set_interleaved_buffer(buffer);
612 }
613 fn populate(
616 &mut self,
617 buffer: &mut InterleavedVertexBuffer,
618 feature: &dyn GeometryTileFeature,
619 length: usize,
620 index: usize,
621 _pattern_positions: &ImagePositions,
622 _pattern_dependencies: Option<&PatternDependency>,
623 canonical: &CanonicalTileID,
624 world: &WorldMapping,
625 formatted_section: &Value,
626 ) {
627 let inputs = EvaluationContext::default()
628 .with_formatted_section(Some(formatted_section))
629 .with_canonical_tile_id(Some(canonical))
630 .with_world(Some(world));
631 self.populate_vertex_vector(buffer, feature, length, index, &inputs);
632 }
633 fn update_vectors(
634 &mut self,
635 buffer: &mut InterleavedVertexBuffer,
636 states: &crate::layer::bucket::FeatureStates,
637 layer: &TileLayer<'_>,
638 ) {
639 self.update_vertex_vectors(buffer, states, layer);
640 }
641 fn depends_on_feature_state(&self) -> bool {
642 match &self.kind {
643 PaintPropertyBinderKind::Constant { .. } => false,
644 PaintPropertyBinderKind::SourceFunction { expression, .. }
645 | PaintPropertyBinderKind::CompositeFunction { expression, .. } => {
646 expression.expression().has(Dependency::FEATURE_STATE)
647 }
648 }
649 }
650 fn binder_vertex_count(&self, buffer: &InterleavedVertexBuffer) -> usize {
651 self.vertex_count(buffer)
652 }
653 fn attribute(&self, buffer: &InterleavedVertexBuffer, _index: usize) -> Option<(AttributeDataType, u32)> {
654 self.apply_paint_property(buffer)
655 }
656}
657
658impl PaintPropertyBinderBase for CrossFadedPaintPropertyBinder<Image> {
659 fn set_interleaved(&mut self, buffer: &mut InterleavedVertexBuffer) {
660 self.set_interleaved_buffer(buffer);
661 }
662 fn populate(
665 &mut self,
666 buffer: &mut InterleavedVertexBuffer,
667 _feature: &dyn GeometryTileFeature,
668 length: usize,
669 _index: usize,
670 pattern_positions: &ImagePositions,
671 pattern_dependencies: Option<&PatternDependency>,
672 _canonical: &CanonicalTileID,
673 _world: &WorldMapping,
674 _formatted_section: &Value,
675 ) {
676 self.populate_vertex_vector(buffer, length, pattern_positions, pattern_dependencies);
677 }
678 fn binder_vertex_count(&self, buffer: &InterleavedVertexBuffer) -> usize {
679 self.vertex_count(buffer)
680 }
681 fn attribute(&self, _buffer: &InterleavedVertexBuffer, index: usize) -> Option<(AttributeDataType, u32)> {
682 self.apply_paint_property(index)
683 }
684}
685
686#[derive(Clone, Debug, Default)]
691pub struct PaintAttributes {
692 pub vertices: Option<VertexBinding>,
696 pub uniforms: Uniforms,
697}
698
699pub fn bind_paint_property(
704 binder: &dyn PaintPropertyBinderBase,
705 buffer: &InterleavedVertexBuffer,
706 attributes: &[&'static str],
707 is_constant: bool,
708 read: &mut Vec<VertexAttribute>,
709 uniforms: &mut Uniforms,
710) {
711 if is_constant || binder.binder_vertex_count(buffer) == 0 {
712 for &attribute in attributes {
713 uniforms.insert(attribute);
714 }
715 } else {
716 read.extend(attributes.iter().enumerate().filter_map(|(index, &name)| {
717 let (format, offset) = binder.attribute(buffer, index)?;
718 Some(VertexAttribute { name, format, offset })
719 }));
720 }
721}
722
723#[must_use]
726pub fn paint_attributes(
727 buffer: &InterleavedVertexBuffer,
728 vertices: Option<&VertexBuffer>,
729 read: Vec<VertexAttribute>,
730 uniforms: Uniforms,
731) -> PaintAttributes {
732 let vertices = vertices.filter(|_| !read.is_empty()).map(|vertices| {
733 debug_assert_eq!(vertices.count() / buffer.stride.max(1), buffer.vertex_count);
734 VertexBinding::new(vertices, buffer.stride as u32, read)
735 });
736 PaintAttributes { vertices, uniforms }
737}
738
739pub trait PaintBinders: Clone + Send + mln_wire::Wire + 'static {
743 type Paint: 'static;
746
747 fn new(paint: &Self::Paint, zoom: f32) -> Self;
749
750 fn vertices_mut(&mut self) -> &mut InterleavedVertexBuffer;
752
753 #[expect(clippy::too_many_arguments, reason = "the feature, its vertices, its tile, its section and its patterns")]
758 fn populate(
759 &mut self,
760 feature: &dyn GeometryTileFeature,
761 length: usize,
762 index: usize,
763 positions: &ImagePositions,
764 pattern: Option<&PatternDependency>,
765 canonical: &CanonicalTileID,
766 world: &WorldMapping,
767 section: &Value,
768 );
769
770 fn feature_state(&mut self, states: &crate::layer::bucket::FeatureStates, layer: &TileLayer<'_>);
773
774 fn depends_on_feature_state(&self) -> bool;
776}
777
778#[derive(Clone, Debug, mln_wire::Wire)]
781#[wire(bound = "P: mln_wire::Wire")]
782pub struct LayerBinders<P> {
783 layers: Vec<(String, P)>,
785}
786
787impl<P> Default for LayerBinders<P> {
788 fn default() -> Self {
790 LayerBinders { layers: Vec::new() }
791 }
792}
793
794impl<P> LayerBinders<P> {
795 #[must_use]
797 pub fn from_layers(layers: Vec<(String, P)>) -> Self {
798 LayerBinders { layers }
799 }
800
801 #[must_use]
803 pub fn get(&self, id: &str) -> Option<&P> {
804 self.layers.iter().find(|(layer, _)| layer == id).map(|(_, binders)| binders)
805 }
806
807 pub fn values(&self) -> impl Iterator<Item = &P> {
809 self.layers.iter().map(|(_, binders)| binders)
810 }
811
812 pub fn values_mut(&mut self) -> impl Iterator<Item = &mut P> {
814 self.layers.iter_mut().map(|(_, binders)| binders)
815 }
816
817 pub fn iter_mut(&mut self) -> impl Iterator<Item = (&str, &mut P)> {
819 self.layers.iter_mut().map(|(id, binders)| (id.as_str(), binders))
820 }
821}
822
823impl<P: PaintBinders> LayerBinders<P> {
824 pub fn new<T>(layers: &[std::sync::Arc<crate::layer::layer_type::EvaluatedLayer<T>>], zoom: f32) -> Self
827 where
828 T: mln_style::layer::StyleLayerType<PaintProperties: mln_style::layer::PaintSet<Evaluated = P::Paint>>,
829 {
830 let mut binders: Vec<(String, P)> = Vec::with_capacity(layers.len());
831 for layer in layers {
832 if !binders.iter().any(|(id, _)| *id == layer.style.id) {
833 binders.push((layer.style.id.clone(), P::new(&layer.paint, zoom)));
834 }
835 }
836 LayerBinders { layers: binders }
837 }
838
839 #[expect(clippy::too_many_arguments, reason = "the feature, its vertices, its tile, its section and its patterns")]
843 pub fn populate(
844 &mut self,
845 feature: &dyn GeometryTileFeature,
846 length: usize,
847 index: usize,
848 positions: &ImagePositions,
849 patterns: Option<&PatternLayerMap>,
850 canonical: &CanonicalTileID,
851 world: &WorldMapping,
852 section: &Value,
853 ) {
854 for (id, binders) in &mut self.layers {
855 let pattern = patterns.and_then(|patterns| patterns.get(id));
856 binders.populate(feature, length, index, positions, pattern, canonical, world, section);
857 }
858 }
859}
860
861#[macro_export]
866macro_rules! paint_property_binders {
867 (
868 $(#[$meta:meta])*
869 pub struct $name:ident for $props:path {
870 $($field:ident: $binder:ty => [$($attribute:expr),+]),+ $(,)?
871 }
872 ) => {
873 $(#[$meta])*
874 #[derive(Clone, Debug, $crate::__private::mln_wire::Wire)]
875 #[wire(crate = $crate::__private::mln_wire)]
876 pub(crate) struct $name {
877 pub interleaved_vertex_buffer: $crate::layer::binders::InterleavedVertexBuffer,
878 $(pub $field: $binder,)+
879 }
880
881 impl $crate::layer::binders::PaintBinders for $name {
882 type Paint = $props;
883
884 fn new(properties: &$props, z: f32) -> Self {
885 let mut result = $name {
886 interleaved_vertex_buffer: Default::default(),
887 $($field: <$binder>::create(&properties.$field, z),)+
888 };
889 $($crate::layer::binders::PaintPropertyBinderBase::set_interleaved(
890 &mut result.$field, &mut result.interleaved_vertex_buffer);)+
891 result
892 }
893
894 fn vertices_mut(&mut self) -> &mut $crate::layer::binders::InterleavedVertexBuffer {
895 &mut self.interleaved_vertex_buffer
896 }
897
898 fn populate(
899 &mut self,
900 feature: &dyn $crate::__private::mln_style::feature::GeometryTileFeature,
901 length: usize,
902 index: usize,
903 pattern_positions: &$crate::text::atlas::ImagePositions,
904 pattern_dependencies: Option<&$crate::layer::binders::PatternDependency>,
905 canonical: &$crate::__private::mln_style::tile_id::CanonicalTileID,
906 world: &$crate::__private::mln_style::crs::WorldMapping,
907 formatted_section: &$crate::__private::mln_style::expression::Value,
908 ) {
909 let buffer = &mut self.interleaved_vertex_buffer;
910 let added = (length - buffer.vertex_count) * buffer.stride;
911 let data = buffer.shared_vertex_vector.get_mut();
912 data.resize(data.len() + added, 0);
913
914 $($crate::layer::binders::PaintPropertyBinderBase::populate(
915 &mut self.$field,
916 &mut self.interleaved_vertex_buffer,
917 feature,
918 length,
919 index,
920 pattern_positions,
921 pattern_dependencies,
922 canonical,
923 world,
924 formatted_section,
925 );)+
926
927 let buffer = &mut self.interleaved_vertex_buffer;
928 buffer.vertex_count += length - buffer.vertex_count;
929 }
931
932 fn feature_state(
933 &mut self,
934 states: &$crate::layer::bucket::FeatureStates,
935 layer: &$crate::tile::TileLayer<'_>,
936 ) {
937 if self.interleaved_vertex_buffer.shared_vertex_vector.is_moved() {
940 return;
941 }
942 $($crate::layer::binders::PaintPropertyBinderBase::update_vectors(
943 &mut self.$field, &mut self.interleaved_vertex_buffer, states, layer);)+
944 }
945
946 fn depends_on_feature_state(&self) -> bool {
947 false $(|| $crate::layer::binders::PaintPropertyBinderBase::depends_on_feature_state(
948 &self.$field))+
949 }
950 }
951
952 impl $name {
953 pub(crate) fn paint(
957 &self,
958 evaluated: &$props,
959 vertices: Option<&$crate::draw::VertexBuffer>,
960 ) -> $crate::layer::binders::PaintAttributes {
961 let mut read = Vec::new();
962 let mut uniforms = $crate::draw::Uniforms::default();
963 $($crate::layer::binders::bind_paint_property(
964 &self.$field,
965 &self.interleaved_vertex_buffer,
966 &[$($attribute),+],
967 evaluated.$field.is_constant(),
968 &mut read,
969 &mut uniforms,
970 );)+
971 $crate::layer::binders::paint_attributes(&self.interleaved_vertex_buffer, vertices, read, uniforms)
972 }
973 }
974 };
975}
976
977#[derive(Clone, Debug, Default, PartialEq, Eq)]
980pub struct PatternDependency {
981 pub min: String,
982 pub mid: String,
983 pub max: String,
984}
985
986pub type PatternLayerMap = mln_style::hash::HashMap<String, PatternDependency>;