1use std::any::Any;
12use std::sync::{Arc, OnceLock};
13
14use mln_wire::{Reader, Wire, Writer};
15
16use crate::collections::VecSet;
17use crate::color::Color;
18use crate::conversion::to_value::make_transition_style_property;
19use crate::conversion::{Converter, Convertible, Error as ConversionError};
20use crate::expression::{Dependency, EvaluationContext, Functions, ValueConverter};
21use crate::feature::{Value, ValueObject};
22use crate::geo::LatLng;
23use crate::layer::{
24 ErasedLayerStyle, ErasedStyleLayerType, FontStack, LayerBase, LayerTypeInfo, PropertyScope, SourceKind,
25};
26use crate::property::evaluated::Evaluated;
27use crate::property::evaluation::PropertyEvaluationParameters;
28use crate::property::set::{Transitionable, Transitioning};
29use crate::property::table::{Kind, PropertyInfo, SetPropertyError, StyleProperty};
30use crate::property::transition::{PropertyTransition, TransitionParameters};
31use crate::property::value::{PropertyValue, StyleValue};
32use crate::sort;
33use crate::types::Rotation;
34
35pub const MAX_DYNAMIC_PROPERTIES: usize = 256;
37
38pub const MAX_DYNAMIC_DATA_DRIVEN_PAINT: usize = 64;
40
41macro_rules! each_kind {
50 ($value:expr, $v:ident => $body:expr) => {
51 match $value {
52 Self::Float($v) => $body,
53 Self::Bool($v) => $body,
54 Self::Color($v) => $body,
55 Self::Vec2($v) => $body,
56 Self::LatLng($v) => $body,
57 Self::Rotation($v) => $body,
58 Self::String($v) | Self::Enum($v) => $body,
59 }
60 };
61 ($pair:expr, $other:ident, ($a:ident, $b:ident) => $body:expr, _ => $fallback:expr) => {
62 match $pair {
63 (Self::Float($a), $other::Float($b)) => $body,
64 (Self::Bool($a), $other::Bool($b)) => $body,
65 (Self::Color($a), $other::Color($b)) => $body,
66 (Self::Vec2($a), $other::Vec2($b)) => $body,
67 (Self::LatLng($a), $other::LatLng($b)) => $body,
68 (Self::Rotation($a), $other::Rotation($b)) => $body,
69 (Self::String($a), $other::String($b)) | (Self::Enum($a), $other::Enum($b)) => $body,
70 _ => $fallback,
71 }
72 };
73}
74
75#[derive(Clone, Debug, PartialEq)]
77pub enum DynamicDefault {
78 Float(f32),
79 Bool(bool),
80 Color(Color),
81 Vec2([f32; 2]),
82 LatLng(LatLng),
83 Rotation(Rotation),
84 String(&'static str),
85 Enum { variants: &'static [&'static str], default: u32 },
86}
87
88impl DynamicDefault {
89 #[must_use]
91 pub fn is_interpolated(&self) -> bool {
92 match self {
93 DynamicDefault::Float(_) => f32::INTERPOLATED,
94 DynamicDefault::Bool(_) => bool::INTERPOLATED,
95 DynamicDefault::Color(_) => Color::INTERPOLATED,
96 DynamicDefault::Vec2(_) => <[f32; 2]>::INTERPOLATED,
97 DynamicDefault::LatLng(_) => LatLng::INTERPOLATED,
98 DynamicDefault::Rotation(_) => Rotation::INTERPOLATED,
99 DynamicDefault::String(_) | DynamicDefault::Enum { .. } => String::INTERPOLATED,
100 }
101 }
102
103 #[must_use]
106 pub fn supports_paint_binder(&self) -> bool {
107 matches!(self, DynamicDefault::Float(_) | DynamicDefault::Color(_))
108 }
109
110 #[must_use]
112 pub fn undefined_value(&self) -> DynamicPropertyValue {
113 match self {
114 DynamicDefault::Float(_) => DynamicPropertyValue::Float(PropertyValue::Undefined),
115 DynamicDefault::Bool(_) => DynamicPropertyValue::Bool(PropertyValue::Undefined),
116 DynamicDefault::Color(_) => DynamicPropertyValue::Color(PropertyValue::Undefined),
117 DynamicDefault::Vec2(_) => DynamicPropertyValue::Vec2(PropertyValue::Undefined),
118 DynamicDefault::LatLng(_) => DynamicPropertyValue::LatLng(PropertyValue::Undefined),
119 DynamicDefault::Rotation(_) => DynamicPropertyValue::Rotation(PropertyValue::Undefined),
120 DynamicDefault::String(_) => DynamicPropertyValue::String(PropertyValue::Undefined),
121 DynamicDefault::Enum { .. } => DynamicPropertyValue::Enum(PropertyValue::Undefined),
122 }
123 }
124
125 #[must_use]
127 pub fn undefined_transitionable(&self) -> DynamicTransitionable {
128 match self {
129 DynamicDefault::Float(_) => DynamicTransitionable::Float(Transitionable::default()),
130 DynamicDefault::Bool(_) => DynamicTransitionable::Bool(Transitionable::default()),
131 DynamicDefault::Color(_) => DynamicTransitionable::Color(Transitionable::default()),
132 DynamicDefault::Vec2(_) => DynamicTransitionable::Vec2(Transitionable::default()),
133 DynamicDefault::LatLng(_) => DynamicTransitionable::LatLng(Transitionable::default()),
134 DynamicDefault::Rotation(_) => DynamicTransitionable::Rotation(Transitionable::default()),
135 DynamicDefault::String(_) => DynamicTransitionable::String(Transitionable::default()),
136 DynamicDefault::Enum { .. } => DynamicTransitionable::Enum(Transitionable::default()),
137 }
138 }
139
140 #[must_use]
142 pub fn default_evaluated(&self) -> DynamicEvaluated {
143 match self {
144 DynamicDefault::Float(v) => DynamicEvaluated::Float(Evaluated::Constant(*v)),
145 DynamicDefault::Bool(v) => DynamicEvaluated::Bool(Evaluated::Constant(*v)),
146 DynamicDefault::Color(v) => DynamicEvaluated::Color(Evaluated::Constant(*v)),
147 DynamicDefault::Vec2(v) => DynamicEvaluated::Vec2(Evaluated::Constant(*v)),
148 DynamicDefault::LatLng(v) => DynamicEvaluated::LatLng(Evaluated::Constant(*v)),
149 DynamicDefault::Rotation(v) => DynamicEvaluated::Rotation(Evaluated::Constant(*v)),
150 DynamicDefault::String(v) => DynamicEvaluated::String(Evaluated::Constant((*v).to_owned())),
151 DynamicDefault::Enum { variants, default } => {
152 let s = variants.get(*default as usize).copied().unwrap_or_default();
153 DynamicEvaluated::Enum(Evaluated::Constant(s.to_owned()))
154 }
155 }
156 }
157
158 fn matches_value(&self, value: &DynamicPropertyValue) -> bool {
159 matches!(
160 (self, value),
161 (DynamicDefault::Float(_), DynamicPropertyValue::Float(_))
162 | (DynamicDefault::Bool(_), DynamicPropertyValue::Bool(_))
163 | (DynamicDefault::Color(_), DynamicPropertyValue::Color(_))
164 | (DynamicDefault::Vec2(_), DynamicPropertyValue::Vec2(_))
165 | (DynamicDefault::LatLng(_), DynamicPropertyValue::LatLng(_))
166 | (DynamicDefault::Rotation(_), DynamicPropertyValue::Rotation(_))
167 | (DynamicDefault::String(_), DynamicPropertyValue::String(_))
168 | (DynamicDefault::Enum { .. }, DynamicPropertyValue::Enum(_))
169 )
170 }
171
172 fn matches_transitionable(&self, value: &DynamicTransitionable) -> bool {
173 matches!(
174 (self, value),
175 (DynamicDefault::Float(_), DynamicTransitionable::Float(_))
176 | (DynamicDefault::Bool(_), DynamicTransitionable::Bool(_))
177 | (DynamicDefault::Color(_), DynamicTransitionable::Color(_))
178 | (DynamicDefault::Vec2(_), DynamicTransitionable::Vec2(_))
179 | (DynamicDefault::LatLng(_), DynamicTransitionable::LatLng(_))
180 | (DynamicDefault::Rotation(_), DynamicTransitionable::Rotation(_))
181 | (DynamicDefault::String(_), DynamicTransitionable::String(_))
182 | (DynamicDefault::Enum { .. }, DynamicTransitionable::Enum(_))
183 )
184 }
185}
186
187#[derive(Clone, Debug, PartialEq)]
189pub struct DynamicPropertyDesc {
190 pub name: &'static str,
192 pub scope: PropertyScope,
193 pub data_driven: bool,
195 pub default: DynamicDefault,
196 pub attribute: Option<&'static str>,
199 pub paint_lays_out: bool,
201}
202
203impl DynamicPropertyDesc {
204 fn property_info(&self) -> PropertyInfo {
205 let info = match self.scope {
206 PropertyScope::Paint => PropertyInfo::paint(self.name),
207 PropertyScope::Layout => PropertyInfo::layout(self.name),
208 };
209 let info = if self.data_driven { info.data_driven() } else { info };
210 if self.default.is_interpolated() { info.interpolated() } else { info }
211 }
212}
213
214#[derive(Clone, Debug)]
216pub struct DynamicLayerDesc {
217 pub info: LayerTypeInfo,
218 pub properties: Vec<DynamicPropertyDesc>,
219}
220
221#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
223pub enum DynamicLayerError {
224 #[error("dynamic layer type name must not be empty")]
225 EmptyLayerName,
226 #[error("dynamic layer type has {0} properties, exceeding the limit of {MAX_DYNAMIC_PROPERTIES}")]
227 TooManyProperties(usize),
228 #[error(
229 "dynamic layer type has {0} data-driven paint properties, exceeding the limit of {MAX_DYNAMIC_DATA_DRIVEN_PAINT}"
230 )]
231 TooManyDataDrivenPaintProperties(usize),
232 #[error("dynamic property name must not be empty")]
233 EmptyPropertyName,
234 #[error("duplicate dynamic property name '{0}'")]
235 DuplicatePropertyName(String),
236 #[error("property '{0}' collides with a paint property transition name")]
237 TransitionNameCollision(String),
238 #[error("enum property '{0}' must declare at least one variant")]
239 EmptyEnumVariants(String),
240 #[error("enum property '{property}' has duplicate variant '{variant}'")]
241 DuplicateEnumVariant { property: String, variant: String },
242 #[error("enum property '{property}' default {default} is out of range for {count} variants")]
243 InvalidEnumDefault { property: String, default: u32, count: usize },
244 #[error("invalid attribute on property '{property}': {reason}")]
245 InvalidAttribute { property: String, reason: &'static str },
246 #[error("duplicate paint attribute name '{0}'")]
247 DuplicateAttributeName(String),
248}
249
250pub fn validate_dynamic_layer_desc(desc: &DynamicLayerDesc) -> Result<(), DynamicLayerError> {
252 if desc.info.name.is_empty() {
253 return Err(DynamicLayerError::EmptyLayerName);
254 }
255 if desc.properties.len() > MAX_DYNAMIC_PROPERTIES {
256 return Err(DynamicLayerError::TooManyProperties(desc.properties.len()));
257 }
258
259 let mut names = VecSet::<&str>::new();
260 let mut paint_names = VecSet::<&str>::new();
261 let mut attributes = VecSet::<&str>::new();
262 let mut data_driven_paint = 0usize;
263
264 for prop in &desc.properties {
265 if prop.name.is_empty() {
266 return Err(DynamicLayerError::EmptyPropertyName);
267 }
268 if !names.insert(prop.name) {
269 return Err(DynamicLayerError::DuplicatePropertyName(prop.name.to_owned()));
270 }
271 if prop.scope == PropertyScope::Paint {
272 paint_names.insert(prop.name);
273 if prop.data_driven {
274 data_driven_paint += 1;
275 }
276 }
277 if let DynamicDefault::Enum { variants, default } = &prop.default {
278 if variants.is_empty() {
279 return Err(DynamicLayerError::EmptyEnumVariants(prop.name.to_owned()));
280 }
281 if (*default as usize) >= variants.len() {
282 return Err(DynamicLayerError::InvalidEnumDefault {
283 property: prop.name.to_owned(),
284 default: *default,
285 count: variants.len(),
286 });
287 }
288 let mut seen_variants = VecSet::<&str>::new();
289 for &variant in *variants {
290 if !seen_variants.insert(variant) {
291 return Err(DynamicLayerError::DuplicateEnumVariant {
292 property: prop.name.to_owned(),
293 variant: variant.to_owned(),
294 });
295 }
296 }
297 }
298 if let Some(attr) = prop.attribute {
299 if attr.is_empty() {
300 return Err(DynamicLayerError::InvalidAttribute {
301 property: prop.name.to_owned(),
302 reason: "attribute name must not be empty",
303 });
304 }
305 if prop.scope != PropertyScope::Paint {
306 return Err(DynamicLayerError::InvalidAttribute {
307 property: prop.name.to_owned(),
308 reason: "attributes are only supported on paint properties",
309 });
310 }
311 if !prop.data_driven {
312 return Err(DynamicLayerError::InvalidAttribute {
313 property: prop.name.to_owned(),
314 reason: "attributes require a data-driven paint property",
315 });
316 }
317 if !prop.default.supports_paint_binder() {
318 return Err(DynamicLayerError::InvalidAttribute {
319 property: prop.name.to_owned(),
320 reason: "attributes are only supported on Float and Color paint properties",
321 });
322 }
323 if !attributes.insert(attr) {
324 return Err(DynamicLayerError::DuplicateAttributeName(attr.to_owned()));
325 }
326 }
327 }
328
329 if data_driven_paint > MAX_DYNAMIC_DATA_DRIVEN_PAINT {
330 return Err(DynamicLayerError::TooManyDataDrivenPaintProperties(data_driven_paint));
331 }
332
333 for prop in &desc.properties {
336 if let Some(base) = prop.name.strip_suffix("-transition")
337 && paint_names.contains(base)
338 {
339 return Err(DynamicLayerError::TransitionNameCollision(prop.name.to_owned()));
340 }
341 }
342
343 Ok(())
344}
345
346#[derive(Debug)]
348pub struct DynamicStyleLayerType {
349 info: LayerTypeInfo,
350 paint_properties: Vec<DynamicPropertyDesc>,
351 layout_properties: Vec<DynamicPropertyDesc>,
352 by_name: Vec<(&'static str, PropertyScope, usize)>,
354 self_ref: OnceLock<&'static Self>,
355}
356
357impl DynamicStyleLayerType {
358 pub fn leak(desc: DynamicLayerDesc) -> Result<&'static Self, DynamicLayerError> {
361 validate_dynamic_layer_desc(&desc)?;
362
363 let mut paint_properties = Vec::new();
364 let mut layout_properties = Vec::new();
365 let mut by_name = Vec::with_capacity(desc.properties.len());
366
367 for prop in desc.properties {
368 let name = prop.name;
369 match prop.scope {
370 PropertyScope::Paint => {
371 let slot = paint_properties.len();
372 paint_properties.push(prop);
373 by_name.push((name, PropertyScope::Paint, slot));
374 }
375 PropertyScope::Layout => {
376 let slot = layout_properties.len();
377 layout_properties.push(prop);
378 by_name.push((name, PropertyScope::Layout, slot));
379 }
380 }
381 }
382 sort::sort_by_key(&mut by_name, |&(name, _, _)| name);
383
384 let leaked: &'static Self = Box::leak(Box::new(DynamicStyleLayerType {
385 info: desc.info,
386 paint_properties,
387 layout_properties,
388 by_name,
389 self_ref: OnceLock::new(),
390 }));
391 let _ = leaked.self_ref.set(leaked);
392 Ok(leaked)
393 }
394
395 fn static_ref(&self) -> &'static Self {
396 self.self_ref.get().copied().unwrap_or_else(|| {
398 static EMPTY: OnceLock<DynamicStyleLayerType> = OnceLock::new();
400 EMPTY.get_or_init(|| DynamicStyleLayerType {
401 info: LayerTypeInfo { name: "", source: SourceKind::None, from_json: false },
402 paint_properties: Vec::new(),
403 layout_properties: Vec::new(),
404 by_name: Vec::new(),
405 self_ref: OnceLock::new(),
406 })
407 })
408 }
409
410 #[must_use]
411 pub fn info(&self) -> LayerTypeInfo {
412 self.info
413 }
414
415 #[must_use]
417 pub fn paint_properties(&self) -> &[DynamicPropertyDesc] {
418 &self.paint_properties
419 }
420
421 #[must_use]
423 pub fn layout_properties(&self) -> &[DynamicPropertyDesc] {
424 &self.layout_properties
425 }
426
427 #[must_use]
428 pub fn paint_property(&self, slot: usize) -> Option<&DynamicPropertyDesc> {
429 self.paint_properties.get(slot)
430 }
431
432 #[must_use]
433 pub fn layout_property(&self, slot: usize) -> Option<&DynamicPropertyDesc> {
434 self.layout_properties.get(slot)
435 }
436
437 #[must_use]
440 pub fn find_property(&self, name: &str) -> Option<(PropertyScope, usize)> {
441 let idx = self.by_name.binary_search_by_key(&name, |&(n, _, _)| n).ok()?;
442 let (_, scope, slot) = self.by_name[idx];
443 Some((scope, slot))
444 }
445
446 fn resolve(&self, name: &str) -> Option<(PropertyScope, usize, bool)> {
448 if let Some((scope, slot)) = self.find_property(name) {
449 return Some((scope, slot, false));
450 }
451 let base = name.strip_suffix("-transition")?;
452 let (scope, slot) = self.find_property(base)?;
453 (scope == PropertyScope::Paint).then_some((scope, slot, true))
454 }
455
456 #[must_use]
457 pub fn default_paint(&self) -> Vec<DynamicTransitionable> {
458 self.paint_properties.iter().map(|prop| prop.default.undefined_transitionable()).collect()
459 }
460
461 #[must_use]
462 pub fn default_layout(&self) -> Vec<DynamicPropertyValue> {
463 self.layout_properties.iter().map(|prop| prop.default.undefined_value()).collect()
464 }
465
466 #[must_use]
467 pub fn default_evaluated_paint(&self) -> DynamicEvaluatedPaint {
468 DynamicEvaluatedPaint {
469 values: self.paint_properties.iter().map(|prop| prop.default.default_evaluated()).collect(),
470 }
471 }
472}
473
474#[derive(Clone, Debug, PartialEq, mln_wire::Wire)]
476pub enum DynamicPropertyValue {
477 Float(PropertyValue<f32>),
478 Bool(PropertyValue<bool>),
479 Color(PropertyValue<Color>),
480 Vec2(PropertyValue<[f32; 2]>),
481 LatLng(PropertyValue<LatLng>),
482 Rotation(PropertyValue<Rotation>),
483 String(PropertyValue<String>),
484 Enum(PropertyValue<String>),
485}
486
487impl DynamicPropertyValue {
488 pub fn convert(
490 desc: &DynamicPropertyDesc,
491 value: &Convertible<'_>,
492 functions: &Arc<Functions>,
493 ) -> Result<Self, ConversionError> {
494 let info = desc.property_info();
495 let converted = match &desc.default {
496 DynamicDefault::Float(_) => PropertyValue::<f32>::convert(value, &info, functions).map(Self::Float),
497 DynamicDefault::Bool(_) => PropertyValue::<bool>::convert(value, &info, functions).map(Self::Bool),
498 DynamicDefault::Color(_) => PropertyValue::<Color>::convert(value, &info, functions).map(Self::Color),
499 DynamicDefault::Vec2(_) => PropertyValue::<[f32; 2]>::convert(value, &info, functions).map(Self::Vec2),
500 DynamicDefault::LatLng(_) => PropertyValue::<LatLng>::convert(value, &info, functions).map(Self::LatLng),
501 DynamicDefault::Rotation(_) => {
502 PropertyValue::<Rotation>::convert(value, &info, functions).map(Self::Rotation)
503 }
504 DynamicDefault::String(_) => PropertyValue::<String>::convert(value, &info, functions).map(Self::String),
505 DynamicDefault::Enum { variants, .. } => {
506 let converted = PropertyValue::<String>::convert(value, &info, functions)?;
507 if let PropertyValue::Constant(ref s) = converted
508 && !variants.contains(&s.as_str())
509 {
510 return Err(ConversionError::new(format!("invalid value '{s}' for enum property '{}'", desc.name)));
511 }
512 Ok(Self::Enum(converted))
513 }
514 }?;
515 if desc.paint_lays_out && converted.dependencies().intersects(Dependency::CAMERA) {
516 return Err(ConversionError::new(
517 "camera expressions are only supported in non-data-driven paint properties",
518 ));
519 }
520 Ok(converted)
521 }
522
523 #[must_use]
524 pub fn style_property(&self) -> StyleProperty {
525 each_kind!(self, v => v.style_property())
526 }
527
528 #[must_use]
529 pub fn is_undefined(&self) -> bool {
530 each_kind!(self, v => v.is_undefined())
531 }
532
533 #[must_use]
534 pub fn is_data_driven(&self) -> bool {
535 each_kind!(self, v => v.is_data_driven())
536 }
537
538 #[must_use]
539 pub fn has_data_driven_property_difference(&self, other: &Self) -> bool {
540 (self.is_data_driven() || other.is_data_driven()) && self != other
541 }
542
543 #[must_use]
544 pub fn dependencies(&self) -> Dependency {
545 each_kind!(self, v => v.dependencies())
546 }
547
548 #[must_use]
549 pub fn global_state_refs(&self) -> Option<&VecSet<String>> {
550 each_kind!(self, v => v.global_state_refs())
551 }
552
553 #[must_use]
554 pub fn host_function_refs(&self) -> Option<&VecSet<String>> {
555 each_kind!(self, v => v.host_function_refs())
556 }
557}
558
559#[derive(Clone, Debug, PartialEq, mln_wire::Wire)]
561pub enum DynamicTransitionable {
562 Float(Transitionable<PropertyValue<f32>>),
563 Bool(Transitionable<PropertyValue<bool>>),
564 Color(Transitionable<PropertyValue<Color>>),
565 Vec2(Transitionable<PropertyValue<[f32; 2]>>),
566 LatLng(Transitionable<PropertyValue<LatLng>>),
567 Rotation(Transitionable<PropertyValue<Rotation>>),
568 String(Transitionable<PropertyValue<String>>),
569 Enum(Transitionable<PropertyValue<String>>),
570}
571
572impl DynamicTransitionable {
573 #[must_use]
574 pub fn style_property(&self, transition: bool) -> StyleProperty {
575 if transition {
576 return make_transition_style_property(self.options());
577 }
578 each_kind!(self, v => v.value.style_property())
579 }
580
581 #[must_use]
582 pub(crate) fn options(&self) -> &PropertyTransition {
583 each_kind!(self, v => &v.options)
584 }
585
586 fn set_options(&mut self, options: PropertyTransition) {
587 each_kind!(self, v => v.options = options);
588 }
589
590 fn value_eq(&self, value: &DynamicPropertyValue) -> bool {
591 each_kind!((self, value), DynamicPropertyValue, (a, b) => a.value == *b, _ => false)
592 }
593
594 fn set_value(&mut self, value: DynamicPropertyValue) {
595 each_kind!((self, value), DynamicPropertyValue, (a, b) => a.value = b, _ => {});
596 }
597
598 #[must_use]
599 pub fn has_data_driven_property_difference(&self, other: &Self) -> bool {
600 each_kind!((self, other), Self, (a, b) => a.value.has_data_driven_property_difference(&b.value), _ => true)
601 }
602
603 #[must_use]
604 pub fn value_differs(&self, other: &Self) -> bool {
605 each_kind!((self, other), Self, (a, b) => a.value != b.value, _ => true)
606 }
607
608 #[must_use]
609 pub fn dependencies(&self) -> Dependency {
610 each_kind!(self, v => v.value.dependencies())
611 }
612
613 #[must_use]
614 pub fn global_state_refs(&self) -> Option<&VecSet<String>> {
615 each_kind!(self, v => v.value.global_state_refs())
616 }
617
618 #[must_use]
619 pub fn host_function_refs(&self) -> Option<&VecSet<String>> {
620 each_kind!(self, v => v.value.host_function_refs())
621 }
622
623 #[must_use]
624 pub fn untransitioned(&self) -> DynamicUnevaluated {
625 match self {
626 Self::Float(v) => DynamicUnevaluated::Float(Transitioning::new(v.value.clone())),
627 Self::Bool(v) => DynamicUnevaluated::Bool(Transitioning::new(v.value.clone())),
628 Self::Color(v) => DynamicUnevaluated::Color(Transitioning::new(v.value.clone())),
629 Self::Vec2(v) => DynamicUnevaluated::Vec2(Transitioning::new(v.value.clone())),
630 Self::LatLng(v) => DynamicUnevaluated::LatLng(Transitioning::new(v.value.clone())),
631 Self::Rotation(v) => DynamicUnevaluated::Rotation(Transitioning::new(v.value.clone())),
632 Self::String(v) => DynamicUnevaluated::String(Transitioning::new(v.value.clone())),
633 Self::Enum(v) => DynamicUnevaluated::Enum(Transitioning::new(v.value.clone())),
634 }
635 }
636
637 #[must_use]
638 pub fn transitioned(&self, parameters: &TransitionParameters, prior: DynamicUnevaluated) -> DynamicUnevaluated {
639 match (self, prior) {
640 (Self::Float(v), DynamicUnevaluated::Float(p)) => DynamicUnevaluated::Float(v.transition(parameters, p)),
641 (Self::Bool(v), DynamicUnevaluated::Bool(p)) => DynamicUnevaluated::Bool(v.transition(parameters, p)),
642 (Self::Color(v), DynamicUnevaluated::Color(p)) => DynamicUnevaluated::Color(v.transition(parameters, p)),
643 (Self::Vec2(v), DynamicUnevaluated::Vec2(p)) => DynamicUnevaluated::Vec2(v.transition(parameters, p)),
644 (Self::LatLng(v), DynamicUnevaluated::LatLng(p)) => DynamicUnevaluated::LatLng(v.transition(parameters, p)),
645 (Self::Rotation(v), DynamicUnevaluated::Rotation(p)) => {
646 DynamicUnevaluated::Rotation(v.transition(parameters, p))
647 }
648 (Self::String(v), DynamicUnevaluated::String(p)) => DynamicUnevaluated::String(v.transition(parameters, p)),
649 (Self::Enum(v), DynamicUnevaluated::Enum(p)) => DynamicUnevaluated::Enum(v.transition(parameters, p)),
650 _ => self.untransitioned(),
651 }
652 }
653}
654
655#[derive(Clone, Debug)]
657pub enum DynamicUnevaluated {
658 Float(Transitioning<PropertyValue<f32>>),
659 Bool(Transitioning<PropertyValue<bool>>),
660 Color(Transitioning<PropertyValue<Color>>),
661 Vec2(Transitioning<PropertyValue<[f32; 2]>>),
662 LatLng(Transitioning<PropertyValue<LatLng>>),
663 Rotation(Transitioning<PropertyValue<Rotation>>),
664 String(Transitioning<PropertyValue<String>>),
665 Enum(Transitioning<PropertyValue<String>>),
666}
667
668impl DynamicUnevaluated {
669 #[must_use]
670 pub fn has_transition(&self) -> bool {
671 each_kind!(self, v => v.has_transition())
672 }
673
674 #[must_use]
675 pub fn dependencies(&self) -> Dependency {
676 each_kind!(self, v => v.value().dependencies())
677 }
678
679 pub fn evaluate_with_previous(
680 &mut self,
681 default: &DynamicDefault,
682 parameters: &PropertyEvaluationParameters,
683 previous: &DynamicEvaluated,
684 ) -> DynamicEvaluated {
685 match (self, default, previous) {
686 (Self::Float(u), DynamicDefault::Float(d), DynamicEvaluated::Float(p)) => {
687 DynamicEvaluated::Float(u.evaluate_with_previous(Evaluated::plain, parameters, *d, p))
688 }
689 (Self::Bool(u), DynamicDefault::Bool(d), DynamicEvaluated::Bool(p)) => {
690 DynamicEvaluated::Bool(u.evaluate_with_previous(Evaluated::plain, parameters, *d, p))
691 }
692 (Self::Color(u), DynamicDefault::Color(d), DynamicEvaluated::Color(p)) => {
693 DynamicEvaluated::Color(u.evaluate_with_previous(Evaluated::plain, parameters, *d, p))
694 }
695 (Self::Vec2(u), DynamicDefault::Vec2(d), DynamicEvaluated::Vec2(p)) => {
696 DynamicEvaluated::Vec2(u.evaluate_with_previous(Evaluated::plain, parameters, *d, p))
697 }
698 (Self::LatLng(u), DynamicDefault::LatLng(d), DynamicEvaluated::LatLng(p)) => {
699 DynamicEvaluated::LatLng(u.evaluate_with_previous(Evaluated::plain, parameters, *d, p))
700 }
701 (Self::Rotation(u), DynamicDefault::Rotation(d), DynamicEvaluated::Rotation(p)) => {
702 DynamicEvaluated::Rotation(u.evaluate_with_previous(Evaluated::plain, parameters, *d, p))
703 }
704 (Self::String(u), DynamicDefault::String(d), DynamicEvaluated::String(p)) => {
705 DynamicEvaluated::String(u.evaluate_with_previous(Evaluated::plain, parameters, (*d).to_owned(), p))
706 }
707 (Self::Enum(u), DynamicDefault::Enum { variants, default: idx }, DynamicEvaluated::Enum(p)) => {
708 let def = variants.get(*idx as usize).copied().unwrap_or_default().to_owned();
709 let mut eval = u.evaluate_with_previous(Evaluated::plain, parameters, def.clone(), p);
710 if let Evaluated::Constant(ref mut s) = eval
711 && !variants.contains(&s.as_str())
712 {
713 *s = def;
714 }
715 DynamicEvaluated::Enum(eval)
716 }
717 _ => default.default_evaluated(),
718 }
719 }
720}
721
722#[derive(Clone, Debug, PartialEq, mln_wire::Wire)]
724pub enum DynamicEvaluated {
725 Float(Evaluated<f32>),
726 Bool(Evaluated<bool>),
727 Color(Evaluated<Color>),
728 Vec2(Evaluated<[f32; 2]>),
729 LatLng(Evaluated<LatLng>),
730 Rotation(Evaluated<Rotation>),
731 String(Evaluated<String>),
732 Enum(Evaluated<String>),
733}
734
735impl DynamicEvaluated {
736 #[must_use]
737 pub fn is_constant(&self) -> bool {
738 each_kind!(self, v => v.is_constant())
739 }
740
741 #[must_use]
742 pub fn dependencies(&self) -> Dependency {
743 each_kind!(self, v => v.dependencies())
744 }
745
746 #[must_use]
747 pub fn global_state_refs(&self) -> Option<&VecSet<String>> {
748 each_kind!(self, v => v.global_state_refs())
749 }
750
751 #[must_use]
752 pub fn host_function_refs(&self) -> Option<&VecSet<String>> {
753 each_kind!(self, v => v.host_function_refs())
754 }
755
756 #[must_use]
757 pub fn as_float(&self) -> Option<&Evaluated<f32>> {
758 match self {
759 Self::Float(v) => Some(v),
760 _ => None,
761 }
762 }
763
764 #[must_use]
765 pub fn as_bool(&self) -> Option<&Evaluated<bool>> {
766 match self {
767 Self::Bool(v) => Some(v),
768 _ => None,
769 }
770 }
771
772 #[must_use]
773 pub fn as_color(&self) -> Option<&Evaluated<Color>> {
774 match self {
775 Self::Color(v) => Some(v),
776 _ => None,
777 }
778 }
779
780 #[must_use]
781 pub fn as_vec2(&self) -> Option<&Evaluated<[f32; 2]>> {
782 match self {
783 Self::Vec2(v) => Some(v),
784 _ => None,
785 }
786 }
787
788 #[must_use]
789 pub fn as_lat_lng(&self) -> Option<&Evaluated<LatLng>> {
790 match self {
791 Self::LatLng(v) => Some(v),
792 _ => None,
793 }
794 }
795
796 #[must_use]
797 pub fn as_rotation(&self) -> Option<&Evaluated<Rotation>> {
798 match self {
799 Self::Rotation(v) => Some(v),
800 _ => None,
801 }
802 }
803
804 #[must_use]
805 pub fn as_string(&self) -> Option<&Evaluated<String>> {
806 match self {
807 Self::String(v) => Some(v),
808 _ => None,
809 }
810 }
811
812 #[must_use]
813 pub fn as_enum(&self) -> Option<&Evaluated<String>> {
814 match self {
815 Self::Enum(v) => Some(v),
816 _ => None,
817 }
818 }
819
820 #[must_use]
821 pub fn uniform_float(&self) -> Option<f32> {
822 self.as_float().map(|v| *v.uniform())
823 }
824
825 #[must_use]
826 pub fn uniform_bool(&self) -> Option<bool> {
827 self.as_bool().map(|v| *v.uniform())
828 }
829
830 #[must_use]
831 pub fn uniform_color(&self) -> Option<Color> {
832 self.as_color().map(|v| *v.uniform())
833 }
834
835 #[must_use]
836 pub fn uniform_vec2(&self) -> Option<[f32; 2]> {
837 self.as_vec2().map(|v| *v.uniform())
838 }
839
840 #[must_use]
841 pub fn uniform_lat_lng(&self) -> Option<LatLng> {
842 self.as_lat_lng().map(|v| *v.uniform())
843 }
844
845 #[must_use]
846 pub fn uniform_rotation(&self) -> Option<Rotation> {
847 self.as_rotation().map(|v| *v.uniform())
848 }
849
850 #[must_use]
851 pub fn uniform_str(&self) -> Option<&str> {
852 match self {
853 Self::String(v) | Self::Enum(v) => Some(v.uniform().as_str()),
854 _ => None,
855 }
856 }
857
858 #[must_use]
859 pub fn constant_float(&self) -> Option<f32> {
860 self.as_float().and_then(Evaluated::constant)
861 }
862
863 #[must_use]
864 pub fn constant_color(&self) -> Option<Color> {
865 self.as_color().and_then(Evaluated::constant)
866 }
867
868 #[must_use]
869 pub fn constant_or_float(&self, default: f32) -> f32 {
870 self.constant_float().unwrap_or(default)
871 }
872
873 #[must_use]
874 pub fn constant_or_color(&self, default: Color) -> Color {
875 self.constant_color().unwrap_or(default)
876 }
877
878 #[must_use]
881 pub fn enum_index(&self, variants: &[&str], default: u32) -> Option<u32> {
882 let s = self.as_enum()?.uniform().as_str();
883 Some(variants.iter().position(|&v| v == s).map_or(default, |idx| idx as u32))
884 }
885
886 #[must_use]
888 pub fn evaluate_float(&self, context: &EvaluationContext<'_>) -> Option<f32> {
889 self.as_float().map(|v| v.evaluate(context))
890 }
891
892 #[must_use]
894 pub fn evaluate_bool(&self, context: &EvaluationContext<'_>) -> Option<bool> {
895 self.as_bool().map(|v| v.evaluate(context))
896 }
897
898 #[must_use]
900 pub fn evaluate_color(&self, context: &EvaluationContext<'_>) -> Option<Color> {
901 self.as_color().map(|v| v.evaluate(context))
902 }
903
904 #[must_use]
906 pub fn evaluate_vec2(&self, context: &EvaluationContext<'_>) -> Option<[f32; 2]> {
907 self.as_vec2().map(|v| v.evaluate(context))
908 }
909
910 #[must_use]
912 pub fn evaluate_string(&self, context: &EvaluationContext<'_>) -> Option<String> {
913 match self {
914 Self::String(v) | Self::Enum(v) => Some(v.evaluate(context)),
915 _ => None,
916 }
917 }
918
919 #[must_use]
922 pub fn evaluate_enum_index(&self, context: &EvaluationContext<'_>, variants: &[&str], default: u32) -> Option<u32> {
923 let s = self.as_enum()?.evaluate(context);
924 Some(variants.iter().position(|&v| v == s).map_or(default, |idx| idx as u32))
925 }
926}
927
928#[derive(Clone, Debug, Default)]
931pub struct DynamicUnevaluatedPaint {
932 pub values: Vec<DynamicUnevaluated>,
933}
934
935impl DynamicUnevaluatedPaint {
936 #[must_use]
937 pub fn has_transition(&self) -> bool {
938 self.values.iter().any(DynamicUnevaluated::has_transition)
939 }
940
941 #[must_use]
942 pub fn dependencies(&self) -> Dependency {
943 self.values.iter().fold(Dependency::NONE, |acc, v| acc | v.dependencies())
944 }
945
946 #[must_use]
947 pub fn evaluate_with_previous(
948 &mut self,
949 layer_type: &DynamicStyleLayerType,
950 parameters: &PropertyEvaluationParameters,
951 previous: &DynamicEvaluatedPaint,
952 ) -> DynamicEvaluatedPaint {
953 let values = self
954 .values
955 .iter_mut()
956 .zip(layer_type.paint_properties())
957 .enumerate()
958 .map(|(slot, (uneval, desc))| {
959 if let Some(prev) = previous.values.get(slot) {
960 uneval.evaluate_with_previous(&desc.default, parameters, prev)
961 } else {
962 let fallback = desc.default.default_evaluated();
963 uneval.evaluate_with_previous(&desc.default, parameters, &fallback)
964 }
965 })
966 .collect();
967 DynamicEvaluatedPaint { values }
968 }
969}
970
971#[derive(Clone, Debug, Default, PartialEq, mln_wire::Wire)]
974pub struct DynamicEvaluatedPaint {
975 pub values: Vec<DynamicEvaluated>,
976}
977
978impl DynamicEvaluatedPaint {
979 #[must_use]
980 pub fn get(&self, slot: usize) -> Option<&DynamicEvaluated> {
981 self.values.get(slot)
982 }
983
984 #[must_use]
986 pub fn constants_mask(&self, layer_type: &DynamicStyleLayerType) -> u64 {
987 let mut mask = 0u64;
988 let mut dd_index = 0u32;
989 for (prop, value) in layer_type.paint_properties().iter().zip(&self.values) {
990 if prop.data_driven {
991 if value.is_constant() {
992 mask |= 1u64 << dd_index;
993 }
994 dd_index += 1;
995 }
996 }
997 mask
998 }
999
1000 #[must_use]
1001 pub fn dependencies(&self) -> Dependency {
1002 self.values.iter().fold(Dependency::NONE, |acc, v| acc | v.dependencies())
1003 }
1004
1005 pub fn collect_global_state_refs(&self, refs: &mut VecSet<String>) {
1006 for value in &self.values {
1007 if let Some(prop_refs) = value.global_state_refs() {
1008 refs.extend(prop_refs.iter().cloned());
1009 }
1010 }
1011 }
1012
1013 pub fn collect_host_function_refs(&self, refs: &mut VecSet<String>) {
1014 for value in &self.values {
1015 if let Some(prop_refs) = value.host_function_refs() {
1016 refs.extend(prop_refs.iter().cloned());
1017 }
1018 }
1019 }
1020}
1021
1022#[derive(Clone)]
1024pub struct DynamicLayerStyle {
1025 pub(crate) base: LayerBase,
1026 pub layout: Vec<DynamicPropertyValue>,
1028 pub paint: Vec<DynamicTransitionable>,
1030 layer_type: &'static DynamicStyleLayerType,
1031}
1032
1033impl std::fmt::Debug for DynamicLayerStyle {
1034 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1035 f.debug_struct("DynamicLayerStyle")
1036 .field("type", &self.layer_type.info.name)
1037 .field("base", &self.base)
1038 .field("layout", &self.layout)
1039 .field("paint", &self.paint)
1040 .finish()
1041 }
1042}
1043
1044impl DynamicLayerStyle {
1045 #[must_use]
1046 pub fn new(layer_type: &'static DynamicStyleLayerType, layer_id: String, source_id: String) -> Self {
1047 DynamicLayerStyle {
1048 base: LayerBase::new(layer_id, source_id),
1049 layout: layer_type.default_layout(),
1050 paint: layer_type.default_paint(),
1051 layer_type,
1052 }
1053 }
1054
1055 #[must_use]
1056 pub fn dynamic_type(&self) -> &'static DynamicStyleLayerType {
1057 self.layer_type
1058 }
1059
1060 #[must_use]
1061 pub fn recover(style: &Arc<dyn ErasedLayerStyle>) -> Option<Arc<Self>> {
1062 let any: Arc<dyn Any + Send + Sync> = Arc::<dyn ErasedLayerStyle>::clone(style);
1063 any.downcast().ok()
1064 }
1065
1066 #[must_use]
1067 pub fn recover_ref(style: &dyn ErasedLayerStyle) -> Option<&Self> {
1068 let any: &dyn Any = style;
1069 any.downcast_ref()
1070 }
1071
1072 #[must_use]
1073 pub fn untransitioned_paint(&self) -> DynamicUnevaluatedPaint {
1074 DynamicUnevaluatedPaint { values: self.paint.iter().map(DynamicTransitionable::untransitioned).collect() }
1075 }
1076
1077 #[must_use]
1078 pub fn transitioned_paint(
1079 &self,
1080 parameters: &TransitionParameters,
1081 prior: DynamicUnevaluatedPaint,
1082 ) -> DynamicUnevaluatedPaint {
1083 let mut prior_iter = prior.values.into_iter();
1084 let values = self
1085 .paint
1086 .iter()
1087 .map(|prop| match prior_iter.next() {
1088 Some(p) => prop.transitioned(parameters, p),
1089 None => prop.untransitioned(),
1090 })
1091 .collect();
1092 DynamicUnevaluatedPaint { values }
1093 }
1094}
1095
1096impl std::ops::Deref for DynamicLayerStyle {
1097 type Target = LayerBase;
1098 fn deref(&self) -> &LayerBase {
1099 &self.base
1100 }
1101}
1102
1103impl std::ops::DerefMut for DynamicLayerStyle {
1104 fn deref_mut(&mut self) -> &mut LayerBase {
1105 &mut self.base
1106 }
1107}
1108
1109impl ErasedLayerStyle for DynamicLayerStyle {
1110 fn base(&self) -> &LayerBase {
1111 &self.base
1112 }
1113
1114 fn info(&self) -> LayerTypeInfo {
1115 self.layer_type.info
1116 }
1117
1118 fn layout_difference(&self, other: &dyn ErasedLayerStyle) -> bool {
1119 let Some(other) = DynamicLayerStyle::recover_ref(other) else {
1120 return true;
1121 };
1122 if !std::ptr::eq(self.layer_type, other.layer_type) {
1123 return true;
1124 }
1125 if self.layer_type.info.source != SourceKind::Geometry {
1126 return false;
1127 }
1128 if self.base.filter != other.base.filter || self.base.visibility != other.base.visibility {
1129 return true;
1130 }
1131 if self.layout != other.layout {
1132 return true;
1133 }
1134 self.layer_type.paint_properties.iter().enumerate().any(|(slot, desc)| {
1135 let (Some(a), Some(b)) = (self.paint.get(slot), other.paint.get(slot)) else {
1136 return true;
1137 };
1138 (desc.data_driven && a.has_data_driven_property_difference(b))
1139 || (desc.paint_lays_out && a.value_differs(b))
1140 })
1141 }
1142
1143 fn layout_dependencies(&self) -> Dependency {
1144 let mut deps = self.base.filter_dependencies();
1145 for value in &self.layout {
1146 deps |= value.dependencies();
1147 }
1148 for (desc, value) in self.layer_type.paint_properties.iter().zip(&self.paint) {
1149 if desc.paint_lays_out {
1150 deps |= value.dependencies();
1151 }
1152 }
1153 deps
1154 }
1155
1156 fn collect_layout_global_state_refs(&self, refs: &mut VecSet<String>) {
1157 self.base.collect_filter_global_state_refs(refs);
1158 for value in &self.layout {
1159 if let Some(prop_refs) = value.global_state_refs() {
1160 refs.extend(prop_refs.iter().cloned());
1161 }
1162 }
1163 for (desc, value) in self.layer_type.paint_properties.iter().zip(&self.paint) {
1164 if desc.paint_lays_out
1165 && let Some(prop_refs) = value.global_state_refs()
1166 {
1167 refs.extend(prop_refs.iter().cloned());
1168 }
1169 }
1170 }
1171
1172 fn collect_layout_host_function_refs(&self, refs: &mut VecSet<String>) {
1173 self.base.collect_filter_host_function_refs(refs);
1174 for value in &self.layout {
1175 if let Some(prop_refs) = value.host_function_refs() {
1176 refs.extend(prop_refs.iter().cloned());
1177 }
1178 }
1179 for (desc, value) in self.layer_type.paint_properties.iter().zip(&self.paint) {
1180 if desc.paint_lays_out
1181 && let Some(prop_refs) = value.host_function_refs()
1182 {
1183 refs.extend(prop_refs.iter().cloned());
1184 }
1185 }
1186 }
1187
1188 fn populate_font_stack(&self, _out: &mut VecSet<FontStack>) {}
1189
1190 fn content_elevation(&self) -> Option<&PropertyValue<f32>> {
1191 None
1192 }
1193
1194 fn layer_type(&self) -> &'static dyn ErasedStyleLayerType {
1195 self.layer_type
1196 }
1197
1198 fn property(&self, name: &str) -> StyleProperty {
1199 let Some((scope, slot, transition)) = self.layer_type.resolve(name) else {
1200 return StyleProperty::default();
1201 };
1202 match scope {
1203 PropertyScope::Paint => {
1204 self.paint.get(slot).map_or_else(StyleProperty::default, |p| p.style_property(transition))
1205 }
1206 PropertyScope::Layout => {
1207 self.layout.get(slot).map_or_else(StyleProperty::default, DynamicPropertyValue::style_property)
1208 }
1209 }
1210 }
1211
1212 fn serialize_properties(&self, out: &mut ValueObject) {
1213 let mut insert = |scope: PropertyScope, name: String, prop: StyleProperty| {
1214 if prop.kind() == Kind::Undefined {
1215 return;
1216 }
1217 let key = match scope {
1218 PropertyScope::Paint => "paint",
1219 PropertyScope::Layout => "layout",
1220 };
1221 if let Some(Value::Object(existing)) = out.get_mut(key) {
1222 existing.entry(name).or_insert_with(|| prop.value().clone());
1223 } else {
1224 let mut inner = ValueObject::new();
1225 inner.insert(name, prop.value().clone());
1226 out.insert(key.to_owned(), Value::Object(inner));
1227 }
1228 };
1229
1230 for (desc, prop) in self.layer_type.paint_properties.iter().zip(&self.paint) {
1231 insert(PropertyScope::Paint, desc.name.to_owned(), prop.style_property(false));
1232 }
1233 for (desc, prop) in self.layer_type.paint_properties.iter().zip(&self.paint) {
1234 let transition = prop.style_property(true);
1235 if transition.kind() != Kind::Undefined {
1236 insert(PropertyScope::Paint, format!("{}-transition", desc.name), transition);
1237 }
1238 }
1239 for (desc, prop) in self.layer_type.layout_properties.iter().zip(&self.layout) {
1240 insert(PropertyScope::Layout, desc.name.to_owned(), prop.style_property());
1241 }
1242 }
1243
1244 fn copy_without_paint(&self, id: &str) -> Arc<dyn ErasedLayerStyle> {
1245 let mut copy = self.clone();
1246 copy.base.id = id.to_owned();
1247 copy.paint = self.layer_type.default_paint();
1248 Arc::new(copy)
1249 }
1250
1251 fn write(&self, w: &mut Writer<'_>) {
1252 self.base.write(w);
1253 self.layout.write(w);
1254 self.paint.write(w);
1255 }
1256}
1257
1258fn make_dynamic_mut(style: &mut Arc<dyn ErasedLayerStyle>) -> Option<&mut DynamicLayerStyle> {
1259 if Arc::get_mut(style).is_none() {
1260 let copy = DynamicLayerStyle::recover_ref(&**style)?.clone();
1261 *style = Arc::new(copy);
1262 }
1263 let style_mut: &mut dyn ErasedLayerStyle = Arc::get_mut(style)?;
1264 let any: &mut dyn Any = style_mut;
1265 any.downcast_mut()
1266}
1267
1268impl ErasedStyleLayerType for DynamicStyleLayerType {
1269 fn info(&self) -> LayerTypeInfo {
1270 self.info
1271 }
1272
1273 fn create(&self, id: &str, source: &str) -> Arc<dyn ErasedLayerStyle> {
1274 Arc::new(DynamicLayerStyle::new(self.static_ref(), id.to_owned(), source.to_owned()))
1275 }
1276
1277 fn set_property(
1278 &self,
1279 style: &mut Arc<dyn ErasedLayerStyle>,
1280 name: &str,
1281 value: &Convertible<'_>,
1282 functions: &Arc<Functions>,
1283 ) -> Result<(), SetPropertyError> {
1284 let Some(current) = DynamicLayerStyle::recover_ref(&**style) else {
1285 return Err(SetPropertyError::Unknown);
1286 };
1287 if !std::ptr::eq(current.layer_type, self.static_ref()) {
1288 return Err(SetPropertyError::Unknown);
1289 }
1290 let Some((scope, slot, transition)) = self.resolve(name) else {
1291 return Err(SetPropertyError::Unknown);
1292 };
1293
1294 match scope {
1295 PropertyScope::Paint => {
1296 let Some(desc) = self.paint_properties.get(slot) else {
1297 return Err(SetPropertyError::Unknown);
1298 };
1299 let Some(cur) = current.paint.get(slot) else {
1300 return Err(SetPropertyError::Unknown);
1301 };
1302 if transition {
1303 let mut error = ConversionError::default();
1304 let Some(options) = <PropertyTransition as Converter>::convert(value, &mut error) else {
1305 return Err(SetPropertyError::Invalid(error));
1306 };
1307 if *cur.options() != options
1308 && let Some(style_mut) = make_dynamic_mut(style)
1309 && let Some(slot_mut) = style_mut.paint.get_mut(slot)
1310 {
1311 slot_mut.set_options(options);
1312 }
1313 } else {
1314 let converted =
1315 DynamicPropertyValue::convert(desc, value, functions).map_err(SetPropertyError::Invalid)?;
1316 if !cur.value_eq(&converted)
1317 && let Some(style_mut) = make_dynamic_mut(style)
1318 && let Some(slot_mut) = style_mut.paint.get_mut(slot)
1319 {
1320 slot_mut.set_value(converted);
1321 }
1322 }
1323 Ok(())
1324 }
1325 PropertyScope::Layout => {
1326 let Some(desc) = self.layout_properties.get(slot) else {
1327 return Err(SetPropertyError::Unknown);
1328 };
1329 let Some(cur) = current.layout.get(slot) else {
1330 return Err(SetPropertyError::Unknown);
1331 };
1332 let converted =
1333 DynamicPropertyValue::convert(desc, value, functions).map_err(SetPropertyError::Invalid)?;
1334 if *cur != converted
1335 && let Some(style_mut) = make_dynamic_mut(style)
1336 && let Some(slot_mut) = style_mut.layout.get_mut(slot)
1337 {
1338 *slot_mut = converted;
1339 }
1340 Ok(())
1341 }
1342 }
1343 }
1344
1345 fn mutate_base(&self, style: &mut Arc<dyn ErasedLayerStyle>, f: &mut dyn FnMut(&mut LayerBase)) {
1346 if let Some(style_mut) = make_dynamic_mut(style)
1347 && std::ptr::eq(style_mut.layer_type, self.static_ref())
1348 {
1349 f(&mut style_mut.base);
1350 }
1351 }
1352
1353 fn read_style(&self, r: &mut Reader<'_>) -> Option<Arc<dyn ErasedLayerStyle>> {
1354 let base = LayerBase::read(r)?;
1355 let layout = Vec::<DynamicPropertyValue>::read(r)?;
1356 let paint = Vec::<DynamicTransitionable>::read(r)?;
1357 if layout.len() != self.layout_properties.len() || paint.len() != self.paint_properties.len() {
1358 return r.fail("dynamic layer style property count mismatch");
1359 }
1360 if !self.layout_properties.iter().zip(&layout).all(|(d, v)| d.default.matches_value(v))
1361 || !self.paint_properties.iter().zip(&paint).all(|(d, v)| d.default.matches_transitionable(v))
1362 {
1363 return r.fail("dynamic layer style property type mismatch");
1364 }
1365 Some(Arc::new(DynamicLayerStyle { base, layout, paint, layer_type: self.static_ref() }))
1366 }
1367}
1368
1369#[cfg(test)]
1370mod tests {
1371 use std::time::Duration;
1372
1373 use super::*;
1374 use crate::feature::PropertyMap;
1375 use crate::property::transition::TransitionOptions;
1376 use crate::registry::StyleRegistry;
1377 use crate::style::Style;
1378 use crate::tests::util::StubGeometryTileFeature;
1379 use crate::time::Instant;
1380
1381 fn prop(name: &'static str, scope: PropertyScope, default: DynamicDefault) -> DynamicPropertyDesc {
1382 DynamicPropertyDesc { name, scope, data_driven: false, default, attribute: None, paint_lays_out: false }
1383 }
1384
1385 fn base_desc(properties: Vec<DynamicPropertyDesc>) -> DynamicLayerDesc {
1386 DynamicLayerDesc {
1387 info: LayerTypeInfo { name: "test:dynamic", source: SourceKind::Geometry, from_json: true },
1388 properties,
1389 }
1390 }
1391
1392 #[test]
1393 fn validation_rejects_invalid_descriptors() {
1394 let too_many_props: Vec<DynamicPropertyDesc> = (0..=MAX_DYNAMIC_PROPERTIES)
1395 .map(|i| {
1396 prop(Box::leak(format!("p-{i}").into_boxed_str()), PropertyScope::Layout, DynamicDefault::Float(0.0))
1397 })
1398 .collect();
1399 let too_many_dd: Vec<DynamicPropertyDesc> = (0..=MAX_DYNAMIC_DATA_DRIVEN_PAINT)
1400 .map(|i| DynamicPropertyDesc {
1401 name: Box::leak(format!("dd-{i}").into_boxed_str()),
1402 scope: PropertyScope::Paint,
1403 data_driven: true,
1404 default: DynamicDefault::Float(0.0),
1405 attribute: None,
1406 paint_lays_out: false,
1407 })
1408 .collect();
1409
1410 let cases: [(&str, DynamicLayerDesc, DynamicLayerError); 13] = [
1411 (
1412 "empty layer name",
1413 DynamicLayerDesc {
1414 info: LayerTypeInfo { name: "", source: SourceKind::None, from_json: true },
1415 properties: vec![],
1416 },
1417 DynamicLayerError::EmptyLayerName,
1418 ),
1419 (
1420 "empty property name",
1421 base_desc(vec![prop("", PropertyScope::Paint, DynamicDefault::Float(1.0))]),
1422 DynamicLayerError::EmptyPropertyName,
1423 ),
1424 (
1425 "duplicate property name across scopes",
1426 base_desc(vec![
1427 prop("radius", PropertyScope::Paint, DynamicDefault::Float(1.0)),
1428 prop("radius", PropertyScope::Layout, DynamicDefault::Float(2.0)),
1429 ]),
1430 DynamicLayerError::DuplicatePropertyName("radius".to_owned()),
1431 ),
1432 (
1433 "transition name collision",
1434 base_desc(vec![
1435 prop("radius", PropertyScope::Paint, DynamicDefault::Float(1.0)),
1436 prop("radius-transition", PropertyScope::Layout, DynamicDefault::Float(2.0)),
1437 ]),
1438 DynamicLayerError::TransitionNameCollision("radius-transition".to_owned()),
1439 ),
1440 (
1441 "too many properties",
1442 base_desc(too_many_props),
1443 DynamicLayerError::TooManyProperties(MAX_DYNAMIC_PROPERTIES + 1),
1444 ),
1445 (
1446 "too many data-driven paint properties",
1447 base_desc(too_many_dd),
1448 DynamicLayerError::TooManyDataDrivenPaintProperties(MAX_DYNAMIC_DATA_DRIVEN_PAINT + 1),
1449 ),
1450 (
1451 "empty enum variants",
1452 base_desc(vec![prop("mode", PropertyScope::Paint, DynamicDefault::Enum { variants: &[], default: 0 })]),
1453 DynamicLayerError::EmptyEnumVariants("mode".to_owned()),
1454 ),
1455 (
1456 "duplicate enum variant",
1457 base_desc(vec![prop(
1458 "mode",
1459 PropertyScope::Paint,
1460 DynamicDefault::Enum { variants: &["a", "a"], default: 0 },
1461 )]),
1462 DynamicLayerError::DuplicateEnumVariant { property: "mode".to_owned(), variant: "a".to_owned() },
1463 ),
1464 (
1465 "enum default out of range",
1466 base_desc(vec![prop(
1467 "mode",
1468 PropertyScope::Paint,
1469 DynamicDefault::Enum { variants: &["a", "b"], default: 2 },
1470 )]),
1471 DynamicLayerError::InvalidEnumDefault { property: "mode".to_owned(), default: 2, count: 2 },
1472 ),
1473 (
1474 "attribute on non-data-driven property",
1475 base_desc(vec![DynamicPropertyDesc {
1476 attribute: Some("a_r"),
1477 ..prop("radius", PropertyScope::Paint, DynamicDefault::Float(1.0))
1478 }]),
1479 DynamicLayerError::InvalidAttribute {
1480 property: "radius".to_owned(),
1481 reason: "attributes require a data-driven paint property",
1482 },
1483 ),
1484 (
1485 "attribute on unsupported type",
1486 base_desc(vec![DynamicPropertyDesc {
1487 data_driven: true,
1488 attribute: Some("a_label"),
1489 ..prop("label", PropertyScope::Paint, DynamicDefault::String("x"))
1490 }]),
1491 DynamicLayerError::InvalidAttribute {
1492 property: "label".to_owned(),
1493 reason: "attributes are only supported on Float and Color paint properties",
1494 },
1495 ),
1496 (
1497 "empty attribute name",
1498 base_desc(vec![DynamicPropertyDesc {
1499 data_driven: true,
1500 attribute: Some(""),
1501 ..prop("radius", PropertyScope::Paint, DynamicDefault::Float(1.0))
1502 }]),
1503 DynamicLayerError::InvalidAttribute {
1504 property: "radius".to_owned(),
1505 reason: "attribute name must not be empty",
1506 },
1507 ),
1508 (
1509 "duplicate attribute name",
1510 base_desc(vec![
1511 DynamicPropertyDesc {
1512 data_driven: true,
1513 attribute: Some("a_val"),
1514 ..prop("radius", PropertyScope::Paint, DynamicDefault::Float(1.0))
1515 },
1516 DynamicPropertyDesc {
1517 data_driven: true,
1518 attribute: Some("a_val"),
1519 ..prop("width", PropertyScope::Paint, DynamicDefault::Float(2.0))
1520 },
1521 ]),
1522 DynamicLayerError::DuplicateAttributeName("a_val".to_owned()),
1523 ),
1524 ];
1525
1526 for (label, desc, expected) in cases {
1527 assert_eq!(DynamicStyleLayerType::leak(desc).unwrap_err(), expected, "case: {label}");
1528 }
1529 }
1530
1531 fn all_types_layer_type() -> &'static DynamicStyleLayerType {
1532 static LAYER_TYPE: OnceLock<&'static DynamicStyleLayerType> = OnceLock::new();
1533 LAYER_TYPE.get_or_init(|| {
1534 DynamicStyleLayerType::leak(DynamicLayerDesc {
1535 info: LayerTypeInfo { name: "test:all-types", source: SourceKind::Geometry, from_json: true },
1536 properties: vec![
1537 DynamicPropertyDesc {
1538 data_driven: true,
1539 attribute: Some("a_radius"),
1540 ..prop("p-float", PropertyScope::Paint, DynamicDefault::Float(4.0))
1541 },
1542 prop("p-bool", PropertyScope::Paint, DynamicDefault::Bool(false)),
1543 DynamicPropertyDesc {
1544 data_driven: true,
1545 attribute: Some("a_color"),
1546 ..prop("p-color", PropertyScope::Paint, DynamicDefault::Color(Color::red()))
1547 },
1548 prop("p-vec2", PropertyScope::Paint, DynamicDefault::Vec2([1.0, 2.0])),
1549 prop("p-latlng", PropertyScope::Paint, DynamicDefault::LatLng(LatLng::new(10.0, 20.0).unwrap())),
1550 prop("p-rot", PropertyScope::Paint, DynamicDefault::Rotation(Rotation::new(0.0))),
1551 prop("p-str", PropertyScope::Paint, DynamicDefault::String("hi")),
1552 DynamicPropertyDesc {
1553 data_driven: true,
1554 ..prop(
1555 "p-enum",
1556 PropertyScope::Paint,
1557 DynamicDefault::Enum { variants: &["flat", "raised"], default: 0 },
1558 )
1559 },
1560 DynamicPropertyDesc {
1561 paint_lays_out: true,
1562 ..prop("p-layout-paint", PropertyScope::Paint, DynamicDefault::Float(1.0))
1563 },
1564 prop("l-size", PropertyScope::Layout, DynamicDefault::Float(8.0)),
1565 ],
1566 })
1567 .unwrap()
1568 })
1569 }
1570
1571 fn registry_with(layer_type: &'static DynamicStyleLayerType) -> Arc<StyleRegistry> {
1572 let types: [&'static dyn ErasedStyleLayerType; 1] = [layer_type];
1573 Arc::new(StyleRegistry::new(Functions::with_builtins(), types, [], [], []))
1574 }
1575
1576 #[test]
1577 fn style_json_parsing_serialization_wire_and_layout_diff_work_for_dynamic_layers() {
1578 let layer_type = all_types_layer_type();
1579 let registry = registry_with(layer_type);
1580 let style_json = r##"{
1581 "version": 8,
1582 "sources": {},
1583 "layers": [{
1584 "id": "dyn-1",
1585 "type": "test:all-types",
1586 "source": "src",
1587 "layout": { "l-size": 12 },
1588 "paint": {
1589 "p-float": 10,
1590 "p-float-transition": { "duration": 200 },
1591 "p-bool": true,
1592 "p-color": "#00ff00",
1593 "p-vec2": [3, 4],
1594 "p-latlng": [45, -122],
1595 "p-rot": 90,
1596 "p-str": "hello",
1597 "p-enum": "raised"
1598 }
1599 }]
1600 }"##;
1601 let style = Style::from_json(®istry, style_json).unwrap();
1602 let layer = style.layer("dyn-1").unwrap();
1603 let dyn_style = DynamicLayerStyle::recover(layer.style()).unwrap();
1604 assert_eq!(dyn_style.dynamic_type().info().name, "test:all-types");
1605 assert_eq!(layer_type.resolve("p-float"), Some((PropertyScope::Paint, 0, false)));
1606 assert_eq!(layer_type.resolve("l-size"), Some((PropertyScope::Layout, 0, false)));
1607
1608 assert_ne!(dyn_style.property("p-float").kind(), Kind::Undefined);
1610 assert_ne!(dyn_style.property("p-float-transition").kind(), Kind::Undefined);
1611 assert_eq!(dyn_style.property("unknown").kind(), Kind::Undefined);
1612
1613 let mut serialized = ValueObject::new();
1614 dyn_style.serialize_properties(&mut serialized);
1615 let Some(Value::Object(paint_obj)) = serialized.get("paint") else {
1616 panic!("expected serialized paint object");
1617 };
1618 assert!(paint_obj.contains_key("p-float"));
1619 assert!(paint_obj.contains_key("p-float-transition"));
1620 assert!(paint_obj.contains_key("p-enum"));
1621 let Some(Value::Object(layout_obj)) = serialized.get("layout") else {
1622 panic!("expected serialized layout object");
1623 };
1624 assert!(layout_obj.contains_key("l-size"));
1625
1626 let no_paint = dyn_style.copy_without_paint("dyn-copy");
1628 let no_paint_dyn = DynamicLayerStyle::recover(&no_paint).unwrap();
1629 assert_eq!(no_paint_dyn.base.id, "dyn-copy");
1630 assert_eq!(no_paint_dyn.property("p-float").kind(), Kind::Undefined);
1631 assert_ne!(no_paint_dyn.property("l-size").kind(), Kind::Undefined);
1632
1633 let mut w = Writer::new();
1635 dyn_style.write(&mut w);
1636 let bytes = w.finish().unwrap();
1637 let mut r = Reader::new(&bytes);
1638 let decoded = layer_type.read_style(&mut r).unwrap();
1639 let decoded_dyn = DynamicLayerStyle::recover(&decoded).unwrap();
1640 assert_eq!(decoded_dyn.layout, dyn_style.layout);
1641 assert_eq!(decoded_dyn.paint, dyn_style.paint);
1642
1643 let bad_enum = r#"{
1645 "version": 8,
1646 "sources": {},
1647 "layers": [{
1648 "id": "dyn-bad",
1649 "type": "test:all-types",
1650 "source": "src",
1651 "paint": { "p-enum": "invalid-variant" }
1652 }]
1653 }"#;
1654 let bad_style = Style::from_json(®istry, bad_enum).unwrap();
1655 let bad_layer = bad_style.layer("dyn-bad").unwrap();
1656 assert_eq!(bad_layer.style().property("p-enum").kind(), Kind::Undefined);
1657
1658 let mut updated = layer.clone();
1660 assert!(updated.set_property("p-bool", &Convertible::from(&serde_json::json!(false)), None).is_none());
1661 assert!(!dyn_style.layout_difference(updated.style().as_ref()));
1662
1663 assert!(updated.set_property("p-layout-paint", &Convertible::from(&serde_json::json!(5.0)), None).is_none());
1664 assert!(dyn_style.layout_difference(updated.style().as_ref()));
1665
1666 let mut dd_updated = layer.clone();
1667 assert!(
1668 dd_updated.set_property("p-float", &Convertible::from(&serde_json::json!(["get", "r"])), None).is_none()
1669 );
1670 assert!(dyn_style.layout_difference(dd_updated.style().as_ref()));
1671 }
1672
1673 fn eval_params(now: Instant) -> PropertyEvaluationParameters {
1674 PropertyEvaluationParameters { now: Some(now), ..PropertyEvaluationParameters::new(0.0) }
1675 }
1676
1677 #[test]
1678 fn transitions_constants_mask_and_feature_evaluation_use_held_clock() {
1679 let layer_type = all_types_layer_type();
1680 let registry = registry_with(layer_type);
1681 let json_a = r##"{
1682 "version": 8,
1683 "sources": {},
1684 "layers": [{
1685 "id": "l",
1686 "type": "test:all-types",
1687 "source": "s",
1688 "paint": {
1689 "p-float": 0,
1690 "p-float-transition": { "duration": 1000 },
1691 "p-color": "#ff0000",
1692 "p-enum": ["get", "mode"]
1693 }
1694 }]
1695 }"##;
1696 let json_b = r#"{
1697 "version": 8,
1698 "sources": {},
1699 "layers": [{
1700 "id": "l",
1701 "type": "test:all-types",
1702 "source": "s",
1703 "paint": {
1704 "p-float": 100,
1705 "p-float-transition": { "duration": 1000 },
1706 "p-color": ["get", "color"],
1707 "p-enum": ["get", "mode"]
1708 }
1709 }]
1710 }"#;
1711 let style_a =
1712 DynamicLayerStyle::recover(Style::from_json(®istry, json_a).unwrap().layer("l").unwrap().style())
1713 .unwrap();
1714 let style_b =
1715 DynamicLayerStyle::recover(Style::from_json(®istry, json_b).unwrap().layer("l").unwrap().style())
1716 .unwrap();
1717
1718 let t0 = Instant::now();
1719 let default_eval = layer_type.default_evaluated_paint();
1720 let mut uneval = style_a.untransitioned_paint();
1721 let eval_t0 = uneval.evaluate_with_previous(layer_type, &eval_params(t0), &default_eval);
1722 assert_eq!(eval_t0.get(0).and_then(DynamicEvaluated::uniform_float), Some(0.0));
1723 assert_eq!(eval_t0.constants_mask(layer_type), 0b011);
1725
1726 let trans_params = TransitionParameters {
1727 now: Some(t0),
1728 transition: TransitionOptions::with_duration(Duration::from_millis(1000)),
1729 global_state_change: None,
1730 };
1731 let mut transitioned = style_b.transitioned_paint(&trans_params, uneval);
1732 assert!(transitioned.has_transition());
1733
1734 let eval_mid =
1736 transitioned.evaluate_with_previous(layer_type, &eval_params(t0 + Duration::from_millis(500)), &eval_t0);
1737 let mid_float = eval_mid.get(0).and_then(DynamicEvaluated::uniform_float).unwrap();
1738 assert!((mid_float - 50.0).abs() < 1.0, "expected midpoint near 50, got {mid_float}");
1739 assert_eq!(eval_mid.constants_mask(layer_type), 0b001);
1741
1742 let eval_end =
1744 transitioned.evaluate_with_previous(layer_type, &eval_params(t0 + Duration::from_millis(1000)), &eval_mid);
1745 assert_eq!(eval_end.get(0).and_then(DynamicEvaluated::uniform_float), Some(100.0));
1746 assert!(!transitioned.has_transition());
1747
1748 let mut props_known = PropertyMap::new();
1750 props_known.insert("mode".to_owned(), Value::String("raised".to_owned()));
1751 let f_known = StubGeometryTileFeature::new(props_known);
1752 let ctx_known = EvaluationContext::with_zoom_feature(0.0, Some(&f_known));
1753 let variants = ["flat", "raised"];
1754 assert_eq!(eval_end.get(7).and_then(|v| v.evaluate_enum_index(&ctx_known, &variants, 0)), Some(1));
1755
1756 let mut props_bad = PropertyMap::new();
1757 props_bad.insert("mode".to_owned(), Value::String("bogus".to_owned()));
1758 let f_bad = StubGeometryTileFeature::new(props_bad);
1759 let ctx_bad = EvaluationContext::with_zoom_feature(0.0, Some(&f_bad));
1760 assert_eq!(eval_end.get(7).and_then(|v| v.evaluate_enum_index(&ctx_bad, &variants, 0)), Some(0));
1761 }
1762}