Skip to main content

mln_style/property/
expression.rs

1use std::sync::Arc;
2
3use mln_wire::shared;
4
5use crate::collections::VecSet;
6use crate::expression::value::from_expression_values;
7use crate::expression::{
8    Dependency, EvaluationContext, Expr, GlobalStateMap, Value, ValueConverter, ZoomCurve, collect_global_state_refs,
9    find_zoom_curve_checked,
10};
11use crate::range::Range;
12use crate::wire::SharedExpression;
13
14fn collect_global_state_refs_shared(expression: &Expr) -> Option<Arc<VecSet<String>>> {
15    if !expression.has(Dependency::GLOBAL_STATE) {
16        return None;
17    }
18    let mut refs = VecSet::new();
19    collect_global_state_refs(expression, &mut refs);
20    Some(Arc::new(refs))
21}
22
23/// A shared expression plus its precomputed constness flags. The zoom curve
24/// isn't cached, since it would borrow from the expression:
25/// `zoom_curve` finds it each time.
26#[derive(Clone, Debug)]
27pub struct PropertyExpressionBase {
28    expression: Arc<Expr>,
29    captured_global_state: Option<Arc<GlobalStateMap>>,
30    global_state_refs: Option<Arc<VecSet<String>>>,
31    use_integer_zoom: bool,
32    global_state_pinned: bool,
33    is_zoom_constant: bool,
34    is_feature_constant: bool,
35    is_runtime_constant: bool,
36}
37
38impl PropertyExpressionBase {
39    pub(crate) fn new(expression: Arc<Expr>) -> Self {
40        let global_state_refs = collect_global_state_refs_shared(expression.as_ref());
41        let is_zoom_constant = !expression.has(Dependency::ZOOM);
42        let is_feature_constant = !expression.has(Dependency::FEATURE);
43        let is_runtime_constant = !expression.has(Dependency::IMAGE | Dependency::GLOBAL_STATE);
44        PropertyExpressionBase {
45            expression,
46            captured_global_state: None,
47            global_state_refs,
48            use_integer_zoom: false,
49            global_state_pinned: false,
50            is_zoom_constant,
51            is_feature_constant,
52            is_runtime_constant,
53        }
54    }
55
56    #[must_use]
57    pub fn is_zoom_constant(&self) -> bool {
58        self.is_zoom_constant
59    }
60
61    #[must_use]
62    pub fn is_feature_constant(&self) -> bool {
63        self.is_feature_constant
64    }
65
66    #[must_use]
67    pub(crate) fn is_runtime_constant(&self) -> bool {
68        self.is_runtime_constant
69    }
70
71    #[must_use]
72    pub fn interpolation_factor(&self, input_levels: Range<f64>, input_value: f64) -> f32 {
73        match self.zoom_curve() {
74            None => {
75                debug_assert!(false);
76                0.0
77            }
78            Some(ZoomCurve::Interpolate(z)) => z.interpolation_factor(input_levels, input_value) as f32,
79            Some(ZoomCurve::Step(_)) => 0.0,
80        }
81    }
82
83    #[must_use]
84    pub fn covering_stops(&self, lower: f64, upper: f64) -> Range<f64> {
85        match self.zoom_curve() {
86            None => {
87                debug_assert!(false);
88                Range::new(0.0, 0.0)
89            }
90            Some(ZoomCurve::Interpolate(z)) => z.covering_stops(lower, upper),
91            Some(ZoomCurve::Step(z)) => z.covering_stops(lower, upper),
92        }
93    }
94
95    #[must_use]
96    pub fn expression(&self) -> &Expr {
97        self.expression.as_ref()
98    }
99
100    /// The expression, as the `Arc` that values of the property share.
101    #[must_use]
102    pub fn shared_expression(&self) -> &Arc<Expr> {
103        &self.expression
104    }
105
106    #[must_use]
107    pub fn use_integer_zoom(&self) -> bool {
108        self.use_integer_zoom
109    }
110
111    pub(crate) fn set_use_integer_zoom(&mut self, value: bool) {
112        self.use_integer_zoom = value;
113    }
114
115    /// Capture a snapshot of the style's global state so that later
116    /// evaluations (e.g. per-feature evaluation during tile layout or in
117    /// paint property binders) can resolve `global-state` expressions without
118    /// explicit plumbing. Only retained if the expression actually depends on
119    /// it.
120    pub fn capture_global_state(&mut self, global_state: Option<Arc<GlobalStateMap>>) {
121        if self.expression.has(Dependency::GLOBAL_STATE) && !self.global_state_pinned {
122            self.captured_global_state = global_state;
123        }
124    }
125
126    /// Evaluate `global-state` with this snapshot even when the evaluation
127    /// context carries a state of its own, so a value shown before a global
128    /// state change keeps its look while it transitions out. The first pin
129    /// wins: a value already showing an older state keeps showing it.
130    pub(crate) fn pin_global_state(&mut self, global_state: Arc<GlobalStateMap>) {
131        if self.global_state_pinned {
132            return;
133        }
134        self.captured_global_state = Some(global_state);
135        self.global_state_pinned = true;
136    }
137
138    #[must_use]
139    pub(crate) fn captured_global_state(&self) -> Option<&Arc<GlobalStateMap>> {
140        self.captured_global_state.as_ref()
141    }
142
143    /// None if the expression does not reference the global state.
144    #[must_use]
145    pub(crate) fn global_state_refs(&self) -> Option<&VecSet<String>> {
146        self.global_state_refs.as_deref()
147    }
148
149    #[must_use]
150    pub(crate) fn dependencies(&self) -> Dependency {
151        self.expression.dependencies()
152    }
153
154    /// The expression's zoom curve (recomputed, see the struct comment).
155    #[must_use]
156    pub(crate) fn zoom_curve(&self) -> Option<ZoomCurve<'_>> {
157        find_zoom_curve_checked(self.expression.as_ref())
158    }
159}
160
161/// Crosses as the expression (shared, see wire.rs)
162/// and what was set on it; the flags are derived from the expression again.
163///
164/// Not inlined: every `PropertyExpression<T>`, `PropertyValue<T>` and
165/// `Evaluated<T>` reads and writes one, so inlined it would compile once per
166/// value type.
167impl mln_wire::Wire for PropertyExpressionBase {
168    #[inline(never)]
169    fn write(&self, w: &mut mln_wire::Writer) {
170        shared::write::<SharedExpression>(&self.expression, w);
171        self.captured_global_state.write(w);
172        self.use_integer_zoom.write(w);
173        self.global_state_pinned.write(w);
174    }
175
176    #[inline(never)]
177    fn read(r: &mut mln_wire::Reader<'_>) -> Option<Self> {
178        let mut base = PropertyExpressionBase::new(shared::read::<SharedExpression>(r)?);
179        base.captured_global_state = mln_wire::Wire::read(r)?;
180        base.use_integer_zoom = mln_wire::Wire::read(r)?;
181        base.global_state_pinned = mln_wire::Wire::read(r)?;
182        Some(base)
183    }
184}
185
186#[derive(Clone, Debug, mln_wire::Wire)]
187pub struct PropertyExpression<T> {
188    base: PropertyExpressionBase,
189    /// A legacy function's `default`, for values its expression can't
190    /// convert to `T`, such as a string that names no enum value. Held as
191    /// a value rather than a `T`, so that only one copy of the code that
192    /// clones and sends it is compiled.
193    default_value: Option<Value>,
194    output: std::marker::PhantomData<fn() -> T>,
195}
196
197impl<T> std::ops::Deref for PropertyExpression<T> {
198    type Target = PropertyExpressionBase;
199    fn deref(&self) -> &PropertyExpressionBase {
200        &self.base
201    }
202}
203
204impl<T> std::ops::DerefMut for PropertyExpression<T> {
205    fn deref_mut(&mut self) -> &mut PropertyExpressionBase {
206        &mut self.base
207    }
208}
209
210impl<T> PropertyExpression<T> {
211    #[must_use]
212    pub fn new(expression: Arc<Expr>) -> Self {
213        PropertyExpression {
214            base: PropertyExpressionBase::new(expression),
215            default_value: None,
216            output: std::marker::PhantomData,
217        }
218    }
219
220    #[must_use]
221    pub fn from_expr(expression: Expr) -> Self {
222        PropertyExpression::new(Arc::new(expression))
223    }
224
225    /// Evaluates to `default_value` where the expression fails or its value
226    /// doesn't convert to `T`, rather than to the property's default.
227    #[must_use]
228    pub fn with_default(self, default_value: Option<T>) -> Self
229    where
230        T: ValueConverter,
231    {
232        PropertyExpression { default_value: default_value.map(|d| d.to_expression_value()), ..self }
233    }
234}
235
236impl<T: Clone + ValueConverter> PropertyExpression<T> {
237    pub fn evaluate(&self, context: &EvaluationContext<'_>, final_default_value: T) -> T {
238        // A pinned snapshot wins, and the captured one fills in for a context
239        // that carries no state.
240        match &self.base.captured_global_state {
241            Some(captured) if self.base.global_state_pinned || context.global_state.is_none() => {
242                let context_with_state = context.with_global_state(Some(captured.as_ref()));
243                self.evaluate_context(&context_with_state, final_default_value)
244            }
245            _ => self.evaluate_context(context, final_default_value),
246        }
247    }
248
249    pub(crate) fn possible_outputs(&self) -> Vec<Option<T>> {
250        from_expression_values::<T>(&self.base.expression.possible_outputs())
251    }
252
253    fn evaluate_context(&self, context: &EvaluationContext<'_>, final_default_value: T) -> T {
254        T::evaluate(&self.base.expression, context)
255            .or_else(|| self.default_value.as_ref().and_then(T::from_expression_value))
256            .unwrap_or(final_default_value)
257    }
258}
259
260impl<T> PartialEq for PropertyExpression<T> {
261    fn eq(&self, other: &Self) -> bool {
262        self.base.expression == other.base.expression
263    }
264}