Skip to main content

mln_engine/
registry.rs

1//! The registrations that a runtime, its renderers and its tile workers
2//! share: the expression functions, the layer types and the source types.
3//!
4//! An app fills a [`RegistryBuilder`] by explicit calls, [`register_builtins`]
5//! first, and builds the [`Registry`] once. Tile workers in other wasm
6//! instances make the same calls, since they run the app's own module.
7
8use std::sync::{Arc, LazyLock};
9
10use mln_style::StyleRegistry;
11use mln_style::expression::Functions;
12use mln_style::expression::functions::{RegisterError, register_builtin_functions};
13use mln_style::layer::ErasedStyleLayerType;
14use mln_style::layers::{
15    Background, Circle, ColorRelief, Fill, FillExtrusion, Heatmap, Hillshade, Line, Raster, Symbol,
16};
17use mln_style::source::ErasedStyleSourceType;
18use mln_style::sources::{
19    CustomGeometrySourceType, CustomVectorSourceType, GeoJsonSourceType, ImageSourceType, RasterDemSourceType,
20    RasterSourceType, VectorSourceType,
21};
22use mln_vec_map::VecMap;
23
24use crate::layer::layer_type::{ErasedLayerType, LayerType, entry};
25use crate::layers::custom::Custom;
26use crate::source::source_type::{self, ErasedSourceType, SourceType};
27
28/// What a [`Registry`] is built from.
29#[derive(Default)]
30pub struct RegistryBuilder {
31    functions: Functions,
32    layer_types: VecMap<&'static str, &'static dyn ErasedLayerType>,
33    source_types: VecMap<&'static str, &'static dyn ErasedSourceType>,
34}
35
36impl std::fmt::Debug for RegistryBuilder {
37    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
38        f.debug_struct("RegistryBuilder")
39            .field("functions", &self.functions)
40            .field("layer_types", &self.layer_types.keys().collect::<Vec<_>>())
41            .field("source_types", &self.source_types.keys().collect::<Vec<_>>())
42            .finish()
43    }
44}
45
46impl RegistryBuilder {
47    #[must_use]
48    pub fn new() -> Self {
49        RegistryBuilder::default()
50    }
51
52    pub fn functions_mut(&mut self) -> &mut Functions {
53        &mut self.functions
54    }
55
56    /// Adds the layer type `T`. Fails for a name that an earlier type took.
57    pub(crate) fn add_layer_type<T: LayerType>(&mut self) -> Result<(), RegisterError> {
58        let name = T::INFO.name;
59        if self.layer_types.contains_key(name) {
60            return Err(RegisterError::Duplicate(name.to_owned()));
61        }
62        self.layer_types.insert(name, entry::<T>());
63        Ok(())
64    }
65
66    /// Adds the source type `T`. Fails for a name that an earlier type took.
67    pub(crate) fn add_source_type<T: SourceType>(&mut self) -> Result<(), RegisterError> {
68        let name = T::INFO.name;
69        if self.source_types.contains_key(name) {
70            return Err(RegisterError::Duplicate(name.to_owned()));
71        }
72        self.source_types.insert(name, source_type::entry::<T>());
73        Ok(())
74    }
75
76    #[must_use]
77    pub fn build(self) -> Arc<Registry> {
78        Registry::new(Arc::new(self.functions), self.layer_types, self.source_types)
79    }
80}
81
82fn style_half(layer_type: &'static dyn ErasedLayerType) -> &'static dyn ErasedStyleLayerType {
83    layer_type
84}
85
86fn style_source_half(source_type: &'static dyn ErasedSourceType) -> &'static dyn ErasedStyleSourceType {
87    source_type
88}
89
90/// Adds the style specification's expression functions, layer types and
91/// source types, the custom layer type and the custom source types. Fails for a name that an
92/// earlier call took, or a role that an earlier function has.
93pub fn register_builtins(builder: &mut RegistryBuilder) -> Result<(), RegisterError> {
94    register_builtin_functions(builder.functions_mut())?;
95    register_builtin_types(builder)
96}
97
98fn register_builtin_types(builder: &mut RegistryBuilder) -> Result<(), RegisterError> {
99    register_builtin_layer_types(builder)?;
100    register_builtin_source_types(builder)
101}
102
103fn register_builtin_layer_types(builder: &mut RegistryBuilder) -> Result<(), RegisterError> {
104    builder.add_layer_type::<Fill>()?;
105    builder.add_layer_type::<Line>()?;
106    builder.add_layer_type::<Circle>()?;
107    builder.add_layer_type::<Symbol>()?;
108    builder.add_layer_type::<Raster>()?;
109    builder.add_layer_type::<Background>()?;
110    builder.add_layer_type::<Hillshade>()?;
111    builder.add_layer_type::<ColorRelief>()?;
112    builder.add_layer_type::<FillExtrusion>()?;
113    builder.add_layer_type::<Heatmap>()?;
114    builder.add_layer_type::<Custom>()
115}
116
117fn register_builtin_source_types(builder: &mut RegistryBuilder) -> Result<(), RegisterError> {
118    builder.add_source_type::<VectorSourceType>()?;
119    builder.add_source_type::<RasterSourceType>()?;
120    builder.add_source_type::<RasterDemSourceType>()?;
121    builder.add_source_type::<GeoJsonSourceType>()?;
122    builder.add_source_type::<ImageSourceType>()?;
123    builder.add_source_type::<CustomGeometrySourceType>()?;
124    builder.add_source_type::<CustomVectorSourceType>()
125}
126
127/// The expression functions, layer types and source types that a style
128/// parses against, its renderer draws and its tile workers lay out, built by
129/// a [`RegistryBuilder`]. It doesn't change once built.
130///
131/// A map and the renderer and tile workers that draw it must be given
132/// registries filled by the same calls: they identify functions, layer
133/// types and source types by name.
134pub struct Registry {
135    style: Arc<StyleRegistry>,
136    layer_types: VecMap<&'static str, &'static dyn ErasedLayerType>,
137    source_types: VecMap<&'static str, &'static dyn ErasedSourceType>,
138}
139
140impl std::fmt::Debug for Registry {
141    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
142        f.debug_struct("Registry").field("style", &self.style).finish_non_exhaustive()
143    }
144}
145
146impl Registry {
147    /// The built-in registrations: what [`register_builtins`] adds. Every
148    /// call returns the same value, built on the first: a registry never
149    /// changes, so sharing it is a cache, and an app with registrations of
150    /// its own still builds its registry with a [`RegistryBuilder`].
151    #[must_use]
152    pub fn with_builtins() -> Arc<Registry> {
153        static BUILTINS: LazyLock<Arc<Registry>> = LazyLock::new(|| {
154            let mut builder = RegistryBuilder::new();
155            // Into no types, the built-ins register.
156            let registered = register_builtin_types(&mut builder);
157            debug_assert_eq!(registered, Ok(()));
158            Registry::new(Functions::with_builtins(), builder.layer_types, builder.source_types)
159        });
160        Arc::clone(&BUILTINS)
161    }
162
163    fn new(
164        functions: Arc<Functions>,
165        layer_types: VecMap<&'static str, &'static dyn ErasedLayerType>,
166        source_types: VecMap<&'static str, &'static dyn ErasedSourceType>,
167    ) -> Arc<Registry> {
168        let style_halves = layer_types.values().map(|&layer_type| style_half(layer_type));
169        let style_source_halves = source_types.values().map(|&source_type| style_source_half(source_type));
170        let style = StyleRegistry::new(functions, style_halves, style_source_halves);
171        Arc::new(Registry { style: Arc::new(style), layer_types, source_types })
172    }
173
174    #[must_use]
175    pub fn style(&self) -> &Arc<StyleRegistry> {
176        &self.style
177    }
178
179    #[must_use]
180    pub fn functions(&self) -> &Arc<Functions> {
181        self.style.functions()
182    }
183
184    pub(crate) fn layer_type(&self, name: &str) -> Option<&'static dyn ErasedLayerType> {
185        self.layer_types.get(name).copied()
186    }
187
188    pub(crate) fn source_type(&self, name: &str) -> Option<&'static dyn ErasedSourceType> {
189        self.source_types.get(name).copied()
190    }
191}
192
193/// A context in which the values that the worker codec reads resolve the
194/// registrations they name against this registry: layers' evaluated values
195/// their layer type, and as for a [`StyleRegistry`], layers' style data and
196/// compound expressions.
197impl mln_wire::Context for &Registry {
198    fn provide<'a>(&'a mut self, request: &mut mln_wire::Request<'a>) {
199        let registry: &'a Registry = self;
200        request.give(registry).give::<StyleRegistry>(registry.style()).give::<Functions>(registry.functions());
201    }
202}
203
204#[cfg(test)]
205mod tests {
206    use super::*;
207
208    #[test]
209    fn builtins_register_once() {
210        let mut builder = RegistryBuilder::new();
211        register_builtins(&mut builder).unwrap();
212        assert!(matches!(register_builtins(&mut builder), Err(RegisterError::Duplicate(_))));
213    }
214
215    #[test]
216    fn builtins_register_seven_source_types() {
217        let mut builder = RegistryBuilder::new();
218        register_builtins(&mut builder).unwrap();
219        let registry = builder.build();
220        let names: Vec<_> = registry.style().source_types().map(|source_type| source_type.info().name).collect();
221        assert_eq!(names, ["custom-geometry", "custom-vector", "geojson", "image", "raster", "raster-dem", "vector"]);
222    }
223
224    #[test]
225    fn a_source_type_registers_once() {
226        let mut builder = RegistryBuilder::new();
227        builder.add_source_type::<GeoJsonSourceType>().unwrap();
228        assert_eq!(builder.add_source_type::<GeoJsonSourceType>(), Err(RegisterError::Duplicate("geojson".to_owned())));
229    }
230
231    #[test]
232    fn a_layer_type_registers_once() {
233        let mut builder = RegistryBuilder::new();
234        builder.add_layer_type::<Circle>().unwrap();
235        assert_eq!(builder.add_layer_type::<Circle>(), Err(RegisterError::Duplicate("circle".to_owned())));
236    }
237}