Skip to main content

mln_engine/layer/
paint_property_binder.rs

1// The binders of a layer's data-driven paint properties, which write each
2// feature's values into the vertices its draws read: `PaintPropertyBinder<T>`
3// for a constant, source or composite function, and
4// `CrossFadedPaintPropertyBinder<T>` for the cross-faded (pattern) ones.
5// `paint_property_binders!` declares a layer type's set of them.
6//
7// The binders write into the bucket's `InterleavedVertexBuffer`, which is
8// passed in, in the vertices' in-memory layout (native-endian floats and
9// u16s), so the buffer is the GPU vertex data as it uploads.
10
11use mln_gfx::gfx_types::AttributeDataType;
12use mln_style::collections::VecMap;
13use mln_style::color::Color;
14use mln_style::expression::{Dependency, EvaluationContext, Image, Value, ValueConverter};
15use mln_style::feature::GeometryTileFeature;
16use mln_style::property::evaluated::{Evaluated, Faded};
17use mln_style::property::expression::PropertyExpression;
18use mln_style::range::Range;
19use mln_style::tile_id::CanonicalTileID;
20
21use crate::draw::vertex::{VertexAttribute, VertexBinding};
22use crate::draw::vertex_attribute::Uniforms;
23use crate::draw::vertices::VertexBuffer;
24use crate::layer::bucket_geometry::GeometryVec;
25use crate::layer::paint_property_statistics::{PaintPropertyStatistics, StatisticValue};
26use crate::text::atlas::ImagePositions;
27use crate::tile::TileLayer;
28use crate::tile::feature::feature_id_to_string;
29
30/// Maps vertex range to feature index.
31#[derive(Clone, Copy, Debug, PartialEq, Eq, mln_wire::Wire)]
32pub(crate) struct FeatureVertexRange {
33    pub(crate) feature_index: usize,
34    pub(crate) start: usize,
35    pub(crate) end: usize,
36}
37
38pub(crate) type FeatureVertexRangeMap = VecMap<String, Vec<FeatureVertexRange>>;
39
40/// The data-driven attribute values of all the binders of one
41/// `paint_property_binders!` struct, one interleaved vertex per layout
42/// vertex.
43#[derive(Clone, Debug, Default, PartialEq, mln_wire::Wire)]
44pub struct InterleavedVertexBuffer {
45    pub stride: usize,
46    pub vertex_count: usize,
47    pub shared_vertex_vector: GeometryVec<u8>,
48}
49
50impl InterleavedVertexBuffer {
51    /// Writes `value` at `offset` in each of the vertices `indexes`.
52    pub fn fill(&mut self, indexes: std::ops::Range<usize>, offset: usize, value: &[u8]) {
53        // Taking the vertices copies a worker's buffer into wasm memory.
54        if indexes.is_empty() {
55            return;
56        }
57        let stride = self.stride;
58        let data = self.shared_vertex_vector.get_mut();
59        for index in indexes {
60            let start = stride * index + offset;
61            debug_assert!(start + value.len() <= data.len());
62            data[start..start + value.len()].copy_from_slice(value);
63        }
64    }
65
66    /// Appends a field of `size` bytes, aligned to `alignment`, to the vertex
67    /// format and returns its offset.
68    pub fn extend_vertex_format(&mut self, size: usize, alignment: usize) -> usize {
69        let mut offset = self.stride & (alignment - 1);
70        if offset != 0 {
71            offset = alignment - offset;
72        }
73
74        let vertex_offset = self.stride + offset;
75        self.stride += size + offset;
76
77        vertex_offset
78    }
79}
80
81/// The value types of data-driven paint properties with a single attribute
82/// (`float` and `Color` in circle, fill and line): the attribute's value of
83/// a value ([`attribute_value`](Self::attribute_value)), and its type.
84pub trait BinderValue: Clone + Default + ValueConverter + StatisticValue + std::fmt::Debug {
85    /// The number of floats `attribute_value` uses.
86    const DIMENSIONS: usize;
87    /// The attribute's type for a value that doesn't change with the zoom.
88    const BASE_DATA_TYPE: AttributeDataType;
89    /// The attribute's type for a value interpolated between two zooms.
90    const INTERPOLATED_DATA_TYPE: AttributeDataType;
91
92    /// The attribute's floats; only the first `DIMENSIONS` entries are used.
93    fn attribute_value(&self) -> [f32; 2];
94}
95
96impl BinderValue for f32 {
97    const DIMENSIONS: usize = 1;
98    const BASE_DATA_TYPE: AttributeDataType = AttributeDataType::Float;
99    const INTERPOLATED_DATA_TYPE: AttributeDataType = AttributeDataType::Float2;
100
101    fn attribute_value(&self) -> [f32; 2] {
102        [*self, 0.0]
103    }
104}
105
106/// Packs two values into a `u16`: `a as u16 * 256 + b as u16`, computed as an
107/// `i32` and truncated.
108fn pack_uint8_pair(a: f32, b: f32) -> u16 {
109    (i32::from(a as u16) * 256 + i32::from(b as u16)) as u16
110}
111
112impl BinderValue for Color {
113    const DIMENSIONS: usize = 2;
114    const BASE_DATA_TYPE: AttributeDataType = AttributeDataType::Float2;
115    const INTERPOLATED_DATA_TYPE: AttributeDataType = AttributeDataType::Float4;
116
117    /// Encode a four-component color value into a pair of floats, with 8
118    /// bits for each component: for each float we use the upper 8 bits for
119    /// one component (e.g. (color.r * 255) * 256), and the lower 8 for
120    /// another.
121    ///
122    /// Also note that colors come in as floats 0..1, so we scale by 255.
123    fn attribute_value(&self) -> [f32; 2] {
124        [
125            f32::from(pack_uint8_pair(255.0 * self.r, 255.0 * self.g)),
126            f32::from(pack_uint8_pair(255.0 * self.b, 255.0 * self.a)),
127        ]
128    }
129}
130
131/// The attribute values of a property that the shader interpolates between
132/// `min` and `max`, its values at the zoom stops: `min`'s, then `max`'s, in
133/// the first `2 * T::DIMENSIONS` floats.
134fn zoom_stop_values<T: BinderValue>(min: &T, max: &T) -> [f32; 4] {
135    let mut values = [0.0; 4];
136    values[..T::DIMENSIONS].copy_from_slice(&min.attribute_value()[..T::DIMENSIONS]);
137    values[T::DIMENSIONS..2 * T::DIMENSIONS].copy_from_slice(&max.attribute_value()[..T::DIMENSIONS]);
138    values
139}
140
141/// The data of a `PaintPropertyBinder` subclass.
142#[derive(Clone, Debug, mln_wire::Wire)]
143pub(crate) enum PaintPropertyBinderKind<T> {
144    Constant {
145        constant: T,
146    },
147    SourceFunction {
148        expression: PropertyExpression<T>,
149        default_value: T,
150        feature_map: FeatureVertexRangeMap,
151        vertex_data: InterleavedVertexData,
152    },
153    CompositeFunction {
154        expression: PropertyExpression<T>,
155        default_value: T,
156        zoom_range: Range<f32>,
157        feature_map: FeatureVertexRangeMap,
158        vertex_data: InterleavedVertexData,
159    },
160}
161
162/// Where a binder's values are in the interleaved vertex: not yet placed,
163/// or at a byte offset.
164#[derive(Clone, Debug, mln_wire::Wire, PartialEq, Eq)]
165pub enum InterleavedVertexData {
166    Uninitialized,
167    Interleaved { offset: usize },
168}
169
170impl InterleavedVertexData {
171    /// The byte offset of the values, once they are placed.
172    #[must_use]
173    pub fn offset(&self) -> Option<usize> {
174        match self {
175            Self::Uninitialized => None,
176            Self::Interleaved { offset } => Some(*offset),
177        }
178    }
179}
180
181impl<T: BinderValue> PaintPropertyBinderKind<T> {
182    fn vertex_offset(&self) -> Option<usize> {
183        match self {
184            Self::Constant { .. } => None,
185            Self::SourceFunction { vertex_data, .. } | Self::CompositeFunction { vertex_data, .. } => {
186                vertex_data.offset()
187            }
188        }
189    }
190
191    fn update_vertex_vector(
192        &self,
193        statistics: &mut PaintPropertyStatistics<T>,
194        buffer: &mut InterleavedVertexBuffer,
195        vertex_offset: usize,
196        range: &FeatureVertexRange,
197        feature: &dyn GeometryTileFeature,
198        state: &mln_style::feature::FeatureState,
199    ) {
200        match self {
201            Self::Constant { .. } => {}
202            Self::SourceFunction { expression, default_value, .. } => {
203                let evaluated = expression.evaluate(
204                    &EvaluationContext::from_feature(Some(feature)).with_feature_state(Some(state)),
205                    default_value.clone(),
206                );
207                statistics.add(&evaluated);
208                let value = evaluated.attribute_value();
209                buffer.fill(range.start..range.end, vertex_offset, bytemuck::cast_slice(&value[..T::DIMENSIONS]));
210            }
211            Self::CompositeFunction { expression, default_value, zoom_range, .. } => {
212                let min = expression.evaluate(
213                    &EvaluationContext::with_zoom_feature_state(zoom_range.min, Some(feature), Some(state)),
214                    default_value.clone(),
215                );
216                let max = expression.evaluate(
217                    &EvaluationContext::with_zoom_feature_state(zoom_range.max, Some(feature), Some(state)),
218                    default_value.clone(),
219                );
220                statistics.add(&min);
221                statistics.add(&max);
222                let value = zoom_stop_values(&min, &max);
223                buffer.fill(range.start..range.end, vertex_offset, bytemuck::cast_slice(&value[..2 * T::DIMENSIONS]));
224            }
225        }
226    }
227}
228
229/// The binder of a data-driven paint property of a single attribute: its
230/// constant, or each feature's value, or each feature's values at the two
231/// zooms its expression interpolates between, in the bucket's interleaved
232/// vertices, with their statistics.
233#[derive(Clone, Debug, mln_wire::Wire)]
234pub struct PaintPropertyBinder<T> {
235    pub(crate) kind: PaintPropertyBinderKind<T>,
236    pub statistics: PaintPropertyStatistics<T>,
237}
238
239impl<T: BinderValue> PaintPropertyBinder<T> {
240    /// The binder of `value`, a property evaluated for a tile at `zoom`.
241    pub fn create(value: &Evaluated<T>, zoom: f32) -> Self {
242        let kind = match value {
243            Evaluated::Constant(constant) | Evaluated::CrossFaded(Faded { to: constant, .. }) => {
244                PaintPropertyBinderKind::Constant { constant: constant.clone() }
245            }
246            Evaluated::PerFeature { expression, default } => {
247                let default_value = default.clone();
248                if expression.is_zoom_constant() {
249                    PaintPropertyBinderKind::SourceFunction {
250                        expression: expression.clone(),
251                        default_value,
252                        feature_map: FeatureVertexRangeMap::new(),
253                        vertex_data: InterleavedVertexData::Uninitialized,
254                    }
255                } else {
256                    PaintPropertyBinderKind::CompositeFunction {
257                        expression: expression.clone(),
258                        default_value,
259                        zoom_range: Range::new(zoom, zoom + 1.0),
260                        feature_map: FeatureVertexRangeMap::new(),
261                        vertex_data: InterleavedVertexData::Uninitialized,
262                    }
263                }
264            }
265        };
266        PaintPropertyBinder { kind, statistics: PaintPropertyStatistics::default() }
267    }
268
269    /// The size in bytes of the zoom-interpolated vertex: `2 * DIMENSIONS`
270    /// floats.
271    fn zoom_interpolated_size() -> usize {
272        2 * T::DIMENSIONS * 4
273    }
274
275    /// Adds the binder's zoom-interpolated vertex to the vertex format. The
276    /// constant binder has no vertex data and does nothing.
277    pub(crate) fn set_interleaved_buffer(&mut self, buffer: &mut InterleavedVertexBuffer) {
278        let vertex_data = match &mut self.kind {
279            PaintPropertyBinderKind::Constant { .. } => return,
280            PaintPropertyBinderKind::SourceFunction { vertex_data, .. }
281            | PaintPropertyBinderKind::CompositeFunction { vertex_data, .. } => vertex_data,
282        };
283        let new_vertex_offset = buffer.extend_vertex_format(Self::zoom_interpolated_size(), align_of::<f32>());
284        if matches!(vertex_data, InterleavedVertexData::Uninitialized) {
285            *vertex_data = InterleavedVertexData::Interleaved { offset: new_vertex_offset };
286        }
287    }
288
289    pub(crate) fn vertex_count(&self, buffer: &InterleavedVertexBuffer) -> usize {
290        if self.kind.vertex_offset().is_some() { buffer.vertex_count } else { 0 }
291    }
292
293    pub(crate) fn is_interpolated(&self) -> bool {
294        matches!(self.kind, PaintPropertyBinderKind::CompositeFunction { .. })
295    }
296
297    pub(crate) fn populate_vertex_vector(
298        &mut self,
299        buffer: &mut InterleavedVertexBuffer,
300        feature: &dyn GeometryTileFeature,
301        length: usize,
302        index: usize,
303        canonical: &CanonicalTileID,
304        formatted_section: &Value,
305    ) {
306        let Some(vertex_offset) = self.kind.vertex_offset() else { return };
307        let elements = self.vertex_count(buffer);
308        match &mut self.kind {
309            PaintPropertyBinderKind::Constant { .. } => {}
310            PaintPropertyBinderKind::SourceFunction { expression, default_value, feature_map, .. } => {
311                let evaluated = expression.evaluate(
312                    &EvaluationContext::from_feature(Some(feature))
313                        .with_formatted_section(Some(formatted_section))
314                        .with_canonical_tile_id(Some(canonical)),
315                    default_value.clone(),
316                );
317                self.statistics.add(&evaluated);
318                let value = evaluated.attribute_value();
319                // The base attribute only.
320                buffer.fill(elements..length, vertex_offset, bytemuck::cast_slice(&value[..T::DIMENSIONS]));
321                if let Some(id_str) = feature_id_to_string(&feature.get_id()) {
322                    feature_map.entry(id_str).or_default().push(FeatureVertexRange {
323                        feature_index: index,
324                        start: elements,
325                        end: length,
326                    });
327                }
328            }
329            PaintPropertyBinderKind::CompositeFunction {
330                expression, default_value, zoom_range, feature_map, ..
331            } => {
332                let min = expression.evaluate(
333                    &EvaluationContext::with_zoom_feature(zoom_range.min, Some(feature))
334                        .with_formatted_section(Some(formatted_section))
335                        .with_canonical_tile_id(Some(canonical)),
336                    default_value.clone(),
337                );
338                let max = expression.evaluate(
339                    &EvaluationContext::with_zoom_feature(zoom_range.max, Some(feature))
340                        .with_formatted_section(Some(formatted_section))
341                        .with_canonical_tile_id(Some(canonical)),
342                    default_value.clone(),
343                );
344                self.statistics.add(&min);
345                self.statistics.add(&max);
346                let value = zoom_stop_values(&min, &max);
347                buffer.fill(elements..length, vertex_offset, bytemuck::cast_slice(&value[..2 * T::DIMENSIONS]));
348                if let Some(id_str) = feature_id_to_string(&feature.get_id()) {
349                    feature_map.entry(id_str).or_default().push(FeatureVertexRange {
350                        feature_index: index,
351                        start: elements,
352                        end: length,
353                    });
354                }
355            }
356        }
357    }
358
359    pub(crate) fn update_vertex_vectors(
360        &mut self,
361        buffer: &mut InterleavedVertexBuffer,
362        states: &crate::layer::bucket::FeatureStates,
363        layer: &TileLayer<'_>,
364    ) {
365        let Self { kind, statistics } = self;
366        let (feature_map, vertex_data) = match &*kind {
367            PaintPropertyBinderKind::Constant { .. } => return,
368            PaintPropertyBinderKind::SourceFunction { feature_map, vertex_data, .. }
369            | PaintPropertyBinderKind::CompositeFunction { feature_map, vertex_data, .. } => (feature_map, vertex_data),
370        };
371        let Some(vertex_offset) = vertex_data.offset() else {
372            return;
373        };
374        for (id, state) in states {
375            let Some(positions) = feature_map.get(id) else {
376                continue;
377            };
378            for pos in positions {
379                // The worker read the feature from the same data, so it
380                // can be read again.
381                let Ok(feature) = layer.feature(pos.feature_index) else {
382                    continue;
383                };
384                kind.update_vertex_vector(statistics, buffer, vertex_offset, pos, &feature, state);
385            }
386        }
387    }
388
389    /// The factor that interpolates between the vertex's two zoom stops; 0
390    /// unless the binder is a composite function.
391    pub fn interpolation_factor(&self, current_zoom: f32) -> f32 {
392        match &self.kind {
393            PaintPropertyBinderKind::Constant { .. } | PaintPropertyBinderKind::SourceFunction { .. } => 0.0,
394            PaintPropertyBinderKind::CompositeFunction { expression, zoom_range, .. } => {
395                let possibly_rounded_zoom =
396                    if expression.get_use_integer_zoom() { current_zoom.floor() } else { current_zoom };
397
398                mln_style::math::fmaxf(
399                    0.0,
400                    mln_style::math::fminf(1.0, expression.interpolation_factor(*zoom_range, possibly_rounded_zoom)),
401                )
402            }
403        }
404    }
405
406    /// Where the property's attribute reads its values in `shared`, the
407    /// vertices of `buffer`; `None` without values.
408    pub(crate) fn apply_paint_property(&self, buffer: &InterleavedVertexBuffer) -> Option<(AttributeDataType, u32)> {
409        if let Some(vertex_offset) = self.kind.vertex_offset() {
410            let data_type = if self.is_interpolated() { T::INTERPOLATED_DATA_TYPE } else { T::BASE_DATA_TYPE };
411            Some((data_type, vertex_offset as u32))
412        } else {
413            // Without an interleaved buffer there are no vertices to read.
414            debug_assert_eq!(self.vertex_count(buffer), 0);
415            None
416        }
417    }
418}
419
420/// The data of a cross-faded `PaintPropertyBinder` subclass.
421#[derive(Clone, Debug, mln_wire::Wire)]
422pub(crate) enum CrossFadedPaintPropertyBinderKind<T> {
423    Constant {
424        constant: Faded<T>,
425    },
426    Composite {
427        expression: PropertyExpression<T>,
428        default_value: T,
429        zoom_range: Range<f32>,
430        vertex_data: InterleavedVertexData,
431        /// The number of vertices `populate_vertex_vector` has written. It
432        /// lags the buffer's count when a feature's patterns are missing,
433        /// so the next feature's pattern also covers those vertices.
434        #[wire(skip)]
435        populated_count: usize,
436    },
437}
438
439impl<T> CrossFadedPaintPropertyBinderKind<T> {
440    fn vertex_offset(&self) -> Option<usize> {
441        match self {
442            Self::Constant { .. } => None,
443            Self::Composite { vertex_data, .. } => vertex_data.offset(),
444        }
445    }
446}
447
448/// The binder of a `*-pattern` property, whose two attributes are four `u16`s
449/// each.
450#[derive(Clone, Debug, mln_wire::Wire)]
451pub struct CrossFadedPaintPropertyBinder<T> {
452    pub(crate) kind: CrossFadedPaintPropertyBinderKind<T>,
453}
454
455/// The size of a zoom-interpolated pattern vertex: eight `u16`s.
456const PATTERN_ZOOM_INTERPOLATED_SIZE: usize = 16;
457
458impl CrossFadedPaintPropertyBinder<Image> {
459    /// The binder of `value`, a pattern property evaluated for a tile at
460    /// `zoom`.
461    #[must_use]
462    pub fn create(value: &Evaluated<Image>, zoom: f32) -> Self {
463        let kind = match value {
464            Evaluated::Constant(constant) => CrossFadedPaintPropertyBinderKind::Constant {
465                constant: Faded { from: constant.clone(), to: constant.clone() },
466            },
467            Evaluated::CrossFaded(constant) => {
468                CrossFadedPaintPropertyBinderKind::Constant { constant: constant.clone() }
469            }
470            Evaluated::PerFeature { expression, default } => CrossFadedPaintPropertyBinderKind::Composite {
471                expression: expression.clone(),
472                default_value: default.clone(),
473                zoom_range: Range::new(zoom, zoom + 1.0),
474                vertex_data: InterleavedVertexData::Uninitialized,
475                populated_count: 0,
476            },
477        };
478        CrossFadedPaintPropertyBinder { kind }
479    }
480
481    /// Adds the binder's vertex data to the vertex format; only the composite
482    /// binder has any.
483    pub(crate) fn set_interleaved_buffer(&mut self, buffer: &mut InterleavedVertexBuffer) {
484        let CrossFadedPaintPropertyBinderKind::Composite { vertex_data, .. } = &mut self.kind else {
485            return;
486        };
487        let new_vertex_offset = buffer.extend_vertex_format(PATTERN_ZOOM_INTERPOLATED_SIZE, align_of::<u16>());
488        if matches!(vertex_data, InterleavedVertexData::Uninitialized) {
489            *vertex_data = InterleavedVertexData::Interleaved { offset: new_vertex_offset };
490        }
491    }
492
493    pub(crate) fn vertex_count(&self, buffer: &InterleavedVertexBuffer) -> usize {
494        if self.kind.vertex_offset().is_some() { buffer.vertex_count } else { 0 }
495    }
496
497    pub(crate) fn populate_vertex_vector(
498        &mut self,
499        buffer: &mut InterleavedVertexBuffer,
500        length: usize,
501        pattern_positions: &ImagePositions,
502        pattern_dependencies: Option<&PatternDependency>,
503    ) {
504        let CrossFadedPaintPropertyBinderKind::Composite { populated_count, vertex_data, .. } = &mut self.kind else {
505            return;
506        };
507        let InterleavedVertexData::Interleaved { offset: vertex_offset } = vertex_data else {
508            return;
509        };
510        match pattern_dependencies {
511            Some(dependencies) if !dependencies.mid.is_empty() => {
512                if !pattern_positions.is_empty() {
513                    // Only the middle pattern reaches the GPU, but a feature
514                    // needs all three.
515                    let (Some(_), Some(image_mid), Some(_)) = (
516                        pattern_positions.get(&dependencies.min),
517                        pattern_positions.get(&dependencies.mid),
518                        pattern_positions.get(&dependencies.max),
519                    ) else {
520                        return;
521                    };
522
523                    buffer.fill(*populated_count..length, *vertex_offset, bytemuck::cast_slice(&image_mid.tlbr()));
524                    *populated_count = (*populated_count).max(length);
525                }
526            }
527            _ => {
528                // Unlike other properties with expressions that evaluate to
529                // null, the default value for `*-pattern` properties is an
530                // empty string and will not have a valid entry in the
531                // pattern positions. We still need to populate the attribute
532                // buffers to avoid crashes when we try to draw the layer
533                // because we don't know at draw time if all features were
534                // evaluated to valid pattern dependencies.
535                buffer.fill(*populated_count..length, *vertex_offset, bytemuck::cast_slice(&[0u16; 4]));
536                *populated_count = (*populated_count).max(length);
537            }
538        }
539    }
540
541    /// The zoom interpolation factors, always (0, 0) for pattern binders.
542    #[must_use]
543    pub fn interpolation_factor(&self, _current_zoom: f32) -> (f32, f32) {
544        (0.0, 0.0)
545    }
546
547    /// Where the property's attributes read the pattern values in `shared`,
548    /// the vertices of `buffer`: both read the same values. `None` without
549    /// values.
550    pub(crate) fn apply_paint_property(&self) -> Option<(AttributeDataType, u32)> {
551        self.kind.vertex_offset().map(|vertex_offset| (AttributeDataType::UShort4, vertex_offset as u32))
552    }
553}
554
555/// What a layer's set of binders and [`bind_paint_property`] do
556/// with either binder enum.
557pub trait PaintPropertyBinderBase {
558    /// Places the binder's values in `buffer`'s interleaved vertex.
559    fn set_interleaved(&mut self, buffer: &mut InterleavedVertexBuffer);
560    #[expect(
561        clippy::too_many_arguments,
562        reason = "the vertex buffer, the feature and its index range, its patterns, the tile and the formatted section that evaluate a property"
563    )]
564    /// Writes the values of `feature`, the feature at `index`, into `buffer`
565    /// for the vertices up to `length`.
566    fn populate(
567        &mut self,
568        buffer: &mut InterleavedVertexBuffer,
569        feature: &dyn GeometryTileFeature,
570        length: usize,
571        index: usize,
572        pattern_positions: &ImagePositions,
573        pattern_dependencies: Option<&PatternDependency>,
574        canonical: &CanonicalTileID,
575        formatted_section: &Value,
576    );
577    /// Rewrites the vertex data that depends on feature state. The default,
578    /// for the constant and cross-faded binders, does nothing.
579    fn update_vectors(
580        &mut self,
581        _buffer: &mut InterleavedVertexBuffer,
582        _states: &crate::layer::bucket::FeatureStates,
583        _layer: &TileLayer<'_>,
584    ) {
585    }
586    /// True if a feature state change rewrites this binder's vertex data.
587    fn depends_on_feature_state(&self) -> bool {
588        false
589    }
590    /// The number of vertices whose values `buffer` holds for the binder.
591    fn binder_vertex_count(&self, buffer: &InterleavedVertexBuffer) -> usize;
592    /// How an attribute reads the binder's values in a vertex of `buffer`:
593    /// its format and offset; `None` for a constant.
594    fn attribute(&self, buffer: &InterleavedVertexBuffer) -> Option<(AttributeDataType, u32)>;
595}
596
597impl<T: BinderValue> PaintPropertyBinderBase for PaintPropertyBinder<T> {
598    fn set_interleaved(&mut self, buffer: &mut InterleavedVertexBuffer) {
599        self.set_interleaved_buffer(buffer);
600    }
601    /// Writes the values of `feature`, the feature at `index`, into `buffer`
602    /// for the vertices up to `length`.
603    fn populate(
604        &mut self,
605        buffer: &mut InterleavedVertexBuffer,
606        feature: &dyn GeometryTileFeature,
607        length: usize,
608        index: usize,
609        _pattern_positions: &ImagePositions,
610        _pattern_dependencies: Option<&PatternDependency>,
611        canonical: &CanonicalTileID,
612        formatted_section: &Value,
613    ) {
614        self.populate_vertex_vector(buffer, feature, length, index, canonical, formatted_section);
615    }
616    fn update_vectors(
617        &mut self,
618        buffer: &mut InterleavedVertexBuffer,
619        states: &crate::layer::bucket::FeatureStates,
620        layer: &TileLayer<'_>,
621    ) {
622        self.update_vertex_vectors(buffer, states, layer);
623    }
624    fn depends_on_feature_state(&self) -> bool {
625        match &self.kind {
626            PaintPropertyBinderKind::Constant { .. } => false,
627            PaintPropertyBinderKind::SourceFunction { expression, .. }
628            | PaintPropertyBinderKind::CompositeFunction { expression, .. } => {
629                expression.get_expression().has(Dependency::FEATURE_STATE)
630            }
631        }
632    }
633    fn binder_vertex_count(&self, buffer: &InterleavedVertexBuffer) -> usize {
634        self.vertex_count(buffer)
635    }
636    fn attribute(&self, buffer: &InterleavedVertexBuffer) -> Option<(AttributeDataType, u32)> {
637        self.apply_paint_property(buffer)
638    }
639}
640
641impl PaintPropertyBinderBase for CrossFadedPaintPropertyBinder<Image> {
642    fn set_interleaved(&mut self, buffer: &mut InterleavedVertexBuffer) {
643        self.set_interleaved_buffer(buffer);
644    }
645    /// Writes the values of `feature`, the feature at `index`, into `buffer`
646    /// for the vertices up to `length`.
647    fn populate(
648        &mut self,
649        buffer: &mut InterleavedVertexBuffer,
650        _feature: &dyn GeometryTileFeature,
651        length: usize,
652        _index: usize,
653        pattern_positions: &ImagePositions,
654        pattern_dependencies: Option<&PatternDependency>,
655        _canonical: &CanonicalTileID,
656        _formatted_section: &Value,
657    ) {
658        self.populate_vertex_vector(buffer, length, pattern_positions, pattern_dependencies);
659    }
660    fn binder_vertex_count(&self, buffer: &InterleavedVertexBuffer) -> usize {
661        self.vertex_count(buffer)
662    }
663    fn attribute(&self, _buffer: &InterleavedVertexBuffer) -> Option<(AttributeDataType, u32)> {
664        self.apply_paint_property()
665    }
666}
667
668/// How a program reads a layer's data-driven paint values ([`PaintBinders`]):
669/// the vertices of the values it reads as attributes, and the properties it
670/// reads from uniforms instead, which pick its variant
671/// ([`Resources::shader_key`](crate::draw::Resources::shader_key)).
672#[derive(Clone, Debug, Default)]
673pub struct PaintAttributes {
674    /// The values' vertices, which a mesh reads beside its own
675    /// ([`MeshDesc::vertices`](crate::draw::MeshDesc::vertices), or
676    /// `instances` for a draw of instances); `None` where it reads none.
677    pub vertices: Option<VertexBinding>,
678    pub uniforms: Uniforms,
679}
680
681/// Adds `binder`'s values in `buffer`, the interleaved vertex of the paint
682/// values, as the attributes `attributes` to `read`, or records the
683/// properties of those names in `uniforms` where the property is constant
684/// or has no values.
685pub fn bind_paint_property(
686    binder: &dyn PaintPropertyBinderBase,
687    buffer: &InterleavedVertexBuffer,
688    attributes: &[&'static str],
689    is_constant: bool,
690    read: &mut Vec<VertexAttribute>,
691    uniforms: &mut Uniforms,
692) {
693    if is_constant || binder.binder_vertex_count(buffer) == 0 {
694        for &attribute in attributes {
695            uniforms.insert(attribute);
696        }
697    } else if let Some((format, offset)) = binder.attribute(buffer) {
698        read.extend(attributes.iter().map(|&name| VertexAttribute { name, format, offset }));
699    }
700}
701
702/// The attributes `read` of `vertices`, the vertices of `buffer`, and
703/// `uniforms`: what a layer's set of binders binds.
704#[must_use]
705pub fn paint_attributes(
706    buffer: &InterleavedVertexBuffer,
707    vertices: Option<&VertexBuffer>,
708    read: Vec<VertexAttribute>,
709    uniforms: Uniforms,
710) -> PaintAttributes {
711    let vertices = vertices.filter(|_| !read.is_empty()).map(|vertices| {
712        debug_assert_eq!(vertices.count() / buffer.stride.max(1), buffer.vertex_count);
713        VertexBinding::new(vertices, buffer.stride as u32, read)
714    });
715    PaintAttributes { vertices, uniforms }
716}
717
718/// A layer type's binders of its data-driven paint properties, one per
719/// property, sharing one [`InterleavedVertexBuffer`]: what
720/// `paint_property_binders!` declares.
721pub trait PaintBinders: Clone + Send + mln_wire::Wire + 'static {
722    /// The evaluated paint values whose data-driven properties the binders
723    /// write.
724    type Paint: 'static;
725
726    /// The binders of `paint` in a tile at `zoom`.
727    fn new(paint: &Self::Paint, zoom: f32) -> Self;
728
729    /// The values, one interleaved vertex per vertex of the bucket.
730    fn vertices_mut(&mut self) -> &mut InterleavedVertexBuffer;
731
732    /// Writes the values of `feature`, the feature at `index` of the tile
733    /// `canonical`, in its text's formatted section `section`, with the
734    /// images of its patterns `pattern` among `positions`, into the
735    /// vertices up to `length`.
736    #[expect(clippy::too_many_arguments, reason = "the feature, its vertices, its tile, its section and its patterns")]
737    fn populate(
738        &mut self,
739        feature: &dyn GeometryTileFeature,
740        length: usize,
741        index: usize,
742        positions: &ImagePositions,
743        pattern: Option<&PatternDependency>,
744        canonical: &CanonicalTileID,
745        section: &Value,
746    );
747
748    /// Rewrites the values that read feature state for `states`, the states
749    /// of the features of `layer`.
750    fn feature_state(&mut self, states: &crate::layer::bucket::FeatureStates, layer: &TileLayer<'_>);
751
752    /// Whether a feature state change rewrites the values.
753    fn depends_on_feature_state(&self) -> bool;
754}
755
756/// A set of binders `P` for each layer of a layout's group, which their
757/// bucket holds.
758#[derive(Clone, Debug, mln_wire::Wire)]
759#[wire(bound = "P: mln_wire::Wire")]
760pub struct LayerBinders<P> {
761    /// Each layer's id and binders, in the group's order.
762    layers: Vec<(String, P)>,
763}
764
765impl<P> Default for LayerBinders<P> {
766    /// The binders of no layer.
767    fn default() -> Self {
768        LayerBinders { layers: Vec::new() }
769    }
770}
771
772impl<P> LayerBinders<P> {
773    /// The binders of the layer `id`, if it is one of the group's.
774    #[must_use]
775    pub fn get(&self, id: &str) -> Option<&P> {
776        self.layers.iter().find(|(layer, _)| layer == id).map(|(_, binders)| binders)
777    }
778
779    /// Each layer's binders.
780    pub fn values(&self) -> impl Iterator<Item = &P> {
781        self.layers.iter().map(|(_, binders)| binders)
782    }
783
784    /// Each layer's binders, to change.
785    pub fn values_mut(&mut self) -> impl Iterator<Item = &mut P> {
786        self.layers.iter_mut().map(|(_, binders)| binders)
787    }
788
789    /// Each layer's id and binders, to change.
790    pub(crate) fn iter_mut(&mut self) -> impl Iterator<Item = (&str, &mut P)> {
791        self.layers.iter_mut().map(|(id, binders)| (id.as_str(), binders))
792    }
793}
794
795impl<P: PaintBinders> LayerBinders<P> {
796    /// The binders of each of `layers`, the first of each id, of their
797    /// paint values at `zoom`.
798    pub fn new<T>(layers: &[std::sync::Arc<crate::layer::layer_type::EvaluatedLayer<T>>], zoom: f32) -> Self
799    where
800        T: mln_style::layer::StyleLayerType<PaintProperties: mln_style::layer::PaintSet<Evaluated = P::Paint>>,
801    {
802        let mut binders: Vec<(String, P)> = Vec::with_capacity(layers.len());
803        for layer in layers {
804            if !binders.iter().any(|(id, _)| *id == layer.style.id) {
805                binders.push((layer.style.id.clone(), P::new(&layer.paint, zoom)));
806            }
807        }
808        LayerBinders { layers: binders }
809    }
810
811    /// Writes `feature`'s values into each layer's binders, with each
812    /// layer's of `patterns` among `positions`, as [`PaintBinders::populate`]
813    /// does.
814    #[expect(clippy::too_many_arguments, reason = "the feature, its vertices, its tile, its section and its patterns")]
815    pub fn populate(
816        &mut self,
817        feature: &dyn GeometryTileFeature,
818        length: usize,
819        index: usize,
820        positions: &ImagePositions,
821        patterns: Option<&PatternLayerMap>,
822        canonical: &CanonicalTileID,
823        section: &Value,
824    ) {
825        for (id, binders) in &mut self.layers {
826            let pattern = patterns.and_then(|patterns| patterns.get(id));
827            binders.populate(feature, length, index, positions, pattern, canonical, section);
828        }
829    }
830}
831
832/// Declares the binders of one layer type's data-driven paint properties: a
833/// struct with one binder per property, each with the names of the attributes
834/// a program reads its values from (fields in the interleaved vertex order),
835/// and the shared `InterleavedVertexBuffer`, and its [`PaintBinders`].
836#[macro_export]
837macro_rules! paint_property_binders {
838    (
839        $(#[$meta:meta])*
840        pub struct $name:ident for $props:path {
841            $($field:ident: $binder:ty => [$($attribute:expr),+]),+ $(,)?
842        }
843    ) => {
844        $(#[$meta])*
845        #[derive(Clone, Debug, $crate::__private::mln_wire::Wire)]
846        #[wire(crate = $crate::__private::mln_wire)]
847        pub(crate) struct $name {
848            pub interleaved_vertex_buffer: $crate::layer::binders::InterleavedVertexBuffer,
849            $(pub $field: $binder,)+
850        }
851
852        impl $crate::layer::binders::PaintBinders for $name {
853            type Paint = $props;
854
855            fn new(properties: &$props, z: f32) -> Self {
856                let mut result = $name {
857                    interleaved_vertex_buffer: Default::default(),
858                    $($field: <$binder>::create(&properties.$field, z),)+
859                };
860                $($crate::layer::binders::PaintPropertyBinderBase::set_interleaved(
861                    &mut result.$field, &mut result.interleaved_vertex_buffer);)+
862                result
863            }
864
865            fn vertices_mut(&mut self) -> &mut $crate::layer::binders::InterleavedVertexBuffer {
866                &mut self.interleaved_vertex_buffer
867            }
868
869            fn populate(
870                &mut self,
871                feature: &dyn $crate::__private::mln_style::feature::GeometryTileFeature,
872                length: usize,
873                index: usize,
874                pattern_positions: &$crate::text::atlas::ImagePositions,
875                pattern_dependencies: Option<&$crate::layer::binders::PatternDependency>,
876                canonical: &$crate::__private::mln_style::tile_id::CanonicalTileID,
877                formatted_section: &$crate::__private::mln_style::expression::Value,
878            ) {
879                let buffer = &mut self.interleaved_vertex_buffer;
880                let added = (length - buffer.vertex_count) * buffer.stride;
881                let data = buffer.shared_vertex_vector.get_mut();
882                data.resize(data.len() + added, 0);
883
884                $($crate::layer::binders::PaintPropertyBinderBase::populate(
885                    &mut self.$field,
886                    &mut self.interleaved_vertex_buffer,
887                    feature,
888                    length,
889                    index,
890                    pattern_positions,
891                    pattern_dependencies,
892                    canonical,
893                    formatted_section,
894                );)+
895
896                let buffer = &mut self.interleaved_vertex_buffer;
897                buffer.vertex_count += length - buffer.vertex_count;
898                // The render thread copies the vector when it builds draws.
899            }
900
901            fn feature_state(
902                &mut self,
903                states: &$crate::layer::bucket::FeatureStates,
904                layer: &$crate::tile::TileLayer<'_>,
905            ) {
906                // Values that moved to the render thread don't depend on
907                // feature state (`depends_on_feature_state`).
908                if self.interleaved_vertex_buffer.shared_vertex_vector.is_moved() {
909                    return;
910                }
911                $($crate::layer::binders::PaintPropertyBinderBase::update_vectors(
912                    &mut self.$field, &mut self.interleaved_vertex_buffer, states, layer);)+
913            }
914
915            fn depends_on_feature_state(&self) -> bool {
916                false $(|| $crate::layer::binders::PaintPropertyBinderBase::depends_on_feature_state(
917                    &self.$field))+
918            }
919        }
920
921        impl $name {
922            /// How a program reads the values of `evaluated`'s data-driven
923            /// properties in `vertices`, the vertices of the paint values,
924            /// and which of the properties it reads from uniforms.
925            pub(crate) fn paint(
926                &self,
927                evaluated: &$props,
928                vertices: Option<&$crate::draw::VertexBuffer>,
929            ) -> $crate::layer::binders::PaintAttributes {
930                let mut read = Vec::new();
931                let mut uniforms = $crate::draw::Uniforms::default();
932                $($crate::layer::binders::bind_paint_property(
933                    &self.$field,
934                    &self.interleaved_vertex_buffer,
935                    &[$($attribute),+],
936                    evaluated.$field.is_constant(),
937                    &mut read,
938                    &mut uniforms,
939                );)+
940                $crate::layer::binders::paint_attributes(&self.interleaved_vertex_buffer, vertices, read, uniforms)
941            }
942        }
943    };
944}
945
946/// The images of a feature's pattern at the zooms its cross-fade reads: a
947/// pattern property's dependency, which its binder takes the positions of.
948#[derive(Clone, Debug, Default, PartialEq, Eq)]
949pub struct PatternDependency {
950    pub min: String,
951    pub mid: String,
952    pub max: String,
953}
954
955/// Each layer's [`PatternDependency`] of a feature, by layer id.
956pub type PatternLayerMap = mln_style::hash::HashMap<String, PatternDependency>;