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::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/// Maps vertex range to feature index.
32#[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/// The data-driven attribute values of all the binders of one
42/// `paint_property_binders!` struct, one interleaved vertex per layout
43/// vertex.
44#[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    /// Writes `value` at `offset` in each of the vertices `indexes`.
53    pub fn fill(&mut self, indexes: std::ops::Range<usize>, offset: usize, value: &[u8]) {
54        // Taking the vertices copies a worker's buffer into wasm memory.
55        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    /// Appends a field of `size` bytes, aligned to `alignment`, to the vertex
68    /// format and returns its offset.
69    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
82/// The value types of data-driven paint properties with a single attribute
83/// (`float` and `Color` in circle, fill and line): the attribute's value of
84/// a value ([`attribute_value`](Self::attribute_value)), and its type.
85pub trait BinderValue: Clone + Default + ValueConverter + StatisticValue + std::fmt::Debug {
86    /// The number of floats `attribute_value` uses.
87    const DIMENSIONS: usize;
88    /// The attribute's type for a value that doesn't change with the zoom.
89    const BASE_DATA_TYPE: AttributeDataType;
90    /// The attribute's type for a value interpolated between two zooms.
91    const INTERPOLATED_DATA_TYPE: AttributeDataType;
92
93    /// The attribute's floats; only the first `DIMENSIONS` entries are used.
94    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
107/// Packs two values into a `u16`: `a as u16 * 256 + b as u16`, computed as an
108/// `i32` and truncated.
109fn 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    /// Encode a four-component color value into a pair of floats, with 8
119    /// bits for each component: for each float we use the upper 8 bits for
120    /// one component (e.g. (color.r * 255) * 256), and the lower 8 for
121    /// another.
122    ///
123    /// Also note that colors come in as floats 0..1, so we scale by 255.
124    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
130/// The attribute values of a property that the shader interpolates between
131/// `min` and `max`, its values at the zoom stops: `min`'s, then `max`'s, in
132/// the first `2 * T::DIMENSIONS` floats.
133fn 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/// The data of a `PaintPropertyBinder` subclass.
141#[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/// Where a binder's values are in the interleaved vertex: not yet placed,
162/// or at a byte offset.
163#[derive(Clone, Debug, mln_wire::Wire, PartialEq, Eq)]
164pub enum InterleavedVertexData {
165    Uninitialized,
166    Interleaved { offset: usize },
167}
168
169impl InterleavedVertexData {
170    /// The byte offset of the values, once they are placed.
171    #[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/// The binder of a data-driven paint property of a single attribute: its
229/// constant, or each feature's value, or each feature's values at the two
230/// zooms its expression interpolates between, in the bucket's interleaved
231/// vertices, with their statistics.
232#[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    /// The binder of `value`, a property evaluated for a tile at `zoom`.
240    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    /// The size in bytes of the zoom-interpolated vertex: `2 * DIMENSIONS`
269    /// floats.
270    fn zoom_interpolated_size() -> usize {
271        2 * T::DIMENSIONS * 4
272    }
273
274    /// Adds the binder's zoom-interpolated vertex to the vertex format. The
275    /// constant binder has no vertex data and does nothing.
276    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    /// Writes the values of `feature`, the feature at `index`, into
297    /// `buffer` for the vertices up to `length`, evaluated with the feature
298    /// and `inputs`: its tile and world and the formatted section of its
299    /// text.
300    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                // The base attribute only.
318                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        // Only a feature state change rewrites the values, so only a binder
336        // that depends on feature state needs to find a feature's vertices.
337        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                // The worker read the feature from the same data, so it
369                // can be read again.
370                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    /// The factor that interpolates between the vertex's two zoom stops; 0
379    /// unless the binder is a composite function.
380    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    /// Where the property's attribute reads its values in `shared`, the
395    /// vertices of `buffer`; `None` without values.
396    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            // Without an interleaved buffer there are no vertices to read.
402            debug_assert_eq!(self.vertex_count(buffer), 0);
403            None
404        }
405    }
406}
407
408/// The data of a cross-faded `PaintPropertyBinder` subclass.
409#[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        /// The number of vertices `populate_vertex_vector` has written. It
420        /// lags the buffer's count when a feature's patterns are missing,
421        /// so the next feature's pattern also covers those vertices.
422        #[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/// The binder of a `*-pattern` property. A feature's vertex holds its image's
437/// place in the atlas, four `u16`s that both the from and the to attributes
438/// read, then the image's pixel ratio, an `f32`, which a third attribute reads
439/// where the layer's shaders size the pattern by it.
440#[derive(Clone, Debug, mln_wire::Wire)]
441pub struct CrossFadedPaintPropertyBinder<T> {
442    pub(crate) kind: CrossFadedPaintPropertyBinderKind<T>,
443}
444
445/// The size of a pattern vertex: the image's four `u16`s, then its pixel
446/// ratio.
447const PATTERN_VERTEX_SIZE: usize = PATTERN_PIXEL_RATIO_OFFSET + size_of::<f32>();
448
449/// Where a pattern vertex holds its image's pixel ratio.
450const PATTERN_PIXEL_RATIO_OFFSET: usize = 4 * size_of::<u16>();
451
452/// A pattern vertex of `tlbr`, an image's place in its atlas, and its
453/// `pixel_ratio`.
454fn 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    /// The binder of `value`, a pattern property evaluated for a tile at
463    /// `zoom`.
464    #[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    /// Adds the binder's vertex data to the vertex format; only the composite
485    /// binder has any.
486    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                    // Only the middle pattern reaches the GPU, but a feature
517                    // needs all three.
518                    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                // Unlike other properties with expressions that evaluate to
533                // null, the default value for `*-pattern` properties is an
534                // empty string and will not have a valid entry in the
535                // pattern positions. We still need to populate the attribute
536                // buffers to avoid crashes when we try to draw the layer
537                // because we don't know at draw time if all features were
538                // evaluated to valid pattern dependencies.
539                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    /// The zoom interpolation factors, always (0, 0) for pattern binders.
546    #[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    /// Where the property's attribute `index` reads the pattern values in
553    /// `shared`, the vertices of `buffer`: the from (0) and to (1)
554    /// attributes read the same place in the atlas, and the third its pixel
555    /// ratio. `None` without values.
556    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
565/// What a layer's set of binders and [`bind_paint_property`] do
566/// with either binder enum.
567pub trait PaintPropertyBinderBase {
568    /// Places the binder's values in `buffer`'s interleaved vertex.
569    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    /// Writes the values of `feature`, the feature at `index`, into `buffer`
575    /// for the vertices up to `length`.
576    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    /// Rewrites the vertex data that depends on feature state. The default,
589    /// for the constant and cross-faded binders, does nothing.
590    fn update_vectors(
591        &mut self,
592        _buffer: &mut InterleavedVertexBuffer,
593        _states: &crate::layer::bucket::FeatureStates,
594        _layer: &TileLayer<'_>,
595    ) {
596    }
597    /// True if a feature state change rewrites this binder's vertex data.
598    fn depends_on_feature_state(&self) -> bool {
599        false
600    }
601    /// The number of vertices whose values `buffer` holds for the binder.
602    fn binder_vertex_count(&self, buffer: &InterleavedVertexBuffer) -> usize;
603    /// How the binder's attribute `index`, in the order of the attribute
604    /// names `paint_property_binders!` gives it, reads its values in a vertex
605    /// of `buffer`: its format and offset; `None` for a constant.
606    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    /// Writes the values of `feature`, the feature at `index`, into `buffer`
614    /// for the vertices up to `length`.
615    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    /// Writes the values of `feature`, the feature at `index`, into `buffer`
663    /// for the vertices up to `length`.
664    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/// How a program reads a layer's data-driven paint values ([`PaintBinders`]):
687/// the vertices of the values it reads as attributes, and the properties it
688/// reads from uniforms instead, which pick its variant
689/// ([`Resources::shader_key`](crate::draw::Resources::shader_key)).
690#[derive(Clone, Debug, Default)]
691pub struct PaintAttributes {
692    /// The values' vertices, which a mesh reads beside its own
693    /// ([`MeshDesc::vertices`](crate::draw::MeshDesc::vertices), or
694    /// `instances` for a draw of instances); `None` where it reads none.
695    pub vertices: Option<VertexBinding>,
696    pub uniforms: Uniforms,
697}
698
699/// Adds `binder`'s values in `buffer`, the interleaved vertex of the paint
700/// values, as the attributes `attributes` to `read`, or records the
701/// properties of those names in `uniforms` where the property is constant
702/// or has no values.
703pub 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/// The attributes `read` of `vertices`, the vertices of `buffer`, and
724/// `uniforms`: what a layer's set of binders binds.
725#[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
739/// A layer type's binders of its data-driven paint properties, one per
740/// property, sharing one [`InterleavedVertexBuffer`]: what
741/// `paint_property_binders!` declares.
742pub trait PaintBinders: Clone + Send + mln_wire::Wire + 'static {
743    /// The evaluated paint values whose data-driven properties the binders
744    /// write.
745    type Paint: 'static;
746
747    /// The binders of `paint` in a tile at `zoom`.
748    fn new(paint: &Self::Paint, zoom: f32) -> Self;
749
750    /// The values, one interleaved vertex per vertex of the bucket.
751    fn vertices_mut(&mut self) -> &mut InterleavedVertexBuffer;
752
753    /// Writes the values of `feature`, the feature at `index` of the tile
754    /// `canonical` of the world square of `world`, in its text's formatted
755    /// section `section`, with the images of its patterns `pattern` among
756    /// `positions`, into the vertices up to `length`.
757    #[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    /// Rewrites the values that read feature state for `states`, the states
771    /// of the features of `layer`.
772    fn feature_state(&mut self, states: &crate::layer::bucket::FeatureStates, layer: &TileLayer<'_>);
773
774    /// Whether a feature state change rewrites the values.
775    fn depends_on_feature_state(&self) -> bool;
776}
777
778/// A set of binders `P` for each layer of a layout's group, which their
779/// bucket holds.
780#[derive(Clone, Debug, mln_wire::Wire)]
781#[wire(bound = "P: mln_wire::Wire")]
782pub struct LayerBinders<P> {
783    /// Each layer's id and binders, in the group's order.
784    layers: Vec<(String, P)>,
785}
786
787impl<P> Default for LayerBinders<P> {
788    /// The binders of no layer.
789    fn default() -> Self {
790        LayerBinders { layers: Vec::new() }
791    }
792}
793
794impl<P> LayerBinders<P> {
795    /// Creates binders from a pre-built list of `(layer_id, binders)` entries.
796    #[must_use]
797    pub fn from_layers(layers: Vec<(String, P)>) -> Self {
798        LayerBinders { layers }
799    }
800
801    /// The binders of the layer `id`, if it is one of the group's.
802    #[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    /// Each layer's binders.
808    pub fn values(&self) -> impl Iterator<Item = &P> {
809        self.layers.iter().map(|(_, binders)| binders)
810    }
811
812    /// Each layer's binders, to change.
813    pub fn values_mut(&mut self) -> impl Iterator<Item = &mut P> {
814        self.layers.iter_mut().map(|(_, binders)| binders)
815    }
816
817    /// Each layer's id and binders, to change.
818    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    /// The binders of each of `layers`, the first of each id, of their
825    /// paint values at `zoom`.
826    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    /// Writes `feature`'s values into each layer's binders, with each
840    /// layer's of `patterns` among `positions`, as [`PaintBinders::populate`]
841    /// does.
842    #[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/// Declares the binders of one layer type's data-driven paint properties: a
862/// struct with one binder per property, each with the names of the attributes
863/// a program reads its values from (fields in the interleaved vertex order),
864/// and the shared `InterleavedVertexBuffer`, and its [`PaintBinders`].
865#[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                // The render thread copies the vector when it builds draws.
930            }
931
932            fn feature_state(
933                &mut self,
934                states: &$crate::layer::bucket::FeatureStates,
935                layer: &$crate::tile::TileLayer<'_>,
936            ) {
937                // Values that moved to the render thread don't depend on
938                // feature state (`depends_on_feature_state`).
939                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            /// How a program reads the values of `evaluated`'s data-driven
954            /// properties in `vertices`, the vertices of the paint values,
955            /// and which of the properties it reads from uniforms.
956            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/// The images of a feature's pattern at the zooms its cross-fade reads: a
978/// pattern property's dependency, which its binder takes the positions of.
979#[derive(Clone, Debug, Default, PartialEq, Eq)]
980pub struct PatternDependency {
981    pub min: String,
982    pub mid: String,
983    pub max: String,
984}
985
986/// Each layer's [`PatternDependency`] of a feature, by layer id.
987pub type PatternLayerMap = mln_style::hash::HashMap<String, PatternDependency>;