Skip to main content

mln_style/property/
value.rs

1use std::fmt::Debug;
2use std::sync::Arc;
3
4use crate::collections::VecSet;
5use crate::conversion::to_value::{ValueFactory, make_style_property};
6use crate::conversion::{Converter, Convertible, Error};
7use crate::expression::{Dependency, Functions, Type, ValueConverter, global_state_refs_intersect};
8use crate::layer::PropertyScope;
9use crate::property::convert::{check_camera, check_elevation, check_tile, convert_property_value};
10use crate::property::evaluated::{Evaluated, Evaluation};
11use crate::property::evaluation::PropertyEvaluationParameters;
12use crate::property::expression::PropertyExpression;
13use crate::property::table::{PropertyInfo, StyleProperty};
14use crate::property::transition::GlobalStateChange;
15
16/// A style property's value: undefined (the default), a constant or an
17/// expression.
18#[derive(Debug, Default, mln_wire::Wire)]
19pub enum PropertyValue<T> {
20    #[default]
21    Undefined,
22    Constant(T),
23    Expression(PropertyExpression<T>),
24}
25
26// Clone and PartialEq are written out rather than derived so that they can be
27// `#[inline(never)]`: a layer's impl, its property sets and the transitions
28// clone and compare one per property, and a derive inlined there copies the
29// match into every one of them, which costs code size (the browser build's
30// wasm most) for no speed that style mutation needs.
31impl<T: Clone> Clone for PropertyValue<T> {
32    #[inline(never)]
33    fn clone(&self) -> Self {
34        match self {
35            PropertyValue::Undefined => PropertyValue::Undefined,
36            PropertyValue::Constant(v) => PropertyValue::Constant(v.clone()),
37            PropertyValue::Expression(e) => PropertyValue::Expression(e.clone()),
38        }
39    }
40}
41
42impl<T: PartialEq> PartialEq for PropertyValue<T> {
43    #[inline(never)]
44    fn eq(&self, other: &Self) -> bool {
45        match (self, other) {
46            (PropertyValue::Undefined, PropertyValue::Undefined) => true,
47            (PropertyValue::Constant(a), PropertyValue::Constant(b)) => a == b,
48            (PropertyValue::Expression(a), PropertyValue::Expression(b)) => a == b,
49            _ => false,
50        }
51    }
52}
53
54impl<T> From<PropertyExpression<T>> for PropertyValue<T> {
55    fn from(expression: PropertyExpression<T>) -> Self {
56        PropertyValue::Expression(expression)
57    }
58}
59
60impl<T> PropertyValue<T> {
61    pub fn is_constant(&self) -> bool {
62        matches!(self, PropertyValue::Constant(_))
63    }
64
65    pub fn is_expression(&self) -> bool {
66        matches!(self, PropertyValue::Expression(_))
67    }
68
69    /// The constant, or `None` when the value isn't a constant.
70    pub fn as_constant(&self) -> Option<&T> {
71        match self {
72            PropertyValue::Constant(t) => Some(t),
73            _ => None,
74        }
75    }
76
77    /// The expression, or `None` when the value isn't an expression.
78    pub fn as_expression(&self) -> Option<&PropertyExpression<T>> {
79        match self {
80            PropertyValue::Expression(e) => Some(e),
81            _ => None,
82        }
83    }
84
85    /// The expression, or `None` when the value isn't an expression.
86    pub fn as_expression_mut(&mut self) -> Option<&mut PropertyExpression<T>> {
87        match self {
88            PropertyValue::Expression(e) => Some(e),
89            _ => None,
90        }
91    }
92}
93
94/// A style value a property holds: a [`PropertyValue`], or a
95/// [`ColorRampPropertyValue`](crate::property::color_ramp::ColorRampPropertyValue).
96pub trait StyleValue: Clone + Default + Debug + PartialEq + 'static {
97    /// What the value evaluates to.
98    type Type: Clone + Debug + Default + ValueConverter;
99
100    /// Converts a style JSON value for the property `info`, parsing
101    /// expressions against `functions`.
102    fn convert(value: &Convertible<'_>, info: &PropertyInfo, functions: &Arc<Functions>) -> Result<Self, Error>;
103
104    fn style_property(&self) -> StyleProperty;
105
106    /// The value for a frame, with `default` for an undefined value.
107    fn evaluate(
108        &self,
109        evaluation: Evaluation<Self::Type>,
110        parameters: &PropertyEvaluationParameters,
111        default: Self::Type,
112    ) -> Evaluated<Self::Type>;
113
114    fn is_undefined(&self) -> bool;
115
116    /// Whether the value may differ by feature, or across a feature's
117    /// extrusion by elevation: the buckets lay out its values.
118    fn is_data_driven(&self) -> bool;
119
120    fn dependencies(&self) -> Dependency;
121
122    fn global_state_refs(&self) -> Option<&VecSet<String>>;
123
124    fn host_function_refs(&self) -> Option<&VecSet<String>> {
125        None
126    }
127
128    /// Whether the values differ and either may differ by feature.
129    fn has_data_driven_property_difference(&self, other: &Self) -> bool {
130        (self.is_data_driven() || other.is_data_driven()) && self != other
131    }
132
133    /// Whether both values are constants, and differ.
134    fn constant_differs(&self, _other: &Self) -> bool {
135        false
136    }
137
138    /// Whether a change of the keys in `changed_keys` transitions the value
139    /// rather than snapping it.
140    fn transitions_on_global_state_change(&self, _changed_keys: Option<&VecSet<String>>) -> bool {
141        false
142    }
143
144    /// Keeps the value reading the global state from before `change`, if it
145    /// transitions on it.
146    fn retain_prior_global_state(&mut self, _change: &GlobalStateChange) {}
147}
148
149impl<T> StyleValue for PropertyValue<T>
150where
151    T: Converter + ValueConverter + ValueFactory + Clone + Debug + Default + PartialEq + 'static,
152{
153    type Type = T;
154
155    fn convert(value: &Convertible<'_>, info: &PropertyInfo, functions: &Arc<Functions>) -> Result<Self, Error> {
156        let mut error = Error::default();
157        let value =
158            convert_property_value::<T>(value, &mut error, info.data_driven, info.tokens, info.interpolated, functions)
159                .ok_or(error)?;
160        let deps = value.dependencies();
161        check_elevation(deps, info.elevation)?;
162        let defers_to_tile =
163            deps.intersects(Dependency::FEATURE | Dependency::IMAGE | Dependency::ELEVATION | Dependency::TILE);
164        let allow_camera = info.scope == PropertyScope::Paint && !info.cross_faded && !defers_to_tile;
165        check_camera(deps, allow_camera)?;
166        let allow_tile = info.scope == PropertyScope::Layout || info.data_driven;
167        check_tile(deps, allow_tile)?;
168        Ok(value)
169    }
170
171    fn style_property(&self) -> StyleProperty {
172        make_style_property(self)
173    }
174
175    fn evaluate(
176        &self,
177        evaluation: Evaluation<T>,
178        parameters: &PropertyEvaluationParameters,
179        default: T,
180    ) -> Evaluated<T> {
181        evaluation(self, parameters, default)
182    }
183
184    fn is_undefined(&self) -> bool {
185        matches!(self, PropertyValue::Undefined)
186    }
187
188    fn is_data_driven(&self) -> bool {
189        match self {
190            PropertyValue::Undefined | PropertyValue::Constant(_) => false,
191            PropertyValue::Expression(fn_) => {
192                !fn_.is_feature_constant() || fn_.dependencies().intersects(Dependency::ELEVATION | Dependency::TILE)
193            }
194        }
195    }
196
197    fn dependencies(&self) -> Dependency {
198        match self {
199            PropertyValue::Undefined | PropertyValue::Constant(_) => Dependency::NONE,
200            PropertyValue::Expression(ex) => ex.dependencies(),
201        }
202    }
203
204    fn global_state_refs(&self) -> Option<&VecSet<String>> {
205        match self {
206            PropertyValue::Undefined | PropertyValue::Constant(_) => None,
207            PropertyValue::Expression(ex) => ex.global_state_refs(),
208        }
209    }
210
211    fn host_function_refs(&self) -> Option<&VecSet<String>> {
212        match self {
213            PropertyValue::Undefined | PropertyValue::Constant(_) => None,
214            PropertyValue::Expression(ex) => ex.host_function_refs(),
215        }
216    }
217
218    fn constant_differs(&self, other: &Self) -> bool {
219        match (self, other) {
220            (PropertyValue::Constant(a), PropertyValue::Constant(b)) => a != b,
221            _ => false,
222        }
223    }
224
225    /// A value that reads a changed key transitions unless it differs by
226    /// feature or is a pattern image: images are never interpolated, so a
227    /// transition would only delay the image the tiles are laid out with.
228    fn transitions_on_global_state_change(&self, changed_keys: Option<&VecSet<String>>) -> bool {
229        T::expression_type() != Type::Image
230            && !self.is_data_driven()
231            && self.dependencies().intersects(Dependency::GLOBAL_STATE)
232            && global_state_refs_intersect(self.global_state_refs(), changed_keys)
233    }
234
235    fn retain_prior_global_state(&mut self, change: &GlobalStateChange) {
236        if self.transitions_on_global_state_change(Some(&change.changed_keys))
237            && let Some(expression) = self.as_expression_mut()
238        {
239            expression.pin_global_state(Arc::clone(&change.prior_state));
240        }
241    }
242}