1pub mod cluster;
17pub mod tile;
18
19use std::sync::{Arc, Weak};
20
21use geojson::GeoJson;
22use mln_engine::MapMode;
23use mln_engine::exec::pool::TaskGroup;
24use mln_engine::query::FeatureExtensionValue;
25use mln_engine::source::{
26 Cover, DataOrigin, Described, Fetch, GeometryTiles, Load, LoadContext, OfflineResources, OriginUpdate, Replier,
27 Respond, SourceSummary, SourceType, Supply, WorldCopy,
28};
29use mln_engine::storage::Data;
30use mln_engine::tile::TileData;
31use mln_style::crs::WorldMapping;
32use mln_style::error::Error;
33use mln_style::expression::{
34 EvaluationContext, Expr, evaluate_accumulated, from_expression_value, with_geojson_feature,
35};
36use mln_style::feature::{Feature, Identifier, PropertyMap, Value};
37use mln_style::source::SourceData;
38use mln_style::sources::GeoJsonSourceType;
39use mln_style::sources::geojson::{ClusterProperties, GeoJSONOptions, GeoJsonSourceOptions, features_to_world};
40use mln_style::tile_id::CanonicalTileID;
41use mln_style::{Edit, Source, constants};
42use parking_lot::Mutex;
43
44const PARSE_STYLE: &str = "mln_builtins::parse_style";
47const GENERAL: &str = "mln_builtins::general";
48
49pub struct GeoJsonSource;
52
53impl SourceType for GeoJsonSource {
54 type Style = GeoJsonSourceType;
55 type Data = GeometryTiles;
56 type Description = Arc<dyn GeoJSONData>;
57
58 const DESCRIBES_IN_BACKGROUND: bool = true;
59
60 const DESCRIBES_IN_WORLD: bool = true;
61
62 fn load(source: &SourceData<GeoJsonSourceType>) -> Load<Arc<dyn GeoJSONData>> {
65 match (&source.options.url, &source.options.inline) {
66 (Some(url), _) => Load::Fetch(Fetch::Source(url.clone())),
67 (None, Some(_)) => Load::Describe,
68 (None, None) => Load::Done,
69 }
70 }
71
72 fn describe(
76 options: &GeoJsonSourceOptions,
77 world: &WorldMapping,
78 data: Option<Data>,
79 respond: Respond<Described<Arc<dyn GeoJSONData>>>,
80 ) {
81 respond(match (data, &options.inline) {
82 (Some(data), _) => Ok(build_geojson(&data, options, world)),
83 (None, Some(inline)) => Ok(build_inline(inline, options, world)),
84 (None, None) => Err(Error::failed("unexpectedly empty GeoJSON")),
85 });
86 }
87
88 fn attribution(source: &SourceData<GeoJsonSourceType>) -> Option<String> {
89 source.options.options.attribution.clone()
90 }
91
92 fn summary(source: &SourceData<GeoJsonSourceType>) -> SourceSummary {
93 SourceSummary {
94 url: source.options.url.clone(),
95 geojson: Some(Arc::clone(&source.options.options)),
96 ..SourceSummary::default()
97 }
98 }
99
100 fn offline(source: &SourceData<GeoJsonSourceType>) -> OfflineResources {
101 match &source.options.url {
102 Some(url) => OfflineResources::Source { url: url.clone() },
103 None => OfflineResources::None,
104 }
105 }
106
107 fn supply(_source: &Source) -> Supply<GeometryTiles> {
108 Supply::tiles(GeoJsonOrigin { data: None, synchronous: false, warned: None })
109 }
110
111 fn query_feature_extension(
115 source: &Source,
116 feature: &mln_engine::tile::feature::Feature,
117 extension: &str,
118 field: &str,
119 args: Option<&PropertyMap>,
120 ) -> Result<FeatureExtensionValue, Error> {
121 query_feature_extension(source, feature, extension, field, args)
122 }
123}
124
125fn tile_features(index: &tile::TileIndex, id: &CanonicalTileID) -> Arc<TileFeatures> {
128 index.tile(id.z, id.x, id.y).unwrap_or_else(|e| {
129 tracing::error!(target: GENERAL, tile = %id, error = %e, "Failed to build GeoJSON tile data");
130 Arc::default()
131 })
132}
133
134struct IndexData {
136 index: tile::TileIndex,
137 world: WorldMapping,
139}
140
141impl std::fmt::Debug for IndexData {
142 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
143 f.write_str("IndexData")
144 }
145}
146
147impl GeoJSONData for IndexData {
148 fn tile(&self, id: &CanonicalTileID) -> Arc<TileFeatures> {
149 tile_features(&self.index, id)
150 }
151
152 fn cuts_on_demand(&self) -> bool {
153 true
154 }
155
156 fn children(&self, _cluster_id: u32) -> Result<Features, Error> {
157 Ok(Features::new())
158 }
159
160 fn leaves(&self, _cluster_id: u32, _limit: u32, _offset: u32) -> Result<Features, Error> {
161 Ok(Features::new())
162 }
163
164 fn cluster_expansion_zoom(&self, _cluster_id: u32) -> Result<u8, Error> {
165 Ok(0)
166 }
167
168 fn world(&self) -> &WorldMapping {
169 &self.world
170 }
171}
172
173struct ClusterData {
174 clusters: cluster::Clusters,
175 world: WorldMapping,
177}
178
179impl std::fmt::Debug for ClusterData {
180 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
181 f.write_str("ClusterData")
182 }
183}
184
185impl GeoJSONData for ClusterData {
186 fn tile(&self, id: &CanonicalTileID) -> Arc<TileFeatures> {
187 Arc::new(self.clusters.tile(id.z, id.x, id.y))
188 }
189
190 fn children(&self, cluster_id: u32) -> Result<Features, Error> {
191 self.clusters.children(cluster_id).map_err(|e| Error::not_found(e.to_string()))
192 }
193
194 fn leaves(&self, cluster_id: u32, limit: u32, offset: u32) -> Result<Features, Error> {
195 self.clusters.leaves(cluster_id, limit as usize, offset as usize).map_err(|e| Error::not_found(e.to_string()))
196 }
197
198 fn cluster_expansion_zoom(&self, cluster_id: u32) -> Result<u8, Error> {
199 self.clusters.expansion_zoom(cluster_id).map_err(|e| Error::not_found(e.to_string()))
200 }
201
202 fn world(&self) -> &WorldMapping {
203 &self.world
204 }
205}
206
207fn evaluate_feature(f: &Feature<f64>, expression: &Arc<Expr>, accumulated: Option<&Value>) -> Value {
208 if let Ok(result) = evaluate_accumulated(expression.as_ref(), accumulated, f)
209 && let Some(typed) = from_expression_value::<Value>(&result)
210 {
211 return typed;
212 }
213 Value::default()
214}
215
216struct ClusterExpressions<'a>(&'a ClusterProperties);
219
220impl cluster::Aggregate for ClusterExpressions<'_> {
221 fn map(&self, properties: &PropertyMap) -> PropertyMap {
222 let mut mapped = PropertyMap::new();
223 let feature = Feature { properties: properties.clone(), ..Feature::default() };
224 for (key, (map_expression, _)) in self.0 {
225 mapped.insert(key.clone(), evaluate_feature(&feature, map_expression, None));
226 }
227 mapped
228 }
229
230 fn reduce(&self, accumulated: &mut PropertyMap, other: &PropertyMap) {
231 let feature = Feature { properties: other.clone(), ..Feature::default() };
232 for (key, (_, reduce_expression)) in self.0 {
233 if !other.contains_key(key) {
234 continue;
235 }
236 let value =
237 evaluate_feature(&feature, reduce_expression, Some(accumulated.get(key).unwrap_or(&Value::Null)));
238 accumulated.insert(key.clone(), value);
239 }
240 }
241}
242
243fn create(
247 features: Features,
248 collection: bool,
249 options: &Arc<GeoJSONOptions>,
250 world: &WorldMapping,
251) -> Result<Arc<dyn GeoJSONData>, Error> {
252 let scale: f64 = f64::from(constants::EXTENT) / constants::TILE_SIZE_D;
253 if options.cluster && collection && !features.is_empty() {
254 let cluster_options = cluster::Options {
255 max_zoom: options.cluster_max_zoom,
256 extent: constants::EXTENT as u16,
257 radius: scale * f64::from(options.cluster_radius),
258 min_points: options.cluster_min_points,
259 generate_id: options.generate_id && options.promote_id.is_none(),
260 };
261 let expressions = ClusterExpressions(&options.cluster_properties);
262 let aggregate: Option<&dyn cluster::Aggregate> =
263 (!options.cluster_properties.is_empty()).then_some(&expressions);
264 let clusters = cluster::Clusters::new(features, world, cluster_options, aggregate)
265 .map_err(|e| Error::invalid_argument(e.to_string()))?;
266 return Ok(Arc::new(ClusterData { clusters, world: world.clone() }));
267 }
268
269 let tile_options = tile::Options {
270 max_zoom: options.maxzoom,
271 tile: tile::TileOptions {
272 extent: constants::EXTENT as u16,
273 buffer: (scale * f64::from(options.buffer)).round() as u16,
274 tolerance: scale * options.tolerance,
275 line_metrics: options.line_metrics,
276 },
277 wrap: world.wraps(),
278 ..Default::default()
279 };
280 let index = tile::TileIndex::new(&features_to_world(features, world), tile_options);
281 Ok(Arc::new(IndexData { index, world: world.clone() }))
282}
283
284pub type TileFeatures = Vec<Feature<i16, Arc<PropertyMap>>>;
287pub type Features = Vec<Feature<f64>>;
288
289pub trait GeoJSONData: Send + Sync {
290 fn tile(&self, id: &CanonicalTileID) -> Arc<TileFeatures>;
293
294 fn cuts_on_demand(&self) -> bool {
298 false
299 }
300
301 fn children(&self, cluster_id: u32) -> Result<Features, Error>;
305 fn leaves(&self, cluster_id: u32, limit: u32, offset: u32) -> Result<Features, Error>;
306 fn cluster_expansion_zoom(&self, cluster_id: u32) -> Result<u8, Error>;
307
308 fn world(&self) -> &WorldMapping;
311}
312
313pub fn create_geojson_data(geojson: GeoJson, options: &Arc<GeoJSONOptions>) -> Result<Arc<dyn GeoJSONData>, Error> {
320 create_geojson_data_in(geojson, options, &WorldMapping::default())
321}
322
323pub fn create_geojson_data_in(
328 geojson: GeoJson,
329 options: &Arc<GeoJSONOptions>,
330 world: &WorldMapping,
331) -> Result<Arc<dyn GeoJSONData>, Error> {
332 let collection = matches!(geojson, GeoJson::FeatureCollection(_));
333 let mut features =
334 mln_style::feature::geojson::features(geojson).map_err(|e| Error::invalid_argument(e.to_string()))?;
335 if let Some(filter) = &options.filter {
336 features.retain(|feature| with_geojson_feature(feature, EvaluationContext::new(0.0), |cx| filter.evaluate(cx)));
337 }
338 assign_ids(&mut features, options);
339 create(features, collection, options, world)
340}
341
342fn assign_ids(features: &mut Features, options: &GeoJSONOptions) {
345 if let Some(property) = &options.promote_id {
346 for feature in features {
347 feature.id = Identifier::promoted(feature.properties.get(property));
348 }
349 } else if options.generate_id {
350 for (index, feature) in features.iter_mut().enumerate() {
351 feature.id = Identifier::Uint(index as u64);
352 }
353 }
354}
355
356fn build_geojson(data: &[u8], options: &GeoJsonSourceOptions, world: &WorldMapping) -> Option<Arc<dyn GeoJSONData>> {
359 match serde_json::from_slice(data) {
360 Ok(geojson) => build_logged(geojson, options, world),
361 Err(e) => {
362 tracing::error!(target: PARSE_STYLE, error = %e, "Failed to parse GeoJSON data");
363 None
364 }
365 }
366}
367
368fn build_inline(
371 inline: &Result<GeoJson, String>,
372 options: &GeoJsonSourceOptions,
373 world: &WorldMapping,
374) -> Option<Arc<dyn GeoJSONData>> {
375 match inline {
376 Ok(geojson) => build_logged(geojson.clone(), options, world),
377 Err(e) => {
378 tracing::error!(target: PARSE_STYLE, error = %e, "Failed to parse GeoJSON data");
379 None
380 }
381 }
382}
383
384fn build_logged(
387 geojson: GeoJson,
388 options: &GeoJsonSourceOptions,
389 world: &WorldMapping,
390) -> Option<Arc<dyn GeoJSONData>> {
391 match create_geojson_data_in(geojson, &options.options, world) {
392 Ok(data) => Some(data),
393 Err(e) => {
394 tracing::error!(target: PARSE_STYLE, error = %e, "Failed to parse GeoJSON data");
395 None
396 }
397 }
398}
399
400struct GeoJsonOrigin {
403 data: Option<(Arc<dyn GeoJSONData>, TaskGroup)>,
407 synchronous: bool,
408 warned: Option<Weak<dyn GeoJSONData>>,
410}
411
412impl GeoJsonOrigin {
413 fn draws(
418 &mut self,
419 id: &str,
420 options: &GeoJsonSourceOptions,
421 world: &WorldMapping,
422 data: &Arc<dyn GeoJSONData>,
423 ) -> bool {
424 if data.world() == world {
425 return true;
426 }
427 let warned = self.warned.as_ref().is_some_and(|warned| std::ptr::addr_eq(warned.as_ptr(), Arc::as_ptr(data)));
428 if !options.tiles_again() && !warned {
429 tracing::warn!(
430 target: GENERAL,
431 source_id = %id,
432 "GeoJSON source has data tiled for another projection and draws nothing; set its data again after \
433 changing the projection."
434 );
435 self.warned = Some(Arc::downgrade(data));
436 }
437 false
438 }
439
440 fn load(&self, cx: &mut LoadContext<'_, '_, Self>, relayout: bool) {
444 let Some((data, cuts)) = &self.data else {
445 return;
446 };
447 if relayout {
448 cx.reset();
449 }
450 let replier = cx.begin_load();
451 let cuts = (!self.synchronous).then_some(cuts);
452 if let Some(features) = request_tile(data, cx.id().canonical, replier, cuts) {
453 cx.deliver(Some(features));
454 }
455 }
456}
457
458impl DataOrigin for GeoJsonOrigin {
459 type Data = GeometryTiles;
460 type Tile = ();
461 type Reply = TileData;
462
463 fn update(&mut self, update: &mut OriginUpdate<'_, Self>) -> Option<Cover> {
464 let source = SourceData::<GeoJsonSourceType>::recover(update.source())?;
465 let synchronous = source.options.synchronous_update;
468 if synchronous != self.synchronous {
469 self.synchronous = synchronous;
470 update.clear_tiles();
471 }
472 let id = update.source().id();
473 let described = source.description::<Arc<dyn GeoJSONData>>();
474 let world = &update.map().world;
475 let data = described.filter(|data| self.draws(id, &source.options, world, data));
476 let same = match (self.data.as_ref().map(|(data, _)| data), data) {
477 (None, None) => true,
478 (Some(a), Some(b)) => std::ptr::addr_eq(Arc::as_ptr(a), Arc::as_ptr(b)),
479 _ => false,
480 };
481 if !same {
482 self.data = data.map(|data| (Arc::clone(data), TaskGroup::new(update.pool())));
483 let tiled_elsewhere = data.is_none() && described.is_some();
486 if update.map().mode != MapMode::Continuous || tiled_elsewhere {
487 update.clear_tiles();
490 } else if data.is_some() {
491 update.clear_cache();
492 let max_z = source.options.zoom_range().max;
493 let relayout = update.needs_relayout();
494 update.update_tiles(|id| id.canonical.z <= max_z, |(), cx| self.load(cx, relayout));
495 }
496 }
497 data?;
498 Some(Cover {
499 tile_size: constants::TILE_SIZE_I,
500 zoom_range: source.options.zoom_range(),
501 bounds: None,
502 round_zoom: false,
503 overscale: true,
504 prefetch: false,
505 synchronous,
506 })
507 }
508
509 fn start(&mut self, cx: &mut LoadContext<'_, '_, Self>, _copy: Option<WorldCopy<'_, ()>>) {
510 self.load(cx, false);
511 }
512
513 fn receive(&mut self, (): &mut (), features: TileData, cx: &mut LoadContext<'_, '_, Self>) {
514 cx.deliver(Some(features));
515 }
516}
517
518fn request_tile(
522 data: &Arc<dyn GeoJSONData>,
523 id: CanonicalTileID,
524 replier: Replier<TileData>,
525 cuts: Option<&TaskGroup>,
526) -> Option<TileData> {
527 let Some(cuts) = cuts.filter(|_| data.cuts_on_demand()) else {
528 return Some(TileData::Features(data.tile(&id)));
529 };
530 let slot: Arc<Mutex<Answered>> = Arc::default();
531 let task_slot = Arc::clone(&slot);
532 let data_for_task = Arc::clone(data);
533 cuts.spawn(move || {
534 let data = TileData::Features(data_for_task.tile(&id));
535 let mut slot = task_slot.lock();
536 if matches!(*slot, Answered::Later) {
537 drop(slot);
538 replier.send(data);
539 } else {
540 *slot = Answered::Now(data);
541 }
542 });
543 let answered = std::mem::replace(&mut *slot.lock(), Answered::Later);
544 match answered {
545 Answered::Now(data) => Some(data),
546 Answered::Pending | Answered::Later => None,
547 }
548}
549
550#[derive(Default)]
553enum Answered {
554 #[default]
555 Pending,
556 Now(TileData),
557 Later,
558}
559
560fn query_feature_extension(
563 source: &Source,
564 feature: &mln_engine::tile::feature::Feature,
565 extension: &str,
566 extension_field: &str,
567 args: Option<&PropertyMap>,
568) -> Result<FeatureExtensionValue, Error> {
569 if extension != "supercluster" {
570 return Ok(FeatureExtensionValue::default());
571 }
572 let Some(cluster_id) = uint_property(&feature.properties, "cluster_id") else {
573 return Ok(FeatureExtensionValue::default());
574 };
575 let Some(json_data) = geojson_data(source) else {
576 return Ok(FeatureExtensionValue::default());
577 };
578 supercluster_extension(&**json_data, extension_field, cluster_id as u32, args)
579 .unwrap_or_else(|| Ok(FeatureExtensionValue::default()))
580}
581
582fn uint_property(properties: &PropertyMap, name: &str) -> Option<u64> {
584 match properties.get(name) {
585 Some(Value::Uint(value)) => Some(*value),
586 _ => None,
587 }
588}
589
590fn supercluster_extension(
593 cluster_data: &dyn GeoJSONData,
594 extension_field: &str,
595 cluster_id: u32,
596 args: Option<&PropertyMap>,
597) -> Option<Result<FeatureExtensionValue, Error>> {
598 Some(match extension_field {
599 "children" => cluster_data.children(cluster_id).map(FeatureExtensionValue::FeatureCollection),
600 "leaves" => {
601 let (limit, offset) = match args.and_then(|args| Some((uint_property(args, "limit")?, args))) {
603 Some((limit, args)) => (limit as u32, uint_property(args, "offset").map_or(0, |offset| offset as u32)),
604 None => (10, 0),
605 };
606 cluster_data.leaves(cluster_id, limit, offset).map(FeatureExtensionValue::FeatureCollection)
607 }
608 "expansion-zoom" => cluster_data
609 .cluster_expansion_zoom(cluster_id)
610 .map(|zoom| FeatureExtensionValue::Value(Value::Uint(u64::from(zoom)))),
611 _ => return None,
612 })
613}
614
615#[must_use]
617pub fn geojson_data(source: &Source) -> Option<&Arc<dyn GeoJSONData>> {
618 SourceData::<GeoJsonSourceType>::recover(source)?.description::<Arc<dyn GeoJSONData>>()
619}
620
621pub fn set_data(id: impl Into<String>, geojson: Option<Arc<dyn GeoJSONData>>) -> Edit {
625 Edit::update_source::<GeoJsonSourceType>(id, "a GeoJSON source", |data| {
626 data.options.url = None;
627 data.options.inline = None;
628 data.description = geojson.map(|geojson| -> mln_style::source::ErasedDescription { Arc::new(geojson) });
629 data.load += 1;
630 true
631 })
632}
633
634impl std::fmt::Debug for dyn GeoJSONData {
637 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
638 f.debug_struct("GeoJSONData").finish_non_exhaustive()
639 }
640}
641
642#[cfg(test)]
643mod crs_test;