Skip to main content

mln_engine/plugin/
layer.rs

1//! Direct in-process `mln_plugin::LayerPlugin` host adapter built on
2//! `DynamicLayerType`.
3
4use std::any::Any;
5use std::borrow::Cow;
6use std::rc::Rc;
7use std::sync::{Arc, LazyLock};
8use std::time::Duration;
9
10use geojson::GeoJson;
11use glam::Vec2 as GlamVec2;
12use mln_gfx::color_mode::ColorMode as GfxColorMode;
13use mln_gfx::cull_face_mode::CullFaceMode as GfxCullFaceMode;
14use mln_gfx::draw_mode::DrawMode as GfxDrawMode;
15use mln_gfx::gfx_types::DrawModeType;
16use mln_gfx::gpu::TextureFormat as GfxTextureFormat;
17use mln_gfx::projection_variant::ProjectionVariant as GfxProjectionVariant;
18use mln_gfx::shaders::bindings::MAX_TEXTURES;
19use mln_gfx::shaders::layer_ubo::ProjectionUBO;
20use mln_gfx::shaders::program::Program as GfxProgram;
21use mln_gfx::texture2d::SamplerState as GfxSamplerState;
22use mln_gfx::types::{
23    CullFaceSideType, CullFaceWindingType, DepthMaskType, TextureChannelDataType, TextureFilterType, TextureWrapType,
24};
25use mln_gfx::{Rgba, Size};
26use mln_plugin::backend::{
27    DrawGroupBackend, DrawsBackend, EvaluateCxBackend, EvaluatedLayerBackend, FrameBackend, FrameQueryCxMutBackend,
28    FrameQueryCxReadBackend, GroundHeightsHandle, HitCxBackend, HostBackend, IndexBufferHandle, MeshHandle,
29    PaintAttributesHandle, PrepareCxMutBackend, PrepareCxReadBackend, ResourcesBackend, TargetHandle, TextureHandle,
30    TileBackend, TileBuildCxBackend, TileGeometryBackend, TileGeometryBuilderBackend, UpdateCxMutBackend,
31    UpdateCxReadBackend, VertexBufferHandle, ViewBackend,
32};
33use mln_plugin::{
34    Alignment, CollisionShape, CollisionShapeKind, Color as PluginColor, ColorMode, Composite as PluginComposite,
35    CullFaceMode, CullFaceSide, CullFaceWinding, DepthMode, DrawGroup, DrawMode, DrawOptions,
36    DrawRange as PluginDrawRange, Draws as PluginDraws, Error as PluginError, EvaluateCx, EvaluatedLayer,
37    Evaluation as PluginEvaluation, FeatureType as PluginFeatureType, Frame as PluginFrame, FrameInfo, FrameQueryCx,
38    GroundHeights as PluginGroundHeights, Hit as PluginHit, HitCx, HitInfo, Host, IndexBuffer as PluginIndexBuffer,
39    LatLng as PluginLatLng, LayerBlend, LayerInput, LayerInstance, LayerPlugin, LendAt as PluginLendAt,
40    LoadedFeatureInfo, MapMode as PluginMapMode, Mesh as PluginMesh, MeshDesc as PluginMeshDesc,
41    PaintAttributes as PluginPaintAttributes, PointI16, PrepareCx, ProjectedPoint, ProjectionUbo, ProjectionVariant,
42    PropertyDefault, PropertyScope, RasterTileInfo, RenderPasses, Resources as PluginResources, Result as PluginResult,
43    SamplerState, ScreenPoint, Status, Target as PluginTarget, TerrainMode, Texture as PluginTexture,
44    TextureChannelType, TextureFilter, TextureFormat, TextureWrap, Tile, TileBuildCx, TileChanges, TileCx,
45    TileGeometry, TileGeometryBuilder, TileId, TileOrder as PluginTileOrder, TileTransform as PluginTileTransform,
46    UpdateCx, Vec2 as PluginVec2, VertexBinding as PluginVertexBinding, VertexBuffer as PluginVertexBuffer,
47    View as PluginView, ViewInfo,
48};
49use mln_style::PropertyEvaluationParameters;
50use mln_style::color::Color;
51use mln_style::crs::WorldMapping;
52use mln_style::error::Error as StyleError;
53use mln_style::expression::{EvaluationContext, ValueConverter};
54use mln_style::feature::{FeatureState, GeometryCollection, GeometryCoordinate, GeometryTileFeature};
55use mln_style::geo::{LatLng, WrapMode};
56use mln_style::geometry::{FeatureType, Point};
57use mln_style::hash::HashSet;
58use mln_style::layer::dynamic::{
59    DynamicDefault, DynamicEvaluated, DynamicLayerDesc, DynamicPropertyDesc, DynamicPropertyValue,
60    DynamicStyleLayerType, MAX_DYNAMIC_DATA_DRIVEN_PAINT, MAX_DYNAMIC_PROPERTIES,
61};
62use mln_style::layer::{LayerTypeInfo, PropertyScope as StylePropertyScope, SourceKind};
63use mln_style::property::evaluated::Evaluated;
64use mln_style::property::value::PropertyValue;
65use mln_style::range::Range;
66use mln_style::tile_id::CanonicalTileID;
67use mln_style::time::Instant;
68use mln_style::types::{AlignmentType, CirclePitchScaleType, LayerBlendType, Rotation, TranslateAnchorType};
69
70use crate::camera::{TileProjector, View};
71use crate::draw::draws::{Draws, Group, LayerFrame};
72use crate::draw::ground::{FrameGround, GroundHeights, height_binding};
73use crate::draw::projection::{TileTransform, globe_extrude_scale, tile_projection};
74use crate::draw::{
75    Composite, Depth, Draw, DrawRange, IndexBuffer, Mesh, MeshDesc, Resources, Target, Texture, Textures, Uniforms,
76    VertexAttribute, VertexBinding, VertexBuffer,
77};
78use crate::layer::binders::{PaintAttributes, PaintBinders as _};
79use crate::layer::bucket_geometry::{bucket_indexes, bucket_vertices};
80use crate::layer::dynamic::{
81    DynamicBucket, DynamicBuildCx, DynamicEvaluateCx, DynamicEvaluatedLayer, DynamicFrameQuery, DynamicFrameTile,
82    DynamicLayerConfig, DynamicLayerHandler, DynamicLayerInstance, DynamicLayerType, DynamicLayerValues,
83    DynamicPrepareCx, DynamicTileCx, DynamicTileData, DynamicUpdateCx,
84};
85use crate::layer::layer_drawing::TileMap;
86use crate::layer::render_layer::{Evaluation, OnTerrain};
87use crate::map::MapMode;
88use crate::placement::{Shape, TestedShape};
89use crate::plugin::program::{
90    EngineProgram, create_program, resolve_attribute_name, resolve_uniform_block, to_attribute_format,
91};
92use crate::query::feature_index::{Hit, QueryRegion};
93use crate::query::translate_query_geometry;
94use crate::render::pass::RenderPass;
95use crate::render::shared_targets::SharedTargets;
96use crate::render::tile::RenderTile;
97use crate::source::render_source::TileOrder;
98use crate::tile::feature::Feature;
99use crate::tile::{OverscaledTileID, TileLayer, UnwrappedTileID};
100use crate::tile_store::TileLodMode;
101use crate::tile_store::tile_cover::{TileCoverParameters, tile_cover};
102
103// ---------------------------------------------------------------------------
104// Time conversion
105// ---------------------------------------------------------------------------
106
107static TIME_ORIGIN: LazyLock<Instant> = LazyLock::new(Instant::now);
108
109fn instant_to_ns(instant: Instant) -> i64 {
110    let origin = *TIME_ORIGIN;
111    if let Some(after) = instant.checked_duration_since(origin) {
112        i64::try_from(after.as_nanos()).unwrap_or(i64::MAX)
113    } else if let Some(before) = origin.checked_duration_since(instant) {
114        let nanos = i64::try_from(before.as_nanos()).unwrap_or(i64::MAX);
115        nanos.saturating_neg()
116    } else {
117        0
118    }
119}
120
121// ---------------------------------------------------------------------------
122// Value conversions
123// ---------------------------------------------------------------------------
124
125fn to_color(c: PluginColor) -> Color {
126    Color::rgba(c.r, c.g, c.b, c.a.clamp(0.0, 1.0))
127}
128
129fn from_color(c: Color) -> PluginColor {
130    let [r, g, b, a] = c.straight_rgba();
131    PluginColor::rgba(r, g, b, a)
132}
133
134fn to_lat_lng(ll: PluginLatLng) -> PluginResult<LatLng> {
135    if !ll.latitude.is_finite() || !ll.longitude.is_finite() {
136        return Err(PluginError::invalid_argument("latitude and longitude must be finite"));
137    }
138    Ok(LatLng::saturating(ll.latitude, ll.longitude, WrapMode::Unwrapped))
139}
140
141fn from_lat_lng(ll: LatLng) -> PluginLatLng {
142    PluginLatLng::new(ll.latitude(), ll.longitude())
143}
144
145fn from_overscaled_tile_id(id: OverscaledTileID) -> TileId {
146    TileId {
147        overscaled_z: u32::from(id.overscaled_z),
148        wrap: i32::from(id.wrap),
149        canonical_z: u32::from(id.canonical.z),
150        canonical_x: id.canonical.x,
151        canonical_y: id.canonical.y,
152    }
153}
154
155fn from_unwrapped_tile_id(id: UnwrappedTileID) -> TileId {
156    TileId {
157        overscaled_z: u32::from(id.canonical.z),
158        wrap: i32::from(id.wrap),
159        canonical_z: u32::from(id.canonical.z),
160        canonical_x: id.canonical.x,
161        canonical_y: id.canonical.y,
162    }
163}
164
165fn overscaled_tile_id(id: TileId) -> PluginResult<OverscaledTileID> {
166    let oz = u8::try_from(id.overscaled_z).map_err(|_| PluginError::invalid_argument("overscaled_z out of range"))?;
167    let wrap = i16::try_from(id.wrap).map_err(|_| PluginError::invalid_argument("tile wrap out of range"))?;
168    let cz = u8::try_from(id.canonical_z).map_err(|_| PluginError::invalid_argument("canonical_z out of range"))?;
169    Ok(OverscaledTileID::new(oz, wrap, CanonicalTileID::new(cz, id.canonical_x, id.canonical_y)))
170}
171
172fn unwrapped_tile_id(id: TileId) -> PluginResult<UnwrappedTileID> {
173    let wrap = i16::try_from(id.wrap).map_err(|_| PluginError::invalid_argument("tile wrap out of range"))?;
174    let cz = u8::try_from(id.canonical_z).map_err(|_| PluginError::invalid_argument("canonical_z out of range"))?;
175    Ok(UnwrappedTileID::with_wrap(wrap, CanonicalTileID::new(cz, id.canonical_x, id.canonical_y)))
176}
177
178fn from_projection_variant(v: GfxProjectionVariant) -> ProjectionVariant {
179    match v {
180        GfxProjectionVariant::Mercator => ProjectionVariant::Mercator,
181        GfxProjectionVariant::Globe => ProjectionVariant::Globe,
182        GfxProjectionVariant::Terrain => ProjectionVariant::MercatorStanding,
183        GfxProjectionVariant::GlobeTerrain => ProjectionVariant::GlobeStanding,
184    }
185}
186
187fn to_projection_variant(v: ProjectionVariant) -> GfxProjectionVariant {
188    match v {
189        ProjectionVariant::Mercator => GfxProjectionVariant::Mercator,
190        ProjectionVariant::Globe => GfxProjectionVariant::Globe,
191        ProjectionVariant::MercatorStanding => GfxProjectionVariant::Terrain,
192        ProjectionVariant::GlobeStanding => GfxProjectionVariant::GlobeTerrain,
193    }
194}
195
196fn from_projection_ubo(u: ProjectionUBO) -> ProjectionUbo {
197    ProjectionUbo {
198        matrix: u.matrix,
199        fallback_matrix: u.fallback_matrix,
200        tile_mercator_coords: u.tile_mercator_coords,
201        clipping_plane: u.clipping_plane,
202        projection_transition: u.projection_transition,
203        depth_offset: u.depth_offset,
204        translate: u.translate,
205        anchor: u.anchor,
206        anchor_angles: u.anchor_angles,
207    }
208}
209
210fn to_projection_ubo(u: &ProjectionUbo) -> ProjectionUBO {
211    ProjectionUBO {
212        matrix: u.matrix,
213        fallback_matrix: u.fallback_matrix,
214        tile_mercator_coords: u.tile_mercator_coords,
215        clipping_plane: u.clipping_plane,
216        projection_transition: u.projection_transition,
217        depth_offset: u.depth_offset,
218        translate: u.translate,
219        anchor: u.anchor,
220        anchor_angles: u.anchor_angles,
221    }
222}
223
224fn to_translate_anchor(a: Alignment) -> TranslateAnchorType {
225    match a {
226        Alignment::Map => TranslateAnchorType::Map,
227        Alignment::Viewport => TranslateAnchorType::Viewport,
228    }
229}
230
231fn to_alignment_type(a: Alignment) -> AlignmentType {
232    match a {
233        Alignment::Map => AlignmentType::Map,
234        Alignment::Viewport => AlignmentType::Viewport,
235    }
236}
237
238fn to_pitch_scale_type(a: Alignment) -> CirclePitchScaleType {
239    match a {
240        Alignment::Map => CirclePitchScaleType::Map,
241        Alignment::Viewport => CirclePitchScaleType::Viewport,
242    }
243}
244
245fn from_feature_type(t: FeatureType) -> PluginFeatureType {
246    match t {
247        FeatureType::Unknown => PluginFeatureType::Unknown,
248        FeatureType::Point => PluginFeatureType::Point,
249        FeatureType::LineString => PluginFeatureType::LineString,
250        FeatureType::Polygon => PluginFeatureType::Polygon,
251    }
252}
253
254fn from_map_mode(m: MapMode) -> PluginMapMode {
255    match m {
256        MapMode::Continuous => PluginMapMode::Continuous,
257        MapMode::Static => PluginMapMode::Static,
258        MapMode::Tile => PluginMapMode::Tile,
259    }
260}
261
262fn from_render_pass(pass: RenderPass) -> RenderPasses {
263    let mut out = RenderPasses::NONE;
264    if pass & RenderPass::OPAQUE != RenderPass::NONE {
265        out = out.union(RenderPasses::OPAQUE);
266    }
267    if pass & RenderPass::TRANSLUCENT != RenderPass::NONE {
268        out = out.union(RenderPasses::TRANSLUCENT);
269    }
270    out
271}
272
273fn to_render_pass(pass: RenderPasses) -> RenderPass {
274    let mut out = RenderPass::NONE;
275    if pass.contains(RenderPasses::OPAQUE) {
276        out |= RenderPass::OPAQUE;
277    }
278    if pass.contains(RenderPasses::TRANSLUCENT) {
279        out |= RenderPass::TRANSLUCENT;
280    }
281    out
282}
283
284fn to_color_mode(m: ColorMode) -> GfxColorMode {
285    match m {
286        ColorMode::AlphaBlended => GfxColorMode::alpha_blended(),
287        ColorMode::Unblended => GfxColorMode::unblended(),
288        ColorMode::Additive => GfxColorMode::additive(),
289        ColorMode::Disabled => GfxColorMode::disabled(),
290    }
291}
292
293fn to_cull_face_mode(m: CullFaceMode) -> GfxCullFaceMode {
294    let side = match m.side {
295        CullFaceSide::Back => CullFaceSideType::Back,
296        CullFaceSide::Front => CullFaceSideType::Front,
297        CullFaceSide::FrontAndBack => CullFaceSideType::FrontAndBack,
298    };
299    let winding = match m.winding {
300        CullFaceWinding::Ccw => CullFaceWindingType::CounterClockwise,
301        CullFaceWinding::Cw => CullFaceWindingType::Clockwise,
302    };
303    GfxCullFaceMode { enabled: m.enabled, side, winding }
304}
305
306fn to_draw_mode(m: DrawMode) -> GfxDrawMode {
307    match m {
308        DrawMode::Triangles => GfxDrawMode::Triangles(),
309        DrawMode::TriangleStrip => GfxDrawMode::TriangleStrip(),
310        DrawMode::TriangleFan => GfxDrawMode { kind: DrawModeType::TriangleFan, size: 0.0 },
311        DrawMode::Lines(w) => GfxDrawMode::Lines(if w > 0.0 { w } else { 1.0 }),
312        DrawMode::LineLoop(w) => GfxDrawMode { kind: DrawModeType::LineLoop, size: if w > 0.0 { w } else { 1.0 } },
313        DrawMode::LineStrip(w) => GfxDrawMode { kind: DrawModeType::LineStrip, size: if w > 0.0 { w } else { 1.0 } },
314        DrawMode::Points(s) => GfxDrawMode { kind: DrawModeType::Points, size: if s > 0.0 { s } else { 1.0 } },
315    }
316}
317
318fn to_draw_options(o: DrawOptions) -> Draw {
319    let depth = match o.depth {
320        DepthMode::Layer { sub_layer, write } => {
321            Depth::Layer { sub_layer, mask: if write { DepthMaskType::ReadWrite } else { DepthMaskType::ReadOnly } }
322        }
323        DepthMode::Off => Depth::Off,
324        DepthMode::Volume { write } => {
325            Depth::Volume { mask: if write { DepthMaskType::ReadWrite } else { DepthMaskType::ReadOnly } }
326        }
327    };
328    Draw { order: o.order, opaque: o.opaque, depth, clip: o.clip }
329}
330
331fn to_layer_blend(b: LayerBlend) -> LayerBlendType {
332    match b {
333        LayerBlend::Normal => LayerBlendType::Normal,
334        LayerBlend::Multiply => LayerBlendType::Multiply,
335        LayerBlend::Screen => LayerBlendType::Screen,
336        LayerBlend::Overlay => LayerBlendType::Overlay,
337        LayerBlend::Darken => LayerBlendType::Darken,
338        LayerBlend::Lighten => LayerBlendType::Lighten,
339        LayerBlend::ColorDodge => LayerBlendType::ColorDodge,
340        LayerBlend::ColorBurn => LayerBlendType::ColorBurn,
341        LayerBlend::HardLight => LayerBlendType::HardLight,
342        LayerBlend::SoftLight => LayerBlendType::SoftLight,
343        LayerBlend::Difference => LayerBlendType::Difference,
344        LayerBlend::Exclusion => LayerBlendType::Exclusion,
345        LayerBlend::Hue => LayerBlendType::Hue,
346        LayerBlend::Saturation => LayerBlendType::Saturation,
347        LayerBlend::Color => LayerBlendType::Color,
348        LayerBlend::Luminosity => LayerBlendType::Luminosity,
349        LayerBlend::PlusLighter => LayerBlendType::PlusLighter,
350    }
351}
352
353fn to_texture_format(f: TextureFormat) -> GfxTextureFormat {
354    match f {
355        TextureFormat::Rgba8Unorm => GfxTextureFormat::Rgba8Unorm,
356        TextureFormat::R8Unorm => GfxTextureFormat::R8Unorm,
357        TextureFormat::A8Unorm => GfxTextureFormat::A8Unorm,
358        TextureFormat::R16Float => GfxTextureFormat::R16Float,
359        TextureFormat::R32Float => GfxTextureFormat::R32Float,
360        TextureFormat::Rgba16Float => GfxTextureFormat::Rgba16Float,
361        TextureFormat::Rgba32Float => GfxTextureFormat::Rgba32Float,
362    }
363}
364
365fn to_channel_type(c: TextureChannelType) -> TextureChannelDataType {
366    match c {
367        TextureChannelType::UnsignedByte => TextureChannelDataType::UnsignedByte,
368        TextureChannelType::HalfFloat => TextureChannelDataType::HalfFloat,
369        TextureChannelType::Float => TextureChannelDataType::Float,
370    }
371}
372
373fn to_sampler(s: SamplerState) -> GfxSamplerState {
374    GfxSamplerState {
375        filter: match s.filter {
376            TextureFilter::Nearest => TextureFilterType::Nearest,
377            TextureFilter::Linear => TextureFilterType::Linear,
378        },
379        wrap_u: match s.wrap_u {
380            TextureWrap::Clamp => TextureWrapType::Clamp,
381            TextureWrap::Repeat => TextureWrapType::Repeat,
382        },
383        wrap_v: match s.wrap_v {
384            TextureWrap::Clamp => TextureWrapType::Clamp,
385            TextureWrap::Repeat => TextureWrapType::Repeat,
386        },
387        max_anisotropy: s.max_anisotropy.max(1),
388        mipmapped: s.mipmapped,
389    }
390}
391
392fn to_evaluation(ev: PluginEvaluation, time_point: Option<Instant>) -> Evaluation {
393    let opaque = ev.passes.contains(RenderPasses::OPAQUE);
394    let draws = opaque || ev.passes.contains(RenderPasses::TRANSLUCENT);
395    let solid = ev.solid_color.map(to_color);
396    let repaint_at = ev.repaint_after_ns.and_then(|ns| {
397        let t = time_point?;
398        t.checked_add(Duration::from_nanos(ns))
399    });
400    Evaluation {
401        draws,
402        opaque,
403        solid,
404        drapes_by_bearing: ev.drapes_by_bearing,
405        drapes_by_zoom: ev.drapes_by_zoom,
406        needs_repaint: ev.needs_repaint,
407        repaint_at,
408        reads_collision_shapes: ev.reads_collision_shapes,
409    }
410}
411
412fn to_draw_range(r: PluginDrawRange) -> DrawRange {
413    DrawRange {
414        first_index: r.first_index,
415        index_count: r.index_count,
416        base_vertex: r.base_vertex,
417        first_instance: r.first_instance,
418        instance_count: r.instance_count,
419    }
420}
421
422fn from_draw_range(r: DrawRange) -> PluginDrawRange {
423    PluginDrawRange {
424        first_index: r.first_index,
425        index_count: r.index_count,
426        base_vertex: r.base_vertex,
427        first_instance: r.first_instance,
428        instance_count: r.instance_count,
429    }
430}
431
432fn convert_vertex_binding(
433    program: &'static GfxProgram,
434    binding: &PluginVertexBinding<'_>,
435) -> PluginResult<VertexBinding> {
436    let buf = downcast_vertex_buffer(binding.buffer)?;
437    if binding.stride == 0 {
438        return Err(PluginError::invalid_argument("vertex_binding.stride must not be zero"));
439    }
440    let mut attrs = Vec::with_capacity(binding.attributes.len());
441    for attr in binding.attributes {
442        let static_name = resolve_attribute_name(program, attr.name)?;
443        attrs.push(VertexAttribute {
444            name: static_name,
445            format: to_attribute_format(attr.format),
446            offset: attr.offset,
447        });
448    }
449    Ok(VertexBinding::new(buf, binding.stride, attrs).starting_at(binding.first_vertex))
450}
451
452// ---------------------------------------------------------------------------
453// Host & owned GPU resource handles
454// ---------------------------------------------------------------------------
455
456struct EngineHost;
457
458impl HostBackend for EngineHost {
459    fn create_program(&self, desc: &mln_plugin::ProgramDesc<'_>) -> PluginResult<mln_plugin::Program> {
460        create_program(desc)
461    }
462
463    fn create_ground_heights(&self) -> PluginResult<PluginGroundHeights> {
464        Ok(PluginGroundHeights::from_handle(Box::new(EngineGroundHeights { inner: GroundHeights::default() })))
465    }
466}
467
468#[derive(Debug)]
469struct EngineVertexBuffer {
470    inner: VertexBuffer,
471}
472
473impl VertexBufferHandle for EngineVertexBuffer {
474    fn as_any(&self) -> &dyn Any {
475        self
476    }
477}
478
479#[derive(Debug)]
480struct EngineIndexBuffer {
481    inner: IndexBuffer,
482}
483
484impl IndexBufferHandle for EngineIndexBuffer {
485    fn as_any(&self) -> &dyn Any {
486        self
487    }
488}
489
490#[derive(Debug)]
491struct EngineTexture {
492    inner: Texture,
493}
494
495impl TextureHandle for EngineTexture {
496    fn as_any(&self) -> &dyn Any {
497        self
498    }
499}
500
501#[derive(Debug)]
502struct EngineTarget {
503    inner: Target,
504}
505
506impl TargetHandle for EngineTarget {
507    fn texture(&self) -> Option<PluginTexture> {
508        Some(PluginTexture::from_handle(Box::new(EngineTexture { inner: self.inner.texture().clone() })))
509    }
510
511    fn as_any(&self) -> &dyn Any {
512        self
513    }
514}
515
516#[derive(Debug)]
517struct EnginePaintAttributes {
518    inner: PaintAttributes,
519}
520
521impl PaintAttributesHandle for EnginePaintAttributes {
522    fn as_any(&self) -> &dyn Any {
523        self
524    }
525}
526
527struct EngineMesh {
528    inner: Mesh,
529}
530
531impl std::fmt::Debug for EngineMesh {
532    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
533        f.debug_struct("EngineMesh").field("seq", &self.inner.seq()).finish_non_exhaustive()
534    }
535}
536
537impl MeshHandle for EngineMesh {
538    fn seq(&self) -> i64 {
539        self.inner.seq()
540    }
541
542    fn as_any(&self) -> &dyn Any {
543        self
544    }
545}
546
547struct EngineGroundHeights {
548    inner: GroundHeights,
549}
550
551impl std::fmt::Debug for EngineGroundHeights {
552    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
553        f.debug_struct("EngineGroundHeights").finish_non_exhaustive()
554    }
555}
556
557impl GroundHeightsHandle for EngineGroundHeights {
558    fn as_any_mut(&mut self) -> &mut dyn Any {
559        self
560    }
561}
562
563// ---------------------------------------------------------------------------
564// Downcast helpers
565// ---------------------------------------------------------------------------
566
567fn downcast_program(p: &mln_plugin::Program) -> PluginResult<&'static GfxProgram> {
568    p.handle()
569        .as_any()
570        .downcast_ref::<EngineProgram>()
571        .map(EngineProgram::inner)
572        .ok_or_else(|| PluginError::invalid_argument("program was not created by the mln_engine host"))
573}
574
575fn downcast_vertex_buffer(vb: &PluginVertexBuffer) -> PluginResult<&VertexBuffer> {
576    vb.handle()
577        .as_any()
578        .downcast_ref::<EngineVertexBuffer>()
579        .map(|b| &b.inner)
580        .ok_or_else(|| PluginError::invalid_argument("vertex buffer was not created by the mln_engine host"))
581}
582
583fn downcast_index_buffer(ib: &PluginIndexBuffer) -> PluginResult<&IndexBuffer> {
584    ib.handle()
585        .as_any()
586        .downcast_ref::<EngineIndexBuffer>()
587        .map(|b| &b.inner)
588        .ok_or_else(|| PluginError::invalid_argument("index buffer was not created by the mln_engine host"))
589}
590
591fn downcast_texture(tex: &PluginTexture) -> PluginResult<&Texture> {
592    tex.handle()
593        .as_any()
594        .downcast_ref::<EngineTexture>()
595        .map(|t| &t.inner)
596        .ok_or_else(|| PluginError::invalid_argument("texture was not created by the mln_engine host"))
597}
598
599fn downcast_target(target: &PluginTarget) -> PluginResult<&Target> {
600    target
601        .handle()
602        .as_any()
603        .downcast_ref::<EngineTarget>()
604        .map(|t| &t.inner)
605        .ok_or_else(|| PluginError::invalid_argument("target was not created by the mln_engine host"))
606}
607
608fn downcast_paint_attributes(paint: &PluginPaintAttributes) -> PluginResult<&PaintAttributes> {
609    paint
610        .handle()
611        .as_any()
612        .downcast_ref::<EnginePaintAttributes>()
613        .map(|p| &p.inner)
614        .ok_or_else(|| PluginError::invalid_argument("paint attributes were not created by the mln_engine host"))
615}
616
617fn downcast_mesh(mesh: &PluginMesh) -> PluginResult<&Mesh> {
618    mesh.handle()
619        .as_any()
620        .downcast_ref::<EngineMesh>()
621        .map(|m| &m.inner)
622        .ok_or_else(|| PluginError::invalid_argument("mesh was not created by the mln_engine host"))
623}
624
625fn downcast_ground_heights_mut(heights: &mut PluginGroundHeights) -> PluginResult<&mut GroundHeights> {
626    heights
627        .handle_mut()
628        .as_any_mut()
629        .downcast_mut::<EngineGroundHeights>()
630        .map(|h| &mut h.inner)
631        .ok_or_else(|| PluginError::invalid_argument("ground heights were not created by the mln_engine host"))
632}
633
634// ---------------------------------------------------------------------------
635// EvaluatedLayer backends
636// ---------------------------------------------------------------------------
637
638fn eval_paint_is_constant(layer: &DynamicEvaluatedLayer, slot: u32) -> bool {
639    layer.paint.get(slot as usize).is_some_and(DynamicEvaluated::is_constant)
640}
641
642fn eval_paint_f32(layer: &DynamicEvaluatedLayer, slot: u32) -> PluginResult<f32> {
643    layer
644        .paint
645        .get(slot as usize)
646        .and_then(DynamicEvaluated::uniform_float)
647        .ok_or_else(|| PluginError::invalid_argument(format!("paint slot {slot} is not a float property")))
648}
649
650fn eval_paint_f32_constant_or(layer: &DynamicEvaluatedLayer, slot: u32, fallback: f32) -> PluginResult<f32> {
651    let prop = layer
652        .paint
653        .get(slot as usize)
654        .ok_or_else(|| PluginError::invalid_argument(format!("paint slot {slot} out of range")))?;
655    if prop.as_float().is_none() {
656        return Err(PluginError::invalid_argument(format!("paint slot {slot} is not a float property")));
657    }
658    Ok(prop.constant_or_float(fallback))
659}
660
661fn eval_paint_bool(layer: &DynamicEvaluatedLayer, slot: u32) -> PluginResult<bool> {
662    layer
663        .paint
664        .get(slot as usize)
665        .and_then(DynamicEvaluated::uniform_bool)
666        .ok_or_else(|| PluginError::invalid_argument(format!("paint slot {slot} is not a bool property")))
667}
668
669fn eval_paint_color(layer: &DynamicEvaluatedLayer, slot: u32) -> PluginResult<PluginColor> {
670    layer
671        .paint
672        .get(slot as usize)
673        .and_then(DynamicEvaluated::uniform_color)
674        .map(from_color)
675        .ok_or_else(|| PluginError::invalid_argument(format!("paint slot {slot} is not a color property")))
676}
677
678fn eval_paint_color_constant_or(
679    layer: &DynamicEvaluatedLayer,
680    slot: u32,
681    fallback: PluginColor,
682) -> PluginResult<PluginColor> {
683    let prop = layer
684        .paint
685        .get(slot as usize)
686        .ok_or_else(|| PluginError::invalid_argument(format!("paint slot {slot} out of range")))?;
687    if prop.as_color().is_none() {
688        return Err(PluginError::invalid_argument(format!("paint slot {slot} is not a color property")));
689    }
690    Ok(from_color(prop.constant_or_color(to_color(fallback))))
691}
692
693fn eval_paint_vec2(layer: &DynamicEvaluatedLayer, slot: u32) -> PluginResult<PluginVec2> {
694    let [x, y] = layer
695        .paint
696        .get(slot as usize)
697        .and_then(DynamicEvaluated::uniform_vec2)
698        .ok_or_else(|| PluginError::invalid_argument(format!("paint slot {slot} is not a vec2 property")))?;
699    Ok(PluginVec2::new(x, y))
700}
701
702fn eval_paint_lat_lng(layer: &DynamicEvaluatedLayer, slot: u32) -> PluginResult<PluginLatLng> {
703    layer
704        .paint
705        .get(slot as usize)
706        .and_then(DynamicEvaluated::uniform_lat_lng)
707        .map(from_lat_lng)
708        .ok_or_else(|| PluginError::invalid_argument(format!("paint slot {slot} is not a lat_lng property")))
709}
710
711fn eval_paint_rotation_degrees(layer: &DynamicEvaluatedLayer, slot: u32) -> PluginResult<f32> {
712    layer
713        .paint
714        .get(slot as usize)
715        .and_then(DynamicEvaluated::uniform_rotation)
716        .map(|r| r.angle() as f32)
717        .ok_or_else(|| PluginError::invalid_argument(format!("paint slot {slot} is not a rotation property")))
718}
719
720fn eval_paint_str(layer: &DynamicEvaluatedLayer, slot: u32) -> PluginResult<&str> {
721    layer
722        .paint
723        .get(slot as usize)
724        .and_then(|v| v.uniform_str())
725        .ok_or_else(|| PluginError::invalid_argument(format!("paint slot {slot} is not a string/enum property")))
726}
727
728fn eval_paint_enum(layer: &DynamicEvaluatedLayer, slot: u32) -> PluginResult<u32> {
729    let idx = slot as usize;
730    let desc = layer
731        .style
732        .dynamic_type()
733        .paint_property(idx)
734        .ok_or_else(|| PluginError::invalid_argument(format!("paint slot {slot} out of range")))?;
735    let DynamicDefault::Enum { variants, default } = &desc.default else {
736        return Err(PluginError::invalid_argument(format!("paint slot {slot} is not an enum property")));
737    };
738    layer
739        .paint
740        .get(idx)
741        .and_then(|v| v.enum_index(variants, *default))
742        .ok_or_else(|| PluginError::invalid_argument(format!("paint slot {slot} is not an enum property")))
743}
744
745/// `'static` evaluated layer wrapper used whenever an `Arc<DynamicEvaluatedLayer>`
746/// is available (supporting `as_any` for `Tile::paint_attributes`).
747struct EngineArcEvaluatedLayer {
748    inner: Arc<DynamicEvaluatedLayer>,
749}
750
751impl EvaluatedLayerBackend for EngineArcEvaluatedLayer {
752    fn id(&self) -> &str {
753        &self.inner.style.id
754    }
755    fn paint_is_constant(&self, slot: u32) -> bool {
756        eval_paint_is_constant(&self.inner, slot)
757    }
758    fn paint_f32(&self, slot: u32) -> PluginResult<f32> {
759        eval_paint_f32(&self.inner, slot)
760    }
761    fn paint_f32_constant_or(&self, slot: u32, fallback: f32) -> PluginResult<f32> {
762        eval_paint_f32_constant_or(&self.inner, slot, fallback)
763    }
764    fn paint_bool(&self, slot: u32) -> PluginResult<bool> {
765        eval_paint_bool(&self.inner, slot)
766    }
767    fn paint_color(&self, slot: u32) -> PluginResult<PluginColor> {
768        eval_paint_color(&self.inner, slot)
769    }
770    fn paint_color_constant_or(&self, slot: u32, fallback: PluginColor) -> PluginResult<PluginColor> {
771        eval_paint_color_constant_or(&self.inner, slot, fallback)
772    }
773    fn paint_vec2(&self, slot: u32) -> PluginResult<PluginVec2> {
774        eval_paint_vec2(&self.inner, slot)
775    }
776    fn paint_lat_lng(&self, slot: u32) -> PluginResult<PluginLatLng> {
777        eval_paint_lat_lng(&self.inner, slot)
778    }
779    fn paint_rotation_degrees(&self, slot: u32) -> PluginResult<f32> {
780        eval_paint_rotation_degrees(&self.inner, slot)
781    }
782    fn paint_str(&self, slot: u32) -> PluginResult<&str> {
783        eval_paint_str(&self.inner, slot)
784    }
785    fn paint_enum(&self, slot: u32) -> PluginResult<u32> {
786        eval_paint_enum(&self.inner, slot)
787    }
788    fn as_any(&self) -> Option<&dyn Any> {
789        Some(self)
790    }
791}
792
793/// Borrowed evaluated layer wrapper used in hooks that only receive
794/// `&DynamicEvaluatedLayer` (`evaluate`, `tile_fade`, `query_radius`).
795struct EngineRefEvaluatedLayer<'a> {
796    inner: &'a DynamicEvaluatedLayer,
797}
798
799impl EvaluatedLayerBackend for EngineRefEvaluatedLayer<'_> {
800    fn id(&self) -> &str {
801        &self.inner.style.id
802    }
803    fn paint_is_constant(&self, slot: u32) -> bool {
804        eval_paint_is_constant(self.inner, slot)
805    }
806    fn paint_f32(&self, slot: u32) -> PluginResult<f32> {
807        eval_paint_f32(self.inner, slot)
808    }
809    fn paint_f32_constant_or(&self, slot: u32, fallback: f32) -> PluginResult<f32> {
810        eval_paint_f32_constant_or(self.inner, slot, fallback)
811    }
812    fn paint_bool(&self, slot: u32) -> PluginResult<bool> {
813        eval_paint_bool(self.inner, slot)
814    }
815    fn paint_color(&self, slot: u32) -> PluginResult<PluginColor> {
816        eval_paint_color(self.inner, slot)
817    }
818    fn paint_color_constant_or(&self, slot: u32, fallback: PluginColor) -> PluginResult<PluginColor> {
819        eval_paint_color_constant_or(self.inner, slot, fallback)
820    }
821    fn paint_vec2(&self, slot: u32) -> PluginResult<PluginVec2> {
822        eval_paint_vec2(self.inner, slot)
823    }
824    fn paint_lat_lng(&self, slot: u32) -> PluginResult<PluginLatLng> {
825        eval_paint_lat_lng(self.inner, slot)
826    }
827    fn paint_rotation_degrees(&self, slot: u32) -> PluginResult<f32> {
828        eval_paint_rotation_degrees(self.inner, slot)
829    }
830    fn paint_str(&self, slot: u32) -> PluginResult<&str> {
831        eval_paint_str(self.inner, slot)
832    }
833    fn paint_enum(&self, slot: u32) -> PluginResult<u32> {
834        eval_paint_enum(self.inner, slot)
835    }
836}
837
838// ---------------------------------------------------------------------------
839// Evaluate, View, Frame, Tile, and Geometry backends
840// ---------------------------------------------------------------------------
841
842struct EngineEvaluateCx<'a> {
843    evaluated: EngineRefEvaluatedLayer<'a>,
844    time_point: Option<Instant>,
845}
846
847impl EvaluateCxBackend for EngineEvaluateCx<'_> {
848    fn evaluated(&self) -> EvaluatedLayer<'_> {
849        EvaluatedLayer::from_backend(&self.evaluated)
850    }
851
852    fn time_point_ns(&self) -> Option<i64> {
853        self.time_point.map(instant_to_ns)
854    }
855}
856
857struct EngineView<'a> {
858    inner: &'a View,
859}
860
861impl ViewBackend for EngineView<'_> {
862    fn info(&self) -> ViewInfo {
863        let v = self.inner;
864        let size = v.size();
865        ViewInfo {
866            width: size.width,
867            height: size.height,
868            zoom: v.zoom(),
869            integer_zoom: v.integer_zoom(),
870            angle_rad: v.angle(),
871            pitch_rad: v.pitch(),
872            camera_to_center_distance: v.camera_to_center_distance(),
873            is_globe: v.is_globe(),
874            world_wraps: v.world().wraps(),
875        }
876    }
877
878    fn world_from_lat_lng(&self, lat_lng: PluginLatLng) -> PluginResult<(f64, f64)> {
879        let ll = to_lat_lng(lat_lng)?;
880        let p = self.inner.world().world_from_lat_lng(&ll);
881        Ok((p.x, p.y))
882    }
883
884    fn lat_lng_near_center(&self, lat_lng: PluginLatLng) -> PluginResult<PluginLatLng> {
885        let ll = to_lat_lng(lat_lng)?;
886        Ok(from_lat_lng(self.inner.lat_lng_near_center(&ll)))
887    }
888
889    fn ground_meters_per_world_unit_at(&self, lat_lng: PluginLatLng) -> f64 {
890        let Ok(ll) = to_lat_lng(lat_lng) else {
891            return 0.0;
892        };
893        self.inner.ground_meters_per_world_unit_at(&ll)
894    }
895
896    fn world_copies(&self) -> PluginResult<Vec<i16>> {
897        let parameters = TileCoverParameters {
898            view: self.inner.clone(),
899            tile_lod_min_radius: 3.0,
900            tile_lod_scale: 1.0,
901            tile_lod_pitch_threshold: std::f64::consts::FRAC_PI_3,
902            tile_lod_mode: TileLodMode::Default,
903            requested_zoom: None,
904            round_zoom: false,
905            max_content_elevation: 0.0,
906            // The copies the view shows: a plugin adds its own for what it
907            // draws past them.
908            content_overflows: false,
909        };
910        Ok(tile_cover(&parameters, 0, Range::new(0, 0), None).iter().map(|t| t.wrap).collect())
911    }
912
913    fn project_tile_point(&self, tile_id: TileId, x: f64, y: f64, elevation_m: f64) -> PluginResult<ProjectedPoint> {
914        let tile = unwrapped_tile_id(tile_id)?;
915        let projected = TileProjector::new(self.inner, &tile).project_as_drawn(&Point::new(x, y), elevation_m);
916        Ok(ProjectedPoint {
917            clip_x: projected.point.x,
918            clip_y: projected.point.y,
919            signed_distance_from_camera: projected.signed_distance_from_camera,
920            occluded: projected.occluded,
921        })
922    }
923
924    fn map_aligned_scale_at(&self, tile_id: TileId, x: f64, y: f64) -> f64 {
925        let Ok(tile) = unwrapped_tile_id(tile_id) else {
926            return 1.0;
927        };
928        TileProjector::new(self.inner, &tile).map_aligned_scale_at(&Point::new(x, y))
929    }
930
931    fn globe_extrude_scale(&self, tile_id: TileId) -> f32 {
932        let Ok(tile) = unwrapped_tile_id(tile_id) else {
933            return 0.0;
934        };
935        globe_extrude_scale(self.inner, &tile)
936    }
937
938    fn tile_unit_translation(
939        &self,
940        tile_id: TileId,
941        translate: PluginVec2,
942        anchor: Alignment,
943    ) -> PluginResult<PluginVec2> {
944        let tile = unwrapped_tile_id(tile_id)?;
945        let [tx, ty] = RenderTile::tile_unit_translation(
946            &tile,
947            [translate.x, translate.y],
948            to_translate_anchor(anchor),
949            self.inner,
950        );
951        Ok(PluginVec2::new(tx, ty))
952    }
953}
954
955pub(crate) fn with_view<R>(view: &View, f: impl FnOnce(PluginView<'_>) -> R) -> R {
956    let backend = EngineView { inner: view };
957    f(PluginView::from_backend(&backend))
958}
959
960struct EngineFrame<'a, 'f> {
961    inner: &'a LayerFrame<'f>,
962    view: EngineView<'f>,
963}
964
965impl<'a, 'f> EngineFrame<'a, 'f> {
966    fn new(inner: &'a LayerFrame<'f>) -> Self {
967        Self { inner, view: EngineView { inner: inner.view } }
968    }
969}
970
971impl FrameBackend for EngineFrame<'_, '_> {
972    fn info(&self) -> FrameInfo {
973        let f = self.inner;
974        let size = f.size();
975        FrameInfo {
976            width: size.width,
977            height: size.height,
978            pixel_ratio: f.pixel_ratio(),
979            pixel_scale: f.pixel_scale(),
980            pixels_to_gl_units: f.pixels_to_gl_units,
981            camera_moving: f.camera_moving,
982            terrain: f.terrain,
983            composites_with_frame_depth: f.composites_with_frame_depth,
984            drape_lit: f.drape_lit(),
985            has_ground: f.ground.is_some(),
986            time_point_ns: f.time_point().map(instant_to_ns),
987        }
988    }
989
990    fn view(&self) -> PluginView<'_> {
991        PluginView::from_backend(&self.view)
992    }
993
994    fn tile_projection(&self, tile_id: TileId, transform: PluginTileTransform) -> PluginResult<ProjectionUbo> {
995        let tile = unwrapped_tile_id(tile_id)?;
996        let tf = TileTransform {
997            translate: transform.translate,
998            anchor: to_translate_anchor(transform.translate_anchor),
999            near_clipped: transform.near_clipped,
1000            pixel_aligned: transform.pixel_aligned,
1001        };
1002        Ok(from_projection_ubo(tile_projection(&tile, self.inner, tf).ubo()))
1003    }
1004
1005    fn ground_height(&self, tile_id: TileId, x: f32, y: f32) -> f32 {
1006        let Some(ground) = self.inner.ground.as_deref() else {
1007            return 0.0;
1008        };
1009        let Ok(tile) = unwrapped_tile_id(tile_id) else {
1010            return 0.0;
1011        };
1012        ground.tile(tile).height(GlamVec2::new(x, y))
1013    }
1014
1015    fn ground_depth_texture(&self) -> Option<PluginTexture> {
1016        let tex = self.inner.ground.as_deref().and_then(|g| g.depth()).cloned()?;
1017        Some(PluginTexture::from_handle(Box::new(EngineTexture { inner: tex })))
1018    }
1019
1020    fn collision_shape_count(&self) -> usize {
1021        self.inner.collision_shapes.len()
1022    }
1023
1024    fn collision_shape(&self, index: usize) -> Option<CollisionShape> {
1025        self.inner.collision_shapes.get(index).map(|&tested| from_tested_shape(tested))
1026    }
1027
1028    fn ground_token(&self) -> Option<Box<dyn Any>> {
1029        self.inner.ground.clone().map(|g| -> Box<dyn Any> { Box::new(g) })
1030    }
1031}
1032
1033/// `tested` as a plugin reads it.
1034fn from_tested_shape(tested: TestedShape) -> CollisionShape {
1035    let kind = match tested.shape {
1036        Shape::Box(aabb) => CollisionShapeKind::Box {
1037            min: PluginVec2::new(aabb.min.x, aabb.min.y),
1038            max: PluginVec2::new(aabb.max.x, aabb.max.y),
1039        },
1040        Shape::Circle { center, radius } => {
1041            CollisionShapeKind::Circle { center: PluginVec2::new(center.x, center.y), radius }
1042        }
1043    };
1044    CollisionShape { kind, placed: tested.placed }
1045}
1046
1047struct EngineTileGeometry<'a> {
1048    inner: &'a DynamicBucket,
1049}
1050
1051impl TileGeometryBackend for EngineTileGeometry<'_> {
1052    fn vertex_stream_count(&self) -> usize {
1053        self.inner.vertices.len()
1054    }
1055
1056    fn vertex_count(&self, stream_index: usize) -> usize {
1057        self.inner.vertices.get(stream_index).map_or(0, |s| s.vertex_count)
1058    }
1059
1060    fn vertex_stride(&self, stream_index: usize) -> u32 {
1061        self.inner.vertices.get(stream_index).map_or(0, |s| s.stride)
1062    }
1063
1064    fn index_stream_count(&self) -> usize {
1065        self.inner.indexes.len()
1066    }
1067
1068    fn index_count(&self, stream_index: usize) -> usize {
1069        self.inner.indexes.get(stream_index).map_or(0, crate::layer::bucket_geometry::GeometryVec::len)
1070    }
1071
1072    fn draw_ranges(&self) -> Cow<'_, [PluginDrawRange]> {
1073        Cow::Owned(self.inner.ranges.iter().copied().map(from_draw_range).collect())
1074    }
1075
1076    fn metadata(&self) -> &[u8] {
1077        &self.inner.metadata
1078    }
1079
1080    fn max_elevation(&self) -> f32 {
1081        self.inner.max_elevation
1082    }
1083
1084    fn binder_interpolation_factor(&self, layer_id: &str, paint_slot: u32, zoom: f32) -> f32 {
1085        let Ok(slot) = u16::try_from(paint_slot) else {
1086            return 0.0;
1087        };
1088        self.inner.binders.get(layer_id).map_or(0.0, |b| b.interpolation_factor(slot, zoom))
1089    }
1090
1091    fn binder_statistics_max_f32(&self, layer_id: &str, paint_slot: u32) -> Option<f32> {
1092        let slot = u16::try_from(paint_slot).ok()?;
1093        let binder = self.inner.binders.get(layer_id)?;
1094        binder.statistics_max_f32(slot)
1095    }
1096}
1097
1098struct EngineTile<'a> {
1099    inner: DynamicFrameTile<'a>,
1100    bucket: Option<EngineTileGeometry<'a>>,
1101}
1102
1103impl<'a> EngineTile<'a> {
1104    fn new(inner: DynamicFrameTile<'a>) -> Self {
1105        let bucket = match inner.data() {
1106            DynamicTileData::Geometry { bucket, .. } => Some(EngineTileGeometry { inner: bucket }),
1107            _ => None,
1108        };
1109        Self { inner, bucket }
1110    }
1111}
1112
1113impl TileBackend for EngineTile<'_> {
1114    fn id(&self) -> TileId {
1115        from_overscaled_tile_id(self.inner.id())
1116    }
1117
1118    fn draw_id(&self) -> TileId {
1119        from_overscaled_tile_id(self.inner.draw_id())
1120    }
1121
1122    fn render_passes(&self) -> RenderPasses {
1123        from_render_pass(self.inner.render_passes())
1124    }
1125
1126    fn has_data_for_pass(&self, pass: RenderPasses) -> bool {
1127        self.inner.has_data_for_pass(to_render_pass(pass))
1128    }
1129
1130    fn geometry(&self) -> Option<TileGeometry<'_>> {
1131        self.bucket.as_ref().map(|b| TileGeometry::from_backend(b))
1132    }
1133
1134    fn geometry_vertices(&self, stream_index: usize) -> Option<PluginVertexBuffer> {
1135        let DynamicTileData::Geometry { bucket, geometry, .. } = self.inner.data() else {
1136            return None;
1137        };
1138        let stream = bucket.vertices.get(stream_index)?;
1139        let buf = bucket_vertices(geometry, &stream.bytes)?;
1140        Some(PluginVertexBuffer::from_handle(Box::new(EngineVertexBuffer { inner: buf })))
1141    }
1142
1143    fn geometry_indexes(&self, stream_index: usize) -> Option<PluginIndexBuffer> {
1144        let DynamicTileData::Geometry { bucket, geometry, .. } = self.inner.data() else {
1145            return None;
1146        };
1147        let indexes = bucket.indexes.get(stream_index)?;
1148        let buf = bucket_indexes(geometry, indexes)?;
1149        Some(PluginIndexBuffer::from_handle(Box::new(EngineIndexBuffer { inner: buf })))
1150    }
1151
1152    fn paint_attributes(
1153        &self,
1154        res: &mut PluginResources<'_>,
1155        evaluated: EvaluatedLayer<'_>,
1156    ) -> Option<PluginPaintAttributes> {
1157        let DynamicTileData::Geometry { bucket, geometry, .. } = self.inner.data() else {
1158            return None;
1159        };
1160        let eval = evaluated.backend().as_any()?.downcast_ref::<EngineArcEvaluatedLayer>()?;
1161        let binders = bucket.binders.get(&eval.inner.style.id)?;
1162        let vertices = if binders.depends_on_feature_state() {
1163            let data = binders.interleaved_vertex_buffer.shared_vertex_vector.data();
1164            let stride = u32::try_from(binders.interleaved_vertex_buffer.stride).unwrap_or(0);
1165            if stride == 0 {
1166                None
1167            } else {
1168                let vb = res.create_vertices(&data, binders.interleaved_vertex_buffer.vertex_count, stride).ok()?;
1169                downcast_vertex_buffer(&vb).ok().cloned()
1170            }
1171        } else {
1172            bucket_vertices(geometry, &binders.interleaved_vertex_buffer.shared_vertex_vector)
1173        };
1174        let paint = binders.paint(eval.inner.style.dynamic_type(), &eval.inner.paint, vertices.as_ref());
1175        Some(PluginPaintAttributes::from_handle(Box::new(EnginePaintAttributes { inner: paint })))
1176    }
1177
1178    fn raster_info(&self) -> Option<RasterTileInfo<'_>> {
1179        let DynamicTileData::Raster(raster) = self.inner.data() else {
1180            return None;
1181        };
1182        let img = raster.image();
1183        let image_id = {
1184            use std::hash::{Hash, Hasher};
1185            let mut h = std::collections::hash_map::DefaultHasher::new();
1186            raster.id().hash(&mut h);
1187            h.finish()
1188        };
1189        Some(RasterTileInfo { image_id, width: img.size.width, height: img.size.height, pixels: &img.data })
1190    }
1191}
1192
1193// ---------------------------------------------------------------------------
1194// Update, Resources, Prepare, and Draws backends
1195// ---------------------------------------------------------------------------
1196
1197struct EngineUpdateCxRo<'t> {
1198    evaluated: EngineArcEvaluatedLayer,
1199    source_max_zoom: Option<u8>,
1200    tiles: Vec<EngineTile<'t>>,
1201}
1202
1203impl UpdateCxReadBackend for EngineUpdateCxRo<'_> {
1204    fn evaluated(&self) -> EvaluatedLayer<'_> {
1205        EvaluatedLayer::from_backend(&self.evaluated)
1206    }
1207
1208    fn source_max_zoom(&self) -> Option<u8> {
1209        self.source_max_zoom
1210    }
1211
1212    fn tile_count(&self) -> usize {
1213        self.tiles.len()
1214    }
1215
1216    fn tile(&self, index: usize) -> Option<Tile<'_>> {
1217        self.tiles.get(index).map(|t| Tile::from_backend(t))
1218    }
1219}
1220
1221struct EngineUpdateCxRw<'r, 'a, 'p> {
1222    cx: &'r mut DynamicUpdateCx<'a, 'p>,
1223}
1224
1225impl UpdateCxMutBackend for EngineUpdateCxRw<'_, '_, '_> {
1226    fn pick_tiles(&mut self, tiles: &[TileId]) -> PluginResult<()> {
1227        let parsed: PluginResult<Vec<OverscaledTileID>> = tiles.iter().copied().map(overscaled_tile_id).collect();
1228        self.cx.pick_tiles(parsed?);
1229        Ok(())
1230    }
1231}
1232
1233struct EngineResources<'r, 'a> {
1234    inner: &'r mut Resources<'a>,
1235}
1236
1237impl ResourcesBackend for EngineResources<'_, '_> {
1238    fn create_program(&mut self, desc: &mln_plugin::ProgramDesc<'_>) -> PluginResult<mln_plugin::Program> {
1239        create_program(desc)
1240    }
1241
1242    fn create_ground_heights(&mut self) -> PluginResult<PluginGroundHeights> {
1243        Ok(PluginGroundHeights::from_handle(Box::new(EngineGroundHeights { inner: GroundHeights::default() })))
1244    }
1245
1246    fn create_vertices(&mut self, bytes: &[u8], vertex_count: usize, stride: u32) -> PluginResult<PluginVertexBuffer> {
1247        if stride == 0 {
1248            return Err(PluginError::invalid_argument("stride must not be zero"));
1249        }
1250        let expected = vertex_count
1251            .checked_mul(stride as usize)
1252            .ok_or_else(|| PluginError::invalid_argument("vertex_count * stride overflow"))?;
1253        if bytes.len() != expected {
1254            return Err(PluginError::invalid_argument(format!(
1255                "vertex bytes length {} does not match vertex_count ({vertex_count}) * stride ({stride})",
1256                bytes.len()
1257            )));
1258        }
1259        let buf = self.inner.vertices(bytes);
1260        Ok(PluginVertexBuffer::from_handle(Box::new(EngineVertexBuffer { inner: buf })))
1261    }
1262
1263    fn create_dynamic_vertices(
1264        &mut self,
1265        bytes: &[u8],
1266        vertex_count: usize,
1267        stride: u32,
1268    ) -> PluginResult<PluginVertexBuffer> {
1269        if stride == 0 {
1270            return Err(PluginError::invalid_argument("stride must not be zero"));
1271        }
1272        let expected = vertex_count
1273            .checked_mul(stride as usize)
1274            .ok_or_else(|| PluginError::invalid_argument("vertex_count * stride overflow"))?;
1275        if bytes.len() != expected {
1276            return Err(PluginError::invalid_argument(format!(
1277                "vertex bytes length {} does not match vertex_count ({vertex_count}) * stride ({stride})",
1278                bytes.len()
1279            )));
1280        }
1281        let buf = self.inner.dynamic_vertices(bytes);
1282        Ok(PluginVertexBuffer::from_handle(Box::new(EngineVertexBuffer { inner: buf })))
1283    }
1284
1285    fn update_vertices(&mut self, buffer: &PluginVertexBuffer, bytes: &[u8]) -> bool {
1286        let Ok(vb) = downcast_vertex_buffer(buffer) else {
1287            return false;
1288        };
1289        self.inner.update_vertices(vb, bytes)
1290    }
1291
1292    fn create_indexes(&mut self, indexes: &[u16]) -> PluginResult<PluginIndexBuffer> {
1293        let buf = self.inner.indexes(indexes);
1294        Ok(PluginIndexBuffer::from_handle(Box::new(EngineIndexBuffer { inner: buf })))
1295    }
1296
1297    fn quad_indexes(&mut self) -> PluginResult<PluginIndexBuffer> {
1298        let buf = self.inner.quad_indexes();
1299        Ok(PluginIndexBuffer::from_handle(Box::new(EngineIndexBuffer { inner: buf })))
1300    }
1301
1302    fn create_texture(&mut self, format: TextureFormat, sampler: SamplerState) -> PluginResult<PluginTexture> {
1303        let tex = self.inner.texture(to_texture_format(format), to_sampler(sampler));
1304        Ok(PluginTexture::from_handle(Box::new(EngineTexture { inner: tex })))
1305    }
1306
1307    fn write_texture(&mut self, texture: &PluginTexture, data: &[u8], width: u32, height: u32) -> PluginResult<()> {
1308        let tex = downcast_texture(texture)?;
1309        self.inner
1310            .write_texture(tex, data, Size::new(width, height))
1311            .map_err(|e| PluginError::native(format!("write_texture failed: {e}")))
1312    }
1313
1314    fn create_target(
1315        &mut self,
1316        width: u32,
1317        height: u32,
1318        channel_type: TextureChannelType,
1319        clear_color: PluginColor,
1320    ) -> PluginResult<PluginTarget> {
1321        let clear = Rgba::new(clear_color.r, clear_color.g, clear_color.b, clear_color.a);
1322        let target = self.inner.target(Size::new(width, height), to_channel_type(channel_type), clear);
1323        Ok(PluginTarget::from_handle(Box::new(EngineTarget { inner: target })))
1324    }
1325
1326    fn create_mesh(&mut self, desc: &PluginMeshDesc<'_>) -> PluginResult<PluginMesh> {
1327        let program = downcast_program(desc.program)?;
1328        let variant = to_projection_variant(desc.projection_variant);
1329        let color_mode = to_color_mode(desc.color_mode);
1330        let cull_face_mode = to_cull_face_mode(desc.cull_face_mode);
1331        let mode = to_draw_mode(desc.draw_mode);
1332        let indexes = downcast_index_buffer(desc.indexes)?.clone();
1333
1334        let mut vertices = Vec::with_capacity(desc.vertex_bindings.len() + 1);
1335        for binding in desc.vertex_bindings {
1336            vertices.push(convert_vertex_binding(program, binding)?);
1337        }
1338
1339        let instances = if desc.instance_bindings.is_empty() {
1340            None
1341        } else {
1342            let mut inst = Vec::with_capacity(desc.instance_bindings.len());
1343            for binding in desc.instance_bindings {
1344                inst.push(convert_vertex_binding(program, binding)?);
1345            }
1346            Some(inst)
1347        };
1348
1349        let mut uniforms = Uniforms::default();
1350        if let Some(paint) = desc.paint_attributes {
1351            let paint = downcast_paint_attributes(paint)?;
1352            uniforms = paint.uniforms;
1353            if let Some(ref paint_binding) = paint.vertices {
1354                vertices.push(paint_binding.clone());
1355            }
1356        }
1357
1358        let mut shader = self.inner.shader_key(program, uniforms, variant);
1359        for &define in desc.extra_defines {
1360            if !define.is_empty() {
1361                shader = shader.with_define(define);
1362            }
1363        }
1364
1365        let ranges: Vec<DrawRange> = desc.ranges.iter().copied().map(to_draw_range).collect();
1366
1367        if desc.textures.len() > MAX_TEXTURES {
1368            return Err(PluginError::invalid_argument(format!(
1369                "mesh_desc.textures length ({}) exceeds maximum ({MAX_TEXTURES})",
1370                desc.textures.len()
1371            )));
1372        }
1373        let mut textures = Textures::default();
1374        for (slot, tex_opt) in desc.textures.iter().enumerate() {
1375            if let Some(tex) = tex_opt {
1376                textures[slot] = Some(downcast_texture(tex)?.clone());
1377            }
1378        }
1379
1380        let mesh = self.inner.mesh(MeshDesc {
1381            shader,
1382            color_mode,
1383            cull_face_mode,
1384            mode,
1385            vertices,
1386            vertex_count: desc.vertex_count,
1387            instances,
1388            indexes,
1389            ranges,
1390            textures,
1391        });
1392        Ok(PluginMesh::from_handle(Box::new(EngineMesh { inner: mesh })))
1393    }
1394
1395    fn mesh_set_texture(&mut self, mesh: &PluginMesh, slot: u32, texture: Option<&PluginTexture>) -> PluginResult<()> {
1396        let slot = slot as usize;
1397        if slot >= MAX_TEXTURES {
1398            return Err(PluginError::invalid_argument(format!("texture slot {slot} exceeds maximum ({MAX_TEXTURES})")));
1399        }
1400        let mesh = downcast_mesh(mesh)?;
1401        let tex = texture.map(downcast_texture).transpose()?;
1402        mesh.set_texture(self.inner, slot, tex);
1403        Ok(())
1404    }
1405
1406    fn mesh_set_sampler(&mut self, mesh: &PluginMesh, slot: u32, sampler: SamplerState) -> PluginResult<()> {
1407        let slot = slot as usize;
1408        if slot >= MAX_TEXTURES {
1409            return Err(PluginError::invalid_argument(format!("texture slot {slot} exceeds maximum ({MAX_TEXTURES})")));
1410        }
1411        let mesh = downcast_mesh(mesh)?;
1412        mesh.set_sampler(self.inner, slot, Some(to_sampler(sampler)));
1413        Ok(())
1414    }
1415
1416    fn mesh_set_paint(&mut self, mesh: &PluginMesh, paint: &PluginPaintAttributes) -> PluginResult<()> {
1417        let mesh = downcast_mesh(mesh)?;
1418        let paint = downcast_paint_attributes(paint)?;
1419        if let Some(ref binding) = paint.vertices {
1420            mesh.set_paint(self.inner, binding);
1421        }
1422        Ok(())
1423    }
1424
1425    fn mesh_bind_vertices(&mut self, mesh: &PluginMesh, binding: &PluginVertexBinding<'_>) -> PluginResult<()> {
1426        let mesh = downcast_mesh(mesh)?;
1427        let converted = convert_vertex_binding(mesh.program(), binding)?;
1428        mesh.bind_vertices(self.inner, &converted);
1429        Ok(())
1430    }
1431
1432    fn apply_ground_heights(
1433        &mut self,
1434        heights: &mut PluginGroundHeights,
1435        mesh: &PluginMesh,
1436        frame: PluginFrame<'_>,
1437        tile_id: TileId,
1438        attribute_name: &str,
1439        centers: &[PointI16],
1440    ) -> PluginResult<()> {
1441        let heights = downcast_ground_heights_mut(heights)?;
1442        let mesh = downcast_mesh(mesh)?;
1443        let static_attr = resolve_attribute_name(mesh.program(), attribute_name)?;
1444        let tile = unwrapped_tile_id(tile_id)?;
1445        let Some(token) = frame.backend().ground_token() else {
1446            return Ok(());
1447        };
1448        let Some(ground) = token.downcast_ref::<Rc<FrameGround>>() else {
1449            return Err(PluginError::invalid_argument("frame does not belong to the mln_engine host"));
1450        };
1451        if heights.are_of(ground) {
1452            return Ok(());
1453        }
1454        let tile_ground = ground.tile(tile);
1455        let sampled: Vec<f32> =
1456            centers.iter().map(|c| tile_ground.height(GlamVec2::new(f32::from(c.x), f32::from(c.y)))).collect();
1457        if let Some(vb) = heights.write(self.inner, ground, &sampled) {
1458            let binding = height_binding(&vb, static_attr);
1459            mesh.bind_vertices(self.inner, &binding);
1460        }
1461        Ok(())
1462    }
1463}
1464
1465struct EnginePrepareCxRo<'a, 't> {
1466    tiles: Vec<EngineTile<'t>>,
1467    picked: &'a [OverscaledTileID],
1468}
1469
1470impl PrepareCxReadBackend for EnginePrepareCxRo<'_, '_> {
1471    fn tile_count(&self) -> usize {
1472        self.tiles.len()
1473    }
1474
1475    fn tile(&self, index: usize) -> Option<Tile<'_>> {
1476        self.tiles.get(index).map(|t| Tile::from_backend(t))
1477    }
1478
1479    fn picked_tiles(&self) -> Vec<TileId> {
1480        self.picked.iter().copied().map(from_overscaled_tile_id).collect()
1481    }
1482}
1483
1484struct EnginePrepareCxRw<'r, 'a> {
1485    layer_id: &'r str,
1486    tiles: &'r mut TileMap<Box<dyn Any>>,
1487    res: EngineResources<'r, 'a>,
1488    targets: Option<&'r mut SharedTargets>,
1489}
1490
1491impl PrepareCxMutBackend for EnginePrepareCxRw<'_, '_> {
1492    fn resources(&mut self) -> PluginResources<'_> {
1493        PluginResources::from_backend(&mut self.res)
1494    }
1495
1496    fn tile_resources_mut(&mut self, tile_id: TileId) -> Option<&mut dyn Any> {
1497        let id = overscaled_tile_id(tile_id).ok()?;
1498        self.tiles.get_mut(&id).map(Box::as_mut)
1499    }
1500
1501    fn tile_resources_and_allocator(&mut self, tile_id: TileId) -> (Option<&mut dyn Any>, PluginResources<'_>) {
1502        let tile = overscaled_tile_id(tile_id).ok().and_then(|id| self.tiles.get_mut(&id)).map(Box::as_mut);
1503        (tile, PluginResources::from_backend(&mut self.res))
1504    }
1505
1506    fn take_tile_changes(&mut self, tile_id: TileId) -> TileChanges {
1507        let Ok(id) = overscaled_tile_id(tile_id) else {
1508            return TileChanges::default();
1509        };
1510        let Some(mut entry) = self.tiles.entry(&id) else {
1511            return TileChanges::default();
1512        };
1513        let c = entry.take_changes();
1514        let mut bits = 0u32;
1515        if c.paint {
1516            bits |= TileChanges::PAINT;
1517        }
1518        if c.opacity {
1519            bits |= TileChanges::OPACITY;
1520        }
1521        if c.dynamic {
1522            bits |= TileChanges::DYNAMIC;
1523        }
1524        if c.sort {
1525            bits |= TileChanges::SORT;
1526        }
1527        TileChanges::from_bits(bits)
1528    }
1529
1530    fn read_shared_target(&mut self, name: &str) -> Option<PluginTexture> {
1531        let tex = self.targets.as_deref_mut()?.read(self.layer_id, name)?;
1532        Some(PluginTexture::from_handle(Box::new(EngineTexture { inner: tex })))
1533    }
1534}
1535
1536struct InvalidTargetGroup;
1537
1538impl DrawGroupBackend for InvalidTargetGroup {
1539    fn push(&mut self, _mesh: &PluginMesh, _options: DrawOptions, _blocks: &[&[u8]]) -> PluginResult<()> {
1540        Err(PluginError::invalid_argument("target was not created by the mln_engine host"))
1541    }
1542
1543    fn push_at(
1544        &mut self,
1545        _mesh: &PluginMesh,
1546        _tile_id: TileId,
1547        _projection: &ProjectionUbo,
1548        _options: DrawOptions,
1549        _blocks: &[&[u8]],
1550    ) -> PluginResult<()> {
1551        Err(PluginError::invalid_argument("target was not created by the mln_engine host"))
1552    }
1553
1554    fn set_block(&mut self, _program: &mln_plugin::Program, _buffer_name: &str, _bytes: &[u8]) -> PluginResult<()> {
1555        Err(PluginError::invalid_argument("target was not created by the mln_engine host"))
1556    }
1557
1558    fn set_composite(&mut self, _composite: PluginComposite) -> PluginResult<()> {
1559        Err(PluginError::invalid_argument("target was not created by the mln_engine host"))
1560    }
1561}
1562
1563struct EngineDraws<'a> {
1564    inner: &'a mut Draws,
1565    invalid: InvalidTargetGroup,
1566}
1567
1568impl DrawsBackend for EngineDraws<'_> {
1569    fn main(&mut self) -> DrawGroup<'_> {
1570        DrawGroup::from_backend(self.inner.main())
1571    }
1572
1573    fn target(&mut self, target: &PluginTarget) -> DrawGroup<'_> {
1574        match downcast_target(target) {
1575            Ok(target) => DrawGroup::from_backend(self.inner.target(target)),
1576            Err(_) => DrawGroup::from_backend(&mut self.invalid),
1577        }
1578    }
1579
1580    fn lend(&mut self, _at: PluginLendAt) -> PluginResult<()> {
1581        Err(PluginError::new(Status::Unsupported, "raw GPU lending requires the C Plugin ABI host"))
1582    }
1583}
1584
1585impl DrawGroupBackend for Group {
1586    fn push(&mut self, mesh: &PluginMesh, options: DrawOptions, blocks: &[&[u8]]) -> PluginResult<()> {
1587        let mesh = downcast_mesh(mesh)?;
1588        self.push_raw(mesh, to_draw_options(options), blocks)
1589            .map(|_| ())
1590            .map_err(|e| PluginError::invalid_argument(e.to_string()))
1591    }
1592
1593    fn push_at(
1594        &mut self,
1595        mesh: &PluginMesh,
1596        tile_id: TileId,
1597        projection: &ProjectionUbo,
1598        options: DrawOptions,
1599        blocks: &[&[u8]],
1600    ) -> PluginResult<()> {
1601        let mesh = downcast_mesh(mesh)?;
1602        let tile = overscaled_tile_id(tile_id)?;
1603        let ubo = to_projection_ubo(projection);
1604        self.push_at_raw(mesh, tile, &ubo, to_draw_options(options), blocks)
1605            .map(|_| ())
1606            .map_err(|e| PluginError::invalid_argument(e.to_string()))
1607    }
1608
1609    fn set_block(&mut self, program: &mln_plugin::Program, buffer_name: &str, bytes: &[u8]) -> PluginResult<()> {
1610        let program = downcast_program(program)?;
1611        let block = resolve_uniform_block(program, buffer_name)?;
1612        self.block_raw(block, bytes).map(|_| ()).map_err(|e| PluginError::invalid_argument(e.to_string()))
1613    }
1614
1615    fn set_composite(&mut self, composite: PluginComposite) -> PluginResult<()> {
1616        let blend = to_layer_blend(composite.blend);
1617        self.composite(Some(Composite { opacity: composite.opacity, blend, frame_depth: composite.frame_depth }));
1618        Ok(())
1619    }
1620}
1621
1622// ---------------------------------------------------------------------------
1623// Tile-worker build backends
1624// ---------------------------------------------------------------------------
1625
1626struct LoadedFeature<'a> {
1627    feature_index: usize,
1628    feature: crate::tile::Feature<'a>,
1629    geometry: GeometryCollection,
1630    rings: Vec<Vec<PointI16>>,
1631}
1632
1633struct EngineTileBuildCx<'r, 'a> {
1634    tile: OverscaledTileID,
1635    canonical: CanonicalTileID,
1636    world: &'a WorldMapping,
1637    zoom: f64,
1638    params: PropertyEvaluationParameters,
1639    mode: MapMode,
1640    pixel_ratio: f32,
1641    first_load: bool,
1642    selected_features: &'a [usize],
1643    source_layer: &'r TileLayer<'a>,
1644    layers: Vec<EngineArcEvaluatedLayer>,
1645    cx: &'r mut DynamicBuildCx<'a>,
1646    current: Option<LoadedFeature<'r>>,
1647    layout_text: String,
1648}
1649
1650impl<'r, 'a> EngineTileBuildCx<'r, 'a> {
1651    fn new(cx: &'r mut DynamicBuildCx<'a>, source_layer: &'r TileLayer<'a>) -> Self {
1652        let tile = cx.tile();
1653        let canonical = *cx.canonical();
1654        let world = cx.world();
1655        let zoom = cx.zoom();
1656        let params = cx.parameters();
1657        let mode = cx.mode();
1658        let pixel_ratio = cx.pixel_ratio();
1659        let first_load = cx.first_load();
1660        let selected_features = cx.selected_features();
1661        let layers = cx.layers().iter().map(|l| EngineArcEvaluatedLayer { inner: Arc::clone(l) }).collect();
1662        Self {
1663            tile,
1664            canonical,
1665            world,
1666            zoom,
1667            params,
1668            mode,
1669            pixel_ratio,
1670            first_load,
1671            selected_features,
1672            source_layer,
1673            layers,
1674            cx,
1675            current: None,
1676            layout_text: String::new(),
1677        }
1678    }
1679
1680    fn eval_layout_value<T>(
1681        &self,
1682        layer_index: usize,
1683        layout_slot: u32,
1684        for_current_feature: bool,
1685        extract: impl for<'p> FnOnce(&'p DynamicPropertyValue, &'p DynamicDefault) -> Option<(&'p PropertyValue<T>, T)>,
1686    ) -> PluginResult<T>
1687    where
1688        T: Clone + Default + std::fmt::Debug + ValueConverter + 'static,
1689    {
1690        let layer = self
1691            .layers
1692            .get(layer_index)
1693            .ok_or_else(|| PluginError::not_found(format!("layer_index {layer_index} out of range")))?;
1694        let slot = layout_slot as usize;
1695        let style = &layer.inner.style;
1696        let prop = style
1697            .layout
1698            .get(slot)
1699            .ok_or_else(|| PluginError::invalid_argument(format!("layout slot {layout_slot} out of range")))?;
1700        let desc = style
1701            .dynamic_type()
1702            .layout_property(slot)
1703            .ok_or_else(|| PluginError::invalid_argument(format!("layout slot {layout_slot} out of range")))?;
1704        let (pv, default) = extract(prop, &desc.default).ok_or_else(|| {
1705            PluginError::invalid_argument(format!("layout slot {layout_slot} has mismatched property type"))
1706        })?;
1707        let evaluated = Evaluated::plain(pv, &self.params, default);
1708        if let Some(val) = evaluated.constant() {
1709            return Ok(val);
1710        }
1711        if for_current_feature {
1712            let loaded = self
1713                .current
1714                .as_ref()
1715                .ok_or_else(|| PluginError::invalid_state("no feature loaded; call load_feature first"))?;
1716            let ctx = EvaluationContext::with_zoom_feature(self.zoom, Some(&loaded.feature))
1717                .with_global_state(self.params.global_state.as_deref())
1718                .with_canonical_tile_id(Some(&self.canonical))
1719                .with_world(Some(self.world));
1720            Ok(evaluated.evaluate(&ctx))
1721        } else {
1722            let ctx = EvaluationContext::new(self.zoom)
1723                .with_global_state(self.params.global_state.as_deref())
1724                .with_canonical_tile_id(Some(&self.canonical))
1725                .with_world(Some(self.world));
1726            Ok(evaluated.evaluate(&ctx))
1727        }
1728    }
1729}
1730
1731impl TileBuildCxBackend for EngineTileBuildCx<'_, '_> {
1732    fn tile_id(&self) -> TileId {
1733        from_overscaled_tile_id(self.tile)
1734    }
1735
1736    fn zoom(&self) -> f64 {
1737        self.zoom
1738    }
1739
1740    fn mode(&self) -> PluginMapMode {
1741        from_map_mode(self.mode)
1742    }
1743
1744    fn pixel_ratio(&self) -> f32 {
1745        self.pixel_ratio
1746    }
1747
1748    fn first_load(&self) -> bool {
1749        self.first_load
1750    }
1751
1752    fn layer_count(&self) -> usize {
1753        self.layers.len()
1754    }
1755
1756    fn layer(&self, index: usize) -> Option<EvaluatedLayer<'_>> {
1757        self.layers.get(index).map(|l| EvaluatedLayer::from_backend(l))
1758    }
1759
1760    fn eval_layout_f32(&self, layer_index: usize, layout_slot: u32, for_current_feature: bool) -> PluginResult<f32> {
1761        self.eval_layout_value(layer_index, layout_slot, for_current_feature, |prop, def| match (prop, def) {
1762            (DynamicPropertyValue::Float(pv), DynamicDefault::Float(d)) => Some((pv, *d)),
1763            _ => None,
1764        })
1765    }
1766
1767    fn eval_layout_bool(&self, layer_index: usize, layout_slot: u32, for_current_feature: bool) -> PluginResult<bool> {
1768        self.eval_layout_value(layer_index, layout_slot, for_current_feature, |prop, def| match (prop, def) {
1769            (DynamicPropertyValue::Bool(pv), DynamicDefault::Bool(d)) => Some((pv, *d)),
1770            _ => None,
1771        })
1772    }
1773
1774    fn eval_layout_color(
1775        &self,
1776        layer_index: usize,
1777        layout_slot: u32,
1778        for_current_feature: bool,
1779    ) -> PluginResult<PluginColor> {
1780        self.eval_layout_value(layer_index, layout_slot, for_current_feature, |prop, def| match (prop, def) {
1781            (DynamicPropertyValue::Color(pv), DynamicDefault::Color(d)) => Some((pv, *d)),
1782            _ => None,
1783        })
1784        .map(from_color)
1785    }
1786
1787    fn eval_layout_vec2(
1788        &self,
1789        layer_index: usize,
1790        layout_slot: u32,
1791        for_current_feature: bool,
1792    ) -> PluginResult<PluginVec2> {
1793        self.eval_layout_value(layer_index, layout_slot, for_current_feature, |prop, def| match (prop, def) {
1794            (DynamicPropertyValue::Vec2(pv), DynamicDefault::Vec2(d)) => Some((pv, *d)),
1795            _ => None,
1796        })
1797        .map(|[x, y]| PluginVec2::new(x, y))
1798    }
1799
1800    fn eval_layout_lat_lng(
1801        &self,
1802        layer_index: usize,
1803        layout_slot: u32,
1804        for_current_feature: bool,
1805    ) -> PluginResult<PluginLatLng> {
1806        self.eval_layout_value(layer_index, layout_slot, for_current_feature, |prop, def| match (prop, def) {
1807            (DynamicPropertyValue::LatLng(pv), DynamicDefault::LatLng(d)) => Some((pv, *d)),
1808            _ => None,
1809        })
1810        .map(from_lat_lng)
1811    }
1812
1813    fn eval_layout_rotation_degrees(
1814        &self,
1815        layer_index: usize,
1816        layout_slot: u32,
1817        for_current_feature: bool,
1818    ) -> PluginResult<f32> {
1819        self.eval_layout_value(layer_index, layout_slot, for_current_feature, |prop, def| match (prop, def) {
1820            (DynamicPropertyValue::Rotation(pv), DynamicDefault::Rotation(d)) => Some((pv, *d)),
1821            _ => None,
1822        })
1823        .map(|r| r.angle() as f32)
1824    }
1825
1826    fn eval_layout_str(
1827        &mut self,
1828        layer_index: usize,
1829        layout_slot: u32,
1830        for_current_feature: bool,
1831    ) -> PluginResult<&str> {
1832        let val =
1833            self.eval_layout_value(layer_index, layout_slot, for_current_feature, |prop, def| match (prop, def) {
1834                (DynamicPropertyValue::String(pv), DynamicDefault::String(d)) => Some((pv, (*d).to_owned())),
1835                _ => None,
1836            })?;
1837        self.layout_text = val;
1838        Ok(self.layout_text.as_str())
1839    }
1840
1841    fn eval_layout_enum(&self, layer_index: usize, layout_slot: u32, for_current_feature: bool) -> PluginResult<u32> {
1842        let layer = self
1843            .layers
1844            .get(layer_index)
1845            .ok_or_else(|| PluginError::not_found(format!("layer_index {layer_index} out of range")))?;
1846        let slot = layout_slot as usize;
1847        let desc = layer
1848            .inner
1849            .style
1850            .dynamic_type()
1851            .layout_property(slot)
1852            .ok_or_else(|| PluginError::invalid_argument(format!("layout slot {layout_slot} out of range")))?;
1853        let DynamicDefault::Enum { variants, default } = desc.default else {
1854            return Err(PluginError::invalid_argument(format!("layout slot {layout_slot} is not an enum property")));
1855        };
1856        let val =
1857            self.eval_layout_value(layer_index, layout_slot, for_current_feature, |prop, def| match (prop, def) {
1858                (DynamicPropertyValue::Enum(pv), DynamicDefault::Enum { variants, default }) => {
1859                    let s = variants.get(*default as usize).copied().unwrap_or_default();
1860                    Some((pv, s.to_owned()))
1861                }
1862                _ => None,
1863            })?;
1864        Ok(variants.iter().position(|v| *v == val.as_str()).map_or(default, |i| i as u32))
1865    }
1866
1867    fn feature_count(&self) -> usize {
1868        self.selected_features.len()
1869    }
1870
1871    fn load_feature(&mut self, selected_index: usize) -> PluginResult<LoadedFeatureInfo> {
1872        let &feature_index = self
1873            .selected_features
1874            .get(selected_index)
1875            .ok_or_else(|| PluginError::not_found("selected_index out of range"))?;
1876        let feature = self
1877            .source_layer
1878            .feature(feature_index)
1879            .map_err(|e| PluginError::native(format!("failed to decode feature {feature_index}: {e}")))?;
1880        let feature_type = from_feature_type(feature.feature_type());
1881        let geometry = feature
1882            .geometry()
1883            .map_err(|e| PluginError::native(format!("failed to decode feature {feature_index} geometry: {e}")))?
1884            .into_owned();
1885        let rings: Vec<Vec<PointI16>> =
1886            geometry.iter().map(|ring| ring.iter().map(|p| PointI16::new(p.x, p.y)).collect()).collect();
1887        let ring_count = rings.len();
1888        self.current = Some(LoadedFeature { feature_index, feature, geometry, rings });
1889        Ok(LoadedFeatureInfo { feature_index, feature_type, ring_count })
1890    }
1891
1892    fn feature_ring(&self, ring_index: usize) -> Option<Cow<'_, [PointI16]>> {
1893        self.current.as_ref()?.rings.get(ring_index).map(|r| Cow::Borrowed(r.as_slice()))
1894    }
1895
1896    fn populate_binders(&mut self, vertex_count: usize) -> PluginResult<()> {
1897        let loaded = self
1898            .current
1899            .as_ref()
1900            .ok_or_else(|| PluginError::invalid_state("no feature loaded; call load_feature first"))?;
1901        self.cx.populate_binders(loaded.feature_index, &loaded.feature, vertex_count);
1902        Ok(())
1903    }
1904
1905    fn index_current_feature(&mut self) -> PluginResult<()> {
1906        let loaded = self
1907            .current
1908            .as_ref()
1909            .ok_or_else(|| PluginError::invalid_state("no feature loaded; call load_feature first"))?;
1910        self.cx.index_feature(loaded.feature_index, &loaded.geometry);
1911        Ok(())
1912    }
1913}
1914
1915struct EngineTileGeometryBuilder {
1916    bucket: DynamicBucket,
1917}
1918
1919impl EngineTileGeometryBuilder {
1920    fn new() -> Self {
1921        Self { bucket: DynamicBucket::default() }
1922    }
1923}
1924
1925impl TileGeometryBuilderBackend for EngineTileGeometryBuilder {
1926    fn add_vertices(&mut self, bytes: &[u8], vertex_count: usize, stride: u32) -> PluginResult<usize> {
1927        if stride == 0 {
1928            return Err(PluginError::invalid_argument("stride must not be zero"));
1929        }
1930        let expected = vertex_count
1931            .checked_mul(stride as usize)
1932            .ok_or_else(|| PluginError::invalid_argument("vertex_count * stride overflow"))?;
1933        if bytes.len() != expected {
1934            return Err(PluginError::invalid_argument(format!(
1935                "vertex bytes length {} does not match vertex_count ({vertex_count}) * stride ({stride})",
1936                bytes.len()
1937            )));
1938        }
1939        Ok(self.bucket.add_vertices(bytes.to_vec(), vertex_count, stride))
1940    }
1941
1942    fn add_indexes(&mut self, indexes: &[u16]) -> PluginResult<usize> {
1943        Ok(self.bucket.add_indexes(indexes.to_vec()))
1944    }
1945
1946    fn add_draw_range(&mut self, range: PluginDrawRange) -> PluginResult<()> {
1947        self.bucket.ranges.push(to_draw_range(range));
1948        Ok(())
1949    }
1950
1951    fn set_metadata(&mut self, bytes: &[u8]) -> PluginResult<()> {
1952        self.bucket.metadata = bytes.to_vec();
1953        Ok(())
1954    }
1955
1956    fn set_max_elevation(&mut self, max_elevation: f32) -> PluginResult<()> {
1957        self.bucket.max_elevation = max_elevation;
1958        Ok(())
1959    }
1960}
1961
1962// ---------------------------------------------------------------------------
1963// Hit & frame query backends
1964// ---------------------------------------------------------------------------
1965
1966struct EngineHitCx<'a> {
1967    evaluated: EngineArcEvaluatedLayer,
1968    view: EngineView<'a>,
1969    region: &'a QueryRegion<'a>,
1970    feature: &'a dyn GeometryTileFeature,
1971    feature_state: &'a FeatureState,
1972    query_geometry: Vec<PointI16>,
1973    screen_geometry: Vec<ScreenPoint>,
1974    feature_rings: Vec<Vec<PointI16>>,
1975}
1976
1977impl<'a> EngineHitCx<'a> {
1978    fn new(
1979        values: &'a DynamicLayerValues,
1980        region: &'a QueryRegion<'a>,
1981        feature: &'a dyn GeometryTileFeature,
1982        geometry: &'a GeometryCollection,
1983        feature_state: &'a FeatureState,
1984    ) -> Self {
1985        let query_geometry = region.geometry.iter().map(|p| PointI16::new(p.x, p.y)).collect();
1986        let screen_geometry = region.screen.iter().map(|p| ScreenPoint { x: p.x, y: p.y }).collect();
1987        let feature_rings =
1988            geometry.iter().map(|ring| ring.iter().map(|p| PointI16::new(p.x, p.y)).collect()).collect();
1989        Self {
1990            evaluated: EngineArcEvaluatedLayer { inner: Arc::clone(&values.evaluated) },
1991            view: EngineView { inner: region.view },
1992            region,
1993            feature,
1994            feature_state,
1995            query_geometry,
1996            screen_geometry,
1997            feature_rings,
1998        }
1999    }
2000
2001    fn eval_context(&self) -> EvaluationContext<'_> {
2002        EvaluationContext::with_zoom_feature_state(
2003            self.region.view.zoom(),
2004            Some(self.feature),
2005            Some(self.feature_state),
2006        )
2007    }
2008}
2009
2010impl HitCxBackend for EngineHitCx<'_> {
2011    fn info(&self) -> HitInfo<'_> {
2012        HitInfo {
2013            tile_id: from_unwrapped_tile_id(*self.region.projector.tile_id()),
2014            pixels_to_tile_units: self.region.pixels_to_tile_units,
2015            has_ground: self.region.ground.is_some(),
2016            query_geometry: Cow::Borrowed(&self.query_geometry),
2017            screen_geometry: Cow::Borrowed(&self.screen_geometry),
2018            feature_ring_count: self.feature_rings.len(),
2019        }
2020    }
2021
2022    fn evaluated(&self) -> EvaluatedLayer<'_> {
2023        EvaluatedLayer::from_backend(&self.evaluated)
2024    }
2025
2026    fn view(&self) -> PluginView<'_> {
2027        PluginView::from_backend(&self.view)
2028    }
2029
2030    fn feature_ring(&self, index: usize) -> Option<Cow<'_, [PointI16]>> {
2031        self.feature_rings.get(index).map(|r| Cow::Borrowed(r.as_slice()))
2032    }
2033
2034    fn eval_paint_f32(&self, slot: u32) -> PluginResult<f32> {
2035        let eval_cx = self.eval_context();
2036        self.evaluated
2037            .inner
2038            .paint
2039            .get(slot as usize)
2040            .and_then(|v| v.evaluate_float(&eval_cx))
2041            .ok_or_else(|| PluginError::invalid_argument(format!("paint slot {slot} is not a float property")))
2042    }
2043
2044    fn eval_paint_bool(&self, slot: u32) -> PluginResult<bool> {
2045        let eval_cx = self.eval_context();
2046        self.evaluated
2047            .inner
2048            .paint
2049            .get(slot as usize)
2050            .and_then(|v| v.evaluate_bool(&eval_cx))
2051            .ok_or_else(|| PluginError::invalid_argument(format!("paint slot {slot} is not a bool property")))
2052    }
2053
2054    fn eval_paint_color(&self, slot: u32) -> PluginResult<PluginColor> {
2055        let eval_cx = self.eval_context();
2056        self.evaluated
2057            .inner
2058            .paint
2059            .get(slot as usize)
2060            .and_then(|v| v.evaluate_color(&eval_cx))
2061            .map(from_color)
2062            .ok_or_else(|| PluginError::invalid_argument(format!("paint slot {slot} is not a color property")))
2063    }
2064
2065    fn eval_paint_vec2(&self, slot: u32) -> PluginResult<PluginVec2> {
2066        let eval_cx = self.eval_context();
2067        let [x, y] = self
2068            .evaluated
2069            .inner
2070            .paint
2071            .get(slot as usize)
2072            .and_then(|v| v.evaluate_vec2(&eval_cx))
2073            .ok_or_else(|| PluginError::invalid_argument(format!("paint slot {slot} is not a vec2 property")))?;
2074        Ok(PluginVec2::new(x, y))
2075    }
2076
2077    fn eval_paint_enum(&self, slot: u32) -> PluginResult<u32> {
2078        let idx = slot as usize;
2079        let desc = self
2080            .evaluated
2081            .inner
2082            .style
2083            .dynamic_type()
2084            .paint_property(idx)
2085            .ok_or_else(|| PluginError::invalid_argument(format!("paint slot {slot} out of range")))?;
2086        let DynamicDefault::Enum { variants, default } = &desc.default else {
2087            return Err(PluginError::invalid_argument(format!("paint slot {slot} is not an enum property")));
2088        };
2089        let eval_cx = self.eval_context();
2090        self.evaluated
2091            .inner
2092            .paint
2093            .get(idx)
2094            .and_then(|v| v.evaluate_enum_index(&eval_cx, variants, *default))
2095            .ok_or_else(|| PluginError::invalid_argument(format!("paint slot {slot} is not an enum property")))
2096    }
2097
2098    fn eval_paint_string(&self, slot: u32) -> PluginResult<String> {
2099        let eval_cx = self.eval_context();
2100        self.evaluated
2101            .inner
2102            .paint
2103            .get(slot as usize)
2104            .and_then(|v| v.evaluate_string(&eval_cx))
2105            .ok_or_else(|| PluginError::invalid_argument(format!("paint slot {slot} is not a string/enum property")))
2106    }
2107
2108    fn ground_height(&self, point: PointI16) -> f64 {
2109        self.region.ground_height(GeometryCoordinate::new(point.x, point.y))
2110    }
2111
2112    fn translated_query_geometry(&self, translate: PluginVec2, anchor: Alignment) -> PluginResult<Vec<PointI16>> {
2113        let bearing = self.region.view.angle() as f32;
2114        let translated = translate_query_geometry(
2115            self.region.geometry,
2116            [translate.x, translate.y],
2117            to_translate_anchor(anchor),
2118            bearing,
2119            self.region.pixels_to_tile_units,
2120        );
2121        let src = translated.as_deref().unwrap_or(self.region.geometry);
2122        Ok(src.iter().map(|p| PointI16::new(p.x, p.y)).collect())
2123    }
2124
2125    fn plane_geometry(
2126        &self,
2127        elevation_m: f64,
2128        translate: PluginVec2,
2129        anchor: Alignment,
2130    ) -> PluginResult<Vec<PointI16>> {
2131        let plane = self.region.plane_geometry(elevation_m, [translate.x, translate.y], to_translate_anchor(anchor));
2132        Ok(plane.iter().map(|p| PointI16::new(p.x, p.y)).collect())
2133    }
2134
2135    fn viewport_point(&self, x: f64, y: f64, elevation_m: f64) -> Option<PluginVec2> {
2136        let p = self.region.viewport_point(Point::new(x, y), elevation_m);
2137        Some(PluginVec2::new(p.x, p.y))
2138    }
2139
2140    fn map_aligned_scale_at(&self, x: f64, y: f64) -> f64 {
2141        self.region.projector.map_aligned_scale_at(&Point::new(x, y))
2142    }
2143
2144    fn pitch_scaled_size(
2145        &self,
2146        size: f32,
2147        point: PointI16,
2148        elevation_m: f64,
2149        pitch_scale: Alignment,
2150        pitch_alignment: Alignment,
2151    ) -> f32 {
2152        self.region.pitch_scaled_size(
2153            size,
2154            GeometryCoordinate::new(point.x, point.y),
2155            elevation_m,
2156            to_pitch_scale_type(pitch_scale),
2157            to_alignment_type(pitch_alignment),
2158        )
2159    }
2160
2161    fn shows(&self, x: f64, y: f64, elevation_m: f64) -> bool {
2162        self.region.shows(Point::new(x, y), elevation_m)
2163    }
2164}
2165
2166struct EngineFrameQueryCxRo<'a> {
2167    evaluated: EngineArcEvaluatedLayer,
2168    view: EngineView<'a>,
2169    query: &'a DynamicFrameQuery<'a>,
2170    screen_geometry: Vec<ScreenPoint>,
2171}
2172
2173impl<'a> EngineFrameQueryCxRo<'a> {
2174    fn new(query: &'a DynamicFrameQuery<'a>) -> Self {
2175        let screen_geometry = query.geometry().iter().map(|p| ScreenPoint { x: p.x, y: p.y }).collect();
2176        Self {
2177            evaluated: EngineArcEvaluatedLayer { inner: Arc::clone(&query.values().evaluated) },
2178            view: EngineView { inner: query.view() },
2179            query,
2180            screen_geometry,
2181        }
2182    }
2183}
2184
2185impl FrameQueryCxReadBackend for EngineFrameQueryCxRo<'_> {
2186    fn evaluated(&self) -> EvaluatedLayer<'_> {
2187        EvaluatedLayer::from_backend(&self.evaluated)
2188    }
2189
2190    fn view(&self) -> PluginView<'_> {
2191        PluginView::from_backend(&self.view)
2192    }
2193
2194    fn geometry(&self) -> Cow<'_, [ScreenPoint]> {
2195        Cow::Borrowed(&self.screen_geometry)
2196    }
2197
2198    fn has_ground(&self) -> bool {
2199        self.query.ground(UnwrappedTileID::new(0, 0, 0)).is_some()
2200    }
2201
2202    fn ground_height(&self, tile_id: TileId, x: f32, y: f32) -> f32 {
2203        let Ok(tile) = unwrapped_tile_id(tile_id) else {
2204            return 0.0;
2205        };
2206        self.query.ground(tile).map_or(0.0, |g| g.height(GlamVec2::new(x, y)))
2207    }
2208
2209    fn ground_visibility(&self, tile_id: TileId, x: f64, y: f64, elevation_m: f64) -> f64 {
2210        let Ok(tile) = unwrapped_tile_id(tile_id) else {
2211            return 1.0;
2212        };
2213        self.query.ground(tile).map_or(1.0, |g| g.visibility(self.query.view(), Point::new(x, y), elevation_m))
2214    }
2215}
2216
2217struct EngineFrameQueryCxRw<'a> {
2218    hits: &'a mut Vec<Feature>,
2219}
2220
2221impl FrameQueryCxMutBackend for EngineFrameQueryCxRw<'_> {
2222    fn push_feature_json(&mut self, geojson_feature: &str) -> PluginResult<()> {
2223        let parsed: GeoJson = serde_json::from_str(geojson_feature)
2224            .map_err(|e| PluginError::invalid_argument(format!("invalid GeoJSON: {e}")))?;
2225        let GeoJson::Feature(feat) = parsed else {
2226            return Err(PluginError::invalid_argument("geojson_feature must be a GeoJSON Feature object"));
2227        };
2228        let mut features = mln_style::feature::geojson::features(GeoJson::Feature(feat))
2229            .map_err(|e| PluginError::invalid_argument(format!("invalid GeoJSON feature: {e}")))?;
2230        if let Some(converted) = features.pop() {
2231            self.hits.push(Feature::from(converted));
2232        }
2233        Ok(())
2234    }
2235
2236    fn push_point_feature(&mut self, position: PluginLatLng) -> PluginResult<()> {
2237        let ll = to_lat_lng(position)?;
2238        let point = geo_types::Point::new(ll.longitude(), ll.latitude());
2239        self.hits.push(Feature { geometry: Some(point.into()), ..Feature::default() });
2240        Ok(())
2241    }
2242}
2243
2244// ---------------------------------------------------------------------------
2245// DynamicLayerHandler / DynamicLayerInstance adapter
2246// ---------------------------------------------------------------------------
2247
2248struct DisabledLayerInstance;
2249
2250impl DynamicLayerInstance for DisabledLayerInstance {
2251    fn evaluate(&mut self, _cx: &mut DynamicEvaluateCx<'_>) -> Evaluation {
2252        Evaluation::NONE
2253    }
2254}
2255
2256struct PluginLayerHandler<P: LayerPlugin> {
2257    name: &'static str,
2258    plugin: P,
2259}
2260
2261struct PluginLayerInstance<I: LayerInstance> {
2262    instance: I,
2263}
2264
2265impl<P: LayerPlugin> DynamicLayerHandler for PluginLayerHandler<P> {
2266    fn create_instance(&self, values: &DynamicLayerValues) -> Box<dyn DynamicLayerInstance> {
2267        let evaluated = EngineArcEvaluatedLayer { inner: Arc::clone(&values.evaluated) };
2268        match self.plugin.create_instance(EvaluatedLayer::from_backend(&evaluated)) {
2269            Ok(instance) => Box::new(PluginLayerInstance { instance }),
2270            Err(err) => {
2271                tracing::error!(
2272                    target: crate::log_target::RENDER,
2273                    layer_type = self.name,
2274                    error = %err,
2275                    "plugin layer create_instance failed; disabling layer instance"
2276                );
2277                Box::new(DisabledLayerInstance)
2278            }
2279        }
2280    }
2281
2282    fn tile_fade(&self, layer: &DynamicEvaluatedLayer) -> Duration {
2283        let evaluated = EngineRefEvaluatedLayer { inner: layer };
2284        Duration::from_nanos(self.plugin.tile_fade_ns(EvaluatedLayer::from_backend(&evaluated)))
2285    }
2286
2287    fn build_bucket(&self, cx: &mut DynamicBuildCx<'_>) -> Result<Option<DynamicBucket>, StyleError> {
2288        let source_layer = cx.source_layer()?;
2289        let mut build_cx = EngineTileBuildCx::new(cx, &source_layer);
2290        let mut builder = EngineTileGeometryBuilder::new();
2291        let res = {
2292            let mut api_cx = TileBuildCx::from_backend(&mut build_cx);
2293            let mut api_builder = TileGeometryBuilder::from_backend(&mut builder);
2294            self.plugin.build_tile_geometry(&mut api_cx, &mut api_builder)
2295        };
2296        drop(build_cx);
2297        if let Err(err) = res {
2298            return Err(StyleError::failed(format!("plugin layer '{}' build_tile_geometry failed: {err}", self.name)));
2299        }
2300        if builder.bucket.vertices.is_empty() {
2301            return Ok(None);
2302        }
2303        builder.bucket.binders = cx.take_binders();
2304        Ok(Some(builder.bucket))
2305    }
2306
2307    fn query_radius(&self, bucket: &DynamicBucket, layer: &DynamicEvaluatedLayer) -> f32 {
2308        let geom = EngineTileGeometry { inner: bucket };
2309        let eval = EngineRefEvaluatedLayer { inner: layer };
2310        self.plugin.query_radius(TileGeometry::from_backend(&geom), EvaluatedLayer::from_backend(&eval))
2311    }
2312}
2313
2314impl<I: LayerInstance> DynamicLayerInstance for PluginLayerInstance<I> {
2315    fn evaluate(&mut self, cx: &mut DynamicEvaluateCx<'_>) -> Evaluation {
2316        let time_point = cx.time_point();
2317        let backend = EngineEvaluateCx { evaluated: EngineRefEvaluatedLayer { inner: cx.evaluated }, time_point };
2318        let res = self.instance.evaluate(EvaluateCx::from_backend(&backend));
2319        to_evaluation(res, time_point)
2320    }
2321
2322    fn update(&mut self, cx: &mut DynamicUpdateCx<'_, '_>, tiles: &[DynamicFrameTile<'_>]) {
2323        let ro = EngineUpdateCxRo {
2324            evaluated: EngineArcEvaluatedLayer { inner: Arc::clone(&cx.values.evaluated) },
2325            source_max_zoom: cx.source_max_zoom(),
2326            tiles: tiles.iter().copied().map(EngineTile::new).collect(),
2327        };
2328        let mut rw = EngineUpdateCxRw { cx };
2329        let mut api_cx = UpdateCx::from_backends(&ro, &mut rw);
2330        self.instance.update(&mut api_cx);
2331    }
2332
2333    fn tile(
2334        &mut self,
2335        cx: &mut DynamicTileCx<'_, '_>,
2336        tile: &DynamicFrameTile<'_>,
2337        previous: Option<Box<dyn Any>>,
2338    ) -> Option<Box<dyn Any>> {
2339        let evaluated = EngineArcEvaluatedLayer { inner: Arc::clone(&cx.values.evaluated) };
2340        let frame = EngineFrame::new(cx.frame);
2341        let tile_backend = EngineTile::new(*tile);
2342        let projection_variant = from_projection_variant(cx.projection_variant());
2343        let mut res = EngineResources { inner: &mut cx.res };
2344        let mut api_cx = TileCx::new(
2345            EvaluatedLayer::from_backend(&evaluated),
2346            projection_variant,
2347            PluginFrame::from_backend(&frame),
2348            Tile::from_backend(&tile_backend),
2349            &mut res,
2350        );
2351        let mut prev = previous.and_then(|b| b.downcast::<I::TileResources>().ok());
2352        match self.instance.create_tile_resources(&mut api_cx, prev.as_deref_mut()) {
2353            Ok(Some(state)) => Some(Box::new(state)),
2354            Ok(None) => None,
2355            Err(err) => {
2356                tracing::error!(
2357                    target: crate::log_target::RENDER,
2358                    error = %err,
2359                    "plugin layer create_tile_resources failed"
2360                );
2361                None
2362            }
2363        }
2364    }
2365
2366    fn prepare(&mut self, cx: &mut DynamicPrepareCx<'_, '_>, tiles: &[DynamicFrameTile<'_>], out: &mut Draws) {
2367        let evaluated = EngineArcEvaluatedLayer { inner: Arc::clone(&cx.values.evaluated) };
2368        let frame = EngineFrame::new(cx.frame);
2369        let projection_variant = from_projection_variant(cx.projection_variant());
2370        let layer_id = cx.base.style.base().id.as_str();
2371        let ro = EnginePrepareCxRo { tiles: tiles.iter().copied().map(EngineTile::new).collect(), picked: cx.picked };
2372        let mut rw = EnginePrepareCxRw {
2373            layer_id,
2374            tiles: cx.tiles,
2375            res: EngineResources { inner: &mut cx.res },
2376            targets: cx.targets.as_deref_mut(),
2377        };
2378        let mut api_cx = PrepareCx::<I::TileResources>::new(
2379            EvaluatedLayer::from_backend(&evaluated),
2380            PluginFrame::from_backend(&frame),
2381            projection_variant,
2382            &ro,
2383            &mut rw,
2384        );
2385        let mut draws_backend = EngineDraws { inner: out, invalid: InvalidTargetGroup };
2386        let mut api_draws = PluginDraws::from_backend(&mut draws_backend);
2387        self.instance.prepare(&mut api_cx, &mut api_draws);
2388    }
2389
2390    fn hit(
2391        &self,
2392        values: &DynamicLayerValues,
2393        region: &QueryRegion<'_>,
2394        feature: &dyn GeometryTileFeature,
2395        geometry: &GeometryCollection,
2396        feature_state: &FeatureState,
2397    ) -> Hit {
2398        let backend = EngineHitCx::new(values, region, feature, geometry, feature_state);
2399        match self.instance.hit(HitCx::from_backend(&backend)) {
2400            PluginHit::Miss => Hit::Miss,
2401            PluginHit::InPlace => Hit::InPlace,
2402            PluginHit::AtDistance(d) => Hit::At(d),
2403        }
2404    }
2405
2406    fn hit_frame(&self, query: &DynamicFrameQuery<'_>, hits: &mut Vec<Feature>) {
2407        let ro = EngineFrameQueryCxRo::new(query);
2408        let mut rw = EngineFrameQueryCxRw { hits };
2409        let mut api_cx = FrameQueryCx::from_backends(&ro, &mut rw);
2410        self.instance.hit_frame(&mut api_cx);
2411    }
2412}
2413
2414// ---------------------------------------------------------------------------
2415// Schema validation & layer type builder
2416// ---------------------------------------------------------------------------
2417
2418enum ValidatedDefault {
2419    Float(f32),
2420    Bool(bool),
2421    Color(Color),
2422    Vec2([f32; 2]),
2423    LatLng(LatLng),
2424    Rotation(Rotation),
2425    String(String),
2426    Enum { variants: Vec<String>, default: u32 },
2427}
2428
2429impl ValidatedDefault {
2430    fn supports_paint_binder(&self) -> bool {
2431        matches!(self, Self::Float(_) | Self::Color(_))
2432    }
2433}
2434
2435struct ValidatedProperty {
2436    name: String,
2437    scope: StylePropertyScope,
2438    data_driven: bool,
2439    paint_lays_out: bool,
2440    attribute: Option<String>,
2441    default: ValidatedDefault,
2442}
2443
2444fn leak_str(s: String) -> &'static str {
2445    Box::leak(s.into_boxed_str())
2446}
2447
2448/// Validates and initializes a [`LayerPlugin`] into a reusable
2449/// `&'static DynamicLayerType`.
2450///
2451/// Hosts that register the same plugin into multiple [`crate::RegistryBuilder`]s
2452/// can build it once (e.g. in a [`std::sync::LazyLock`]) and pass the returned
2453/// type to [`crate::RegistryBuilder::add_dynamic_layer_type`].
2454pub fn build_layer_type<P: LayerPlugin>(mut plugin: P) -> PluginResult<&'static DynamicLayerType> {
2455    let desc = plugin.desc();
2456    if desc.name.is_empty() {
2457        return Err(PluginError::invalid_argument("layer.name must not be empty"));
2458    }
2459
2460    let (source_kind, picks_tiles) = match desc.input {
2461        LayerInput::Frame => (SourceKind::None, false),
2462        LayerInput::ViewportTiles => (SourceKind::None, true),
2463        LayerInput::GeometryTiles => (SourceKind::Geometry, false),
2464        LayerInput::RasterTiles => (SourceKind::Raster, false),
2465        LayerInput::RasterDemTiles => (SourceKind::RasterDem, false),
2466        LayerInput::SourceTiles => (SourceKind::Any, false),
2467    };
2468    let tile_order = match desc.tile_order {
2469        PluginTileOrder::ById => TileOrder::ById,
2470        PluginTileOrder::ByY => TileOrder::ByY,
2471    };
2472    let terrain = match desc.terrain_mode {
2473        TerrainMode::Flat => OnTerrain::Flat,
2474        TerrainMode::Stands => OnTerrain::Stands { hides_behind_ground: false },
2475        TerrainMode::StandsHidingBehindGround => OnTerrain::Stands { hides_behind_ground: true },
2476        TerrainMode::Drapes => OnTerrain::Drapes,
2477    };
2478
2479    if desc.properties.len() > MAX_DYNAMIC_PROPERTIES {
2480        return Err(PluginError::invalid_argument(format!(
2481            "layer '{}' declares {} properties, exceeding maximum ({MAX_DYNAMIC_PROPERTIES})",
2482            desc.name,
2483            desc.properties.len()
2484        )));
2485    }
2486
2487    let mut properties = Vec::with_capacity(desc.properties.len());
2488    let mut names = HashSet::default();
2489    let mut paint_names = HashSet::default();
2490    let mut attributes = HashSet::default();
2491    let mut data_driven_paint = 0usize;
2492
2493    for p in desc.properties {
2494        if p.name.is_empty() {
2495            return Err(PluginError::invalid_argument(format!(
2496                "layer '{}' has a property with an empty name",
2497                desc.name
2498            )));
2499        }
2500        if !names.insert(p.name.to_owned()) {
2501            return Err(PluginError::invalid_argument(format!(
2502                "layer '{}' has duplicate property '{}'",
2503                desc.name, p.name
2504            )));
2505        }
2506        let scope = match p.scope {
2507            PropertyScope::Paint => StylePropertyScope::Paint,
2508            PropertyScope::Layout => StylePropertyScope::Layout,
2509        };
2510        if scope == StylePropertyScope::Paint {
2511            paint_names.insert(p.name.to_owned());
2512            if p.data_driven {
2513                data_driven_paint += 1;
2514            }
2515        }
2516
2517        let default = match p.default {
2518            PropertyDefault::Float(v) => {
2519                if !v.is_finite() {
2520                    return Err(PluginError::invalid_argument(format!(
2521                        "property '{}' default float must be finite",
2522                        p.name
2523                    )));
2524                }
2525                ValidatedDefault::Float(v)
2526            }
2527            PropertyDefault::Bool(v) => ValidatedDefault::Bool(v),
2528            PropertyDefault::Color(c) => ValidatedDefault::Color(to_color(c)),
2529            PropertyDefault::Vec2(v) => {
2530                if !v.x.is_finite() || !v.y.is_finite() {
2531                    return Err(PluginError::invalid_argument(format!(
2532                        "property '{}' default vec2 must be finite",
2533                        p.name
2534                    )));
2535                }
2536                ValidatedDefault::Vec2([v.x, v.y])
2537            }
2538            PropertyDefault::LatLng(ll) => ValidatedDefault::LatLng(to_lat_lng(ll)?),
2539            PropertyDefault::RotationDegrees(deg) => {
2540                if !deg.is_finite() {
2541                    return Err(PluginError::invalid_argument(format!(
2542                        "property '{}' default rotation_degrees must be finite",
2543                        p.name
2544                    )));
2545                }
2546                ValidatedDefault::Rotation(Rotation::new(f64::from(deg)))
2547            }
2548            PropertyDefault::String(s) => ValidatedDefault::String(s.to_owned()),
2549            PropertyDefault::Enum { variants, default_index } => {
2550                if variants.is_empty() {
2551                    return Err(PluginError::invalid_argument(format!(
2552                        "enum property '{}' must declare at least one variant",
2553                        p.name
2554                    )));
2555                }
2556                if (default_index as usize) >= variants.len() {
2557                    return Err(PluginError::invalid_argument(format!(
2558                        "enum property '{}' default index {default_index} is out of range for {} variants",
2559                        p.name,
2560                        variants.len()
2561                    )));
2562                }
2563                let mut seen = HashSet::default();
2564                let mut owned = Vec::with_capacity(variants.len());
2565                for &v in variants {
2566                    if !seen.insert(v.to_owned()) {
2567                        return Err(PluginError::invalid_argument(format!(
2568                            "enum property '{}' has duplicate variant '{v}'",
2569                            p.name
2570                        )));
2571                    }
2572                    owned.push(v.to_owned());
2573                }
2574                ValidatedDefault::Enum { variants: owned, default: default_index }
2575            }
2576        };
2577
2578        let attribute = if p.attribute_name.is_empty() {
2579            None
2580        } else {
2581            let attr = p.attribute_name;
2582            if scope != StylePropertyScope::Paint {
2583                return Err(PluginError::invalid_argument(format!(
2584                    "property '{}': attribute_name is only supported on paint properties",
2585                    p.name
2586                )));
2587            }
2588            if !p.data_driven {
2589                return Err(PluginError::invalid_argument(format!(
2590                    "property '{}': attribute_name requires data_driven",
2591                    p.name
2592                )));
2593            }
2594            if !default.supports_paint_binder() {
2595                return Err(PluginError::invalid_argument(format!(
2596                    "property '{}': attribute_name is only supported on Float and Color paint properties",
2597                    p.name
2598                )));
2599            }
2600            if !attributes.insert(attr.to_owned()) {
2601                return Err(PluginError::invalid_argument(format!(
2602                    "layer '{}' has duplicate attribute '{attr}'",
2603                    desc.name
2604                )));
2605            }
2606            Some(attr.to_owned())
2607        };
2608
2609        properties.push(ValidatedProperty {
2610            name: p.name.to_owned(),
2611            scope,
2612            data_driven: p.data_driven,
2613            paint_lays_out: p.paint_lays_out,
2614            attribute,
2615            default,
2616        });
2617    }
2618
2619    if data_driven_paint > MAX_DYNAMIC_DATA_DRIVEN_PAINT {
2620        return Err(PluginError::invalid_argument(format!(
2621            "layer '{}' has {data_driven_paint} data-driven paint properties, exceeding maximum ({MAX_DYNAMIC_DATA_DRIVEN_PAINT})",
2622            desc.name
2623        )));
2624    }
2625
2626    for prop in &properties {
2627        if let Some(base) = prop.name.strip_suffix("-transition")
2628            && paint_names.contains(base)
2629        {
2630            return Err(PluginError::invalid_argument(format!(
2631                "property '{}' collides with paint transition property for '{base}'",
2632                prop.name
2633            )));
2634        }
2635    }
2636
2637    let name_owned = desc.name.to_owned();
2638    let is_volume = desc.is_volume;
2639
2640    // Initialize plugin (e.g., create shader programs) before leaking anything.
2641    plugin.init(&Host::from_backend(&EngineHost))?;
2642
2643    let name = leak_str(name_owned);
2644    let dyn_properties: Vec<DynamicPropertyDesc> = properties
2645        .into_iter()
2646        .map(|p| {
2647            let default = match p.default {
2648                ValidatedDefault::Float(v) => DynamicDefault::Float(v),
2649                ValidatedDefault::Bool(v) => DynamicDefault::Bool(v),
2650                ValidatedDefault::Color(v) => DynamicDefault::Color(v),
2651                ValidatedDefault::Vec2(v) => DynamicDefault::Vec2(v),
2652                ValidatedDefault::LatLng(v) => DynamicDefault::LatLng(v),
2653                ValidatedDefault::Rotation(v) => DynamicDefault::Rotation(v),
2654                ValidatedDefault::String(v) => DynamicDefault::String(leak_str(v)),
2655                ValidatedDefault::Enum { variants, default } => {
2656                    let leaked_variants: Vec<&'static str> = variants.into_iter().map(leak_str).collect();
2657                    DynamicDefault::Enum { variants: Box::leak(leaked_variants.into_boxed_slice()), default }
2658                }
2659            };
2660            DynamicPropertyDesc {
2661                name: leak_str(p.name),
2662                scope: p.scope,
2663                data_driven: p.data_driven,
2664                default,
2665                attribute: p.attribute.map(leak_str),
2666                paint_lays_out: p.paint_lays_out,
2667            }
2668        })
2669        .collect();
2670
2671    let style_type = DynamicStyleLayerType::leak(DynamicLayerDesc {
2672        info: LayerTypeInfo { name, source: source_kind, from_json: true },
2673        properties: dyn_properties,
2674    })
2675    .map_err(|e| PluginError::invalid_argument(e.to_string()))?;
2676
2677    let config = DynamicLayerConfig { style: style_type, tile_order, terrain, volume: is_volume, picks_tiles };
2678
2679    let handler = Arc::new(PluginLayerHandler { name, plugin });
2680    Ok(DynamicLayerType::leak(config, handler))
2681}