diff --git a/.ai/memory/architecture/core-library.md b/.ai/memory/architecture/core-library.md index bb8f6ad..3b38975 100644 --- a/.ai/memory/architecture/core-library.md +++ b/.ai/memory/architecture/core-library.md @@ -52,6 +52,17 @@ Renderers must treat a null scene as a failed layer. Scene building skips empty geometry, renders polygonal members of geometry collections, and counts other skipped parts in `VectorRenderScene::skippedGeometryCount`. +`MapView` automatically builds viewport-filtered layer scenes with a calculated +margin only when the OGR driver reports a native fast spatial filter. The +private layer cache records the processing extent and retains immutable +geometry and backend mesh identity while the visible extent remains inside it. +Drivers without a fast filter retain complete scenes rather than repeatedly +reading the whole source. Prepared scenes supplied through `AddLayer` are also +complete snapshots and have no processing-extent restriction. Filtered scene +construction must not replace a layer's cached full extent or feature count +with the selected subset. See `VectorRenderSceneOptions`, +`VectorLayerAccess::ForEachGeometry`, and `MapView.cpp`. + ## References - [Architecture documentation](../../../docs/ARCHITECTURE.md#module-design) diff --git a/.github/plans/Vector-Rendering-Performance-Improvement.md b/.github/plans/Vector-Rendering-Performance-Improvement.md index d77356e..ad7a8f3 100644 --- a/.github/plans/Vector-Rendering-Performance-Improvement.md +++ b/.github/plans/Vector-Rendering-Performance-Improvement.md @@ -387,6 +387,27 @@ When the user pans or zooms: - Small pans do not cause complete layer reconstruction. - No visible features are accidentally omitted at viewport boundaries. +### Phase 5 implementation and limitations + +- `MapView` requests features through an OGR bounding-box spatial filter when + the driver reports `OLCFastSpatialFilter`. The margin is at least 64 pixels + and grows with the viewport size to cover longer navigation steps. +- Filtered scenes retain source geometry and backend cache identity while the + visible extent remains inside the processed extent. +- Pans or zoom-outs beyond the margin rebuild the affected layer selection. + This phase does not yet provide incremental feature-level merging or tiling. +- Caller-prepared scenes remain complete snapshots and are not viewport + filtered. The ActiveX control currently supplies these prepared complete + scenes, so its large-layer initial load still processes every feature before + the first visible rendering. The phase remains open until that path uses + viewport-aware preparation or the acceptance criteria are revised. +- Drivers without a native fast spatial filter retain complete scenes instead + of repeatedly scanning the complete layer for marginal viewport changes. + An automatic filtered build that fails falls back to a complete scene. +- The skipped-feature counter is available only when OGR can return a + reliable non-forced layer feature count and the source uses a native fast + spatial filter. It never forces a complete scan for the diagnostic value. + --- # Phase 6 – Optimize OpenGL rendering and data transfer diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 15f7a05..800cdda 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -233,10 +233,17 @@ has no extent or transform of its own. in `skippedLayers` with a reason and do not stop the other layers. This includes `std::exception` errors except `std::bad_alloc`, which propagates. Exceptions outside that hierarchy also propagate. The scene - holds no view state and no references to the map or its datasets. + holds no view state and no references to the map or its datasets. The + lower-level scene options can apply an OGR spatial filter so callers load + only feature envelopes that intersect a requested extent. - **Shared viewport.** Renderers draw the scene through the `Viewport` passed - with it, so every layer uses the same transformation. A view change, such as - a resize, does not rebuild the scene. + with it, so every layer uses the same transformation. `MapView` builds + automatically prepared layer scenes from the visible extent plus a + 64-pixel margin. Small pans and zoom-in operations therefore retain the + immutable scene and backend mesh caches. A resize or navigation operation + that moves outside the cached processing extent rebuilds only the affected + layer scenes; prepared scenes supplied by a caller are complete snapshots + and remain reusable for every view. - **Redraws.** Map changes go through `MapView` (`AddLayer`, `RemoveLayer`, `ClearLayers`, `SetLayerVisible`), which marks the scene stale; `Scene()` assembles it from cached layer scenes on the next call. @@ -316,8 +323,13 @@ the frame trigger a full render. Wheel input calls `MapView::ZoomAt` at the cursor. The control acquires and releases mouse capture through either its window or its windowless in-place site, and ends a drag on capture loss, cancellation, close, or destruction. -These view changes do not rebuild the render scene, and both backends draw -through the updated viewport. +Automatically built `MapView` scenes use a viewport-relative processing margin: +small view changes reuse the scene, and a larger change rebuilds only affected +layer selections. The ActiveX control currently commits caller-prepared complete +scenes, so its view changes continue to reuse the complete snapshot and do not +request filtered scenes. Alternate-size draws use the live scene; filtered +direct-host scenes are therefore valid only through the live viewport. Hosts +that draw a different viewport must supply complete prepared scenes. Rendering consumes backend-neutral input prepared from core data; neither the coordinator nor a backend loads datasets or implements GIS rules. For each @@ -463,17 +475,25 @@ layers and other geometry types are not rendered. There is no reprojection, so coordinates remain in the source coordinate system and layers are assumed to share one. -Core prepares and retains the complete supported polygon scene in memory, -reading feature geometries sequentially without WKT serialization and -reparsing. MapView caches one scene per layer: visibility changes reassemble -the map snapshot without rereading visible layers, hidden layers are prepared -when first shown, and removing or clearing layers drops only the corresponding -cache entries. InvalidateLayerScene rebuilds one layer after source edits; -InvalidateScene clears all layer caches. Adding a prepared layer seeds its -cache directly. Layer scenes are immutable and shared through +For direct `CreateVectorRenderScene` and `CreateMapRenderScene` calls, Core +prepares and retains the complete supported polygon scene in memory. `MapView` +instead applies a padded visible-extent spatial filter to +automatically prepared layers when the driver reports +`OLCFastSpatialFilter`, while a caller-supplied prepared scene remains +complete. Drivers without a native fast filter retain complete scenes so a pan +does not repeatedly force a full-layer scan. +Core reads feature geometries sequentially without WKT serialization and +reparsing. MapView caches one filtered or complete scene per layer: visibility +changes reassemble the map snapshot without rereading visible layers, hidden +layers are prepared when first shown, and removing or clearing layers drops +only the corresponding cache entries. InvalidateLayerScene rebuilds one +layer after source edits; InvalidateScene clears all layer caches. Adding a +prepared layer seeds its cache directly. Layer scenes are immutable and shared through `std::shared_ptr`, so assembling the map snapshot -shares cached coordinates and meshes instead of copying them; peak memory -stays at one copy of each layer's geometry. +shares cached coordinates and meshes instead of copying them. An automatically +built layer holds its selected geometry once, and a prepared layer holds its +complete geometry once. Rebuilding a selection temporarily retains both the old +scene and the new selection until the assembled snapshot is replaced. OpenGL's lazily generated fill meshes have a second, backend-owned cache keyed by stable `LayerId` and the immutable scene identity. Reordering, hiding, redrawing, viewport changes, and backend selection retain valid entries. @@ -493,12 +513,13 @@ each polygon. Both backends read the flat buffers directly. Triangulation accepts a view without reconstructing nested vectors. Standalone `Polygon` and `Ring` types remain available for caller-created triangulation input. -There is no tiling, paging, or clipping to the visible extent. GDI skips a -layer whose device coordinates exceed its range. It clips drawing to the -requested target rectangle and the host's existing clip region, then restores -the device context. Fill triangulation runs when scene preparation explicitly -requests it or when OpenGL first needs a missing mesh. View changes (resize, -zoom, pan) and redraws reuse the retained meshes. The opt-in +There is no tiling or paging. GDI skips a layer whose device coordinates +exceed its range. It clips drawing to the requested target rectangle and the +host's existing clip region, then restores the device context. Fill +triangulation runs when scene preparation explicitly requests it or when +OpenGL first needs a missing mesh. View changes inside the scene's processing +margin and redraws reuse retained meshes; changes outside the margin replace +the affected scene and its backend mesh entry. The opt-in rendering baseline (see [TESTING.md](TESTING.md#rendering-performance-baseline)) tracks scene preparation, mesh storage, and backend frame costs on both a convex grid and a complex mix of concave, holed multipart, and many-vertex diff --git a/src/MapWinGIS.Core/include/mapwingis/map/MapView.h b/src/MapWinGIS.Core/include/mapwingis/map/MapView.h index 892fc6d..9080e10 100644 --- a/src/MapWinGIS.Core/include/mapwingis/map/MapView.h +++ b/src/MapWinGIS.Core/include/mapwingis/map/MapView.h @@ -28,11 +28,16 @@ namespace mwg /// /// Redraws: every mutator returns whether the displayed frame may have /// changed. Hosts request a redraw when it returns true and draw Scene() - /// through GetViewport(). Changes to the layer collection or visibility - /// mark the scene stale; Scene() rebuilds it on the next call. Adding a - /// prepared scene retains the existing geometry instead. Edits to source - /// geometry are not observed. Call InvalidateLayerScene for each affected - /// map layer, or InvalidateScene for all layers. + /// through GetViewport(). Automatically filtered scenes cover only the + /// live viewport plus a processing margin; drawing a different viewport + /// requires a complete prepared scene. Changes to the layer collection or + /// visibility mark the scene stale; Scene() rebuilds it on the next call. + /// For a valid viewport, automatically built layer scenes use a padded + /// spatial filter. Small viewport changes reuse the cached scene; a change + /// beyond that margin refreshes only the affected layer scenes. Adding a + /// prepared scene retains the existing complete geometry instead. Edits to + /// source geometry are not observed. Call InvalidateLayerScene for each + /// affected map layer, or InvalidateScene for all layers. /// /// Initial view: while the viewport has no view, adding a layer fits the /// viewport to the map. A fit that cannot happen because the viewport has @@ -160,8 +165,12 @@ namespace mwg /// per-layer scenes when the map or a layer scene changed. The /// reference stays valid for the lifetime of the MapView; a later /// call that reassembles the scene replaces its contents. Geometry - /// for a visible uncached layer is read once; visibility changes reuse - /// its cache. Reassembly shares cached geometry with the map snapshot + /// for a visible uncached layer is read once. A valid viewport limits + /// automatically built scenes to features intersecting a padded + /// visible extent when the driver supports a fast spatial filter. + /// Drivers without that capability retain a complete scene. Visibility + /// changes and viewport moves within the processing extent reuse + /// the cache. Reassembly shares cached geometry with the map snapshot /// instead of copying it, so a held LayerRenderScene::scene stays /// valid after the layer is invalidated or removed. /// Failed layers retain their diagnostics until explicitly invalidated. diff --git a/src/MapWinGIS.Core/include/mapwingis/rendering/MapRenderScene.h b/src/MapWinGIS.Core/include/mapwingis/rendering/MapRenderScene.h index 06d0cde..5aab5f3 100644 --- a/src/MapWinGIS.Core/include/mapwingis/rendering/MapRenderScene.h +++ b/src/MapWinGIS.Core/include/mapwingis/rendering/MapRenderScene.h @@ -44,6 +44,8 @@ namespace mwg::rendering /// The layer cannot be rendered, for example because it is not a /// polygon layer or its geometry cannot be read. See the message. Failed, + /// No polygon geometry intersects an applied spatial filter. + OutsideViewport, }; /// A map layer that is not part of a MapRenderScene. @@ -74,8 +76,9 @@ namespace mwg::rendering /// layers' source coordinate system; the scene does not reproject. /// /// The scene is a snapshot: later changes to the map or its sources are - /// not reflected, so create a new scene after the map changes. Reads - /// every visible layer completely. Not thread-safe; see Map. + /// not reflected, so create a new scene after the map changes. With no + /// spatial filter, every visible layer is read completely. Not + /// thread-safe; see Map. /// \throws std::bad_alloc when memory runs out. Other std::exception /// errors from individual layers are reported in skippedLayers. /// Exceptions not derived from std::exception propagate. @@ -86,6 +89,7 @@ namespace mwg::rendering /// Hidden, empty, and failed layers retain the same handling as the /// default overload. Fill preparation is disabled by default, so drawable /// layer scenes contain source rings without triangulating polygons. + /// \throws InvalidArgument when the spatial-filter extent is invalid. [[nodiscard]] MWG_CORE_API MapRenderScene CreateMapRenderScene( const Map& map, const VectorRenderSceneOptions& options); diff --git a/src/MapWinGIS.Core/include/mapwingis/rendering/VectorRenderScene.h b/src/MapWinGIS.Core/include/mapwingis/rendering/VectorRenderScene.h index c091f1f..890ff6b 100644 --- a/src/MapWinGIS.Core/include/mapwingis/rendering/VectorRenderScene.h +++ b/src/MapWinGIS.Core/include/mapwingis/rendering/VectorRenderScene.h @@ -135,6 +135,12 @@ namespace mwg /// Enable this only for a rendering operation that needs triangle /// meshes. Source geometry and bounds are prepared either way. bool prepareFillMeshes = false; + /// When present, only features whose bounding boxes intersect this + /// extent are converted. Drivers with OLCFastSpatialFilter avoid + /// reading the other features; other drivers may still read and + /// parse them. Scene construction restores the source filter. + /// \throws InvalidArgument when the extent is not valid. + std::optional spatialFilter; }; /// Owned polygon geometry and its source-coordinate bounds. @@ -164,8 +170,10 @@ namespace mwg /// has fewer than three points, are skipped and counted in /// skippedGeometryCount. Interior rings with fewer than three points /// are dropped. The returned coordinates remain in the layer's coordinate - /// system; this function does not transform projections. Not - /// thread-safe, consistent with the input layer's contract. + /// system; this function does not transform projections. When options + /// specify a spatial filter, sourceFeatureCount is the number of + /// matching source features and extent covers only their geometry. + /// Not thread-safe, consistent with the input layer's contract. /// \throws CoreError when the layer is not polygonal or contains no /// polygon geometry to render. [[nodiscard]] MWG_CORE_API VectorRenderScene CreateVectorRenderScene( @@ -175,7 +183,11 @@ namespace mwg /// /// The default is source geometry only. Set prepareFillMeshes to true /// when the requested fill rendering operation needs triangle meshes. - /// The default overload never invokes polygon triangulation. + /// Set spatialFilter to avoid converting geometry outside a viewport. + /// Drivers with OLCFastSpatialFilter can also avoid reading it. + /// Features returned by an OGR spatial filter include bounding-box + /// boundary intersections. The default overload never invokes polygon + /// triangulation. [[nodiscard]] MWG_CORE_API VectorRenderScene CreateVectorRenderScene( const VectorLayer& layer, const VectorRenderSceneOptions& options); diff --git a/src/MapWinGIS.Core/src/internal/VectorLayerAccess.h b/src/MapWinGIS.Core/src/internal/VectorLayerAccess.h index f9a05de..5f8ba57 100644 --- a/src/MapWinGIS.Core/src/internal/VectorLayerAccess.h +++ b/src/MapWinGIS.Core/src/internal/VectorLayerAccess.h @@ -26,10 +26,15 @@ namespace mwg::detail static std::int64_t ForEachGeometry( const VectorLayer& layer, const std::function& callback, - Extent* extent = nullptr); + Extent* extent = nullptr, + const Extent* spatialFilter = nullptr); /// Whether the source driver can return an extent without scanning /// every feature. [[nodiscard]] static bool HasFastExtent(const VectorLayer& layer); + + /// Whether MapView can safely reduce feature reads with the layer's + /// single active geometry field. + [[nodiscard]] static bool HasFastSpatialFilter(const VectorLayer& layer); }; } diff --git a/src/MapWinGIS.Core/src/internal/VectorRenderSceneBuilder.h b/src/MapWinGIS.Core/src/internal/VectorRenderSceneBuilder.h index f51e21d..19fb3df 100644 --- a/src/MapWinGIS.Core/src/internal/VectorRenderSceneBuilder.h +++ b/src/MapWinGIS.Core/src/internal/VectorRenderSceneBuilder.h @@ -31,4 +31,8 @@ namespace mwg::rendering::detail [[nodiscard]] VectorRenderScene BuildVectorRenderScene( const VectorLayer& layer, const VectorRenderSceneOptions& options = {}); + + /// Rejects programmer errors in scene options before per-layer failures + /// can convert them into skipped-layer diagnostics. + void ValidateVectorRenderSceneOptions(const VectorRenderSceneOptions& options); } diff --git a/src/MapWinGIS.Core/src/map/MapView.cpp b/src/MapWinGIS.Core/src/map/MapView.cpp index 041f0ee..756c371 100644 --- a/src/MapWinGIS.Core/src/map/MapView.cpp +++ b/src/MapWinGIS.Core/src/map/MapView.cpp @@ -6,6 +6,7 @@ */ #include "mapwingis/map/MapView.h" +#include #include #include #include @@ -16,12 +17,16 @@ #include "mapwingis/core/Error.h" #include "mapwingis/diagnostics/PerformanceDiagnostics.h" #include "mapwingis/vector/VectorDataset.h" +#include "internal/VectorLayerAccess.h" #include "internal/VectorRenderSceneBuilder.h" namespace mwg { namespace { + constexpr double kMinimumViewportSceneMarginPixels = 64.0; + constexpr double kViewportSceneMarginFraction = 0.5; + void ValidateStepFactor(const double factor) { if (!std::isfinite(factor) || factor <= 1.0) @@ -67,9 +72,61 @@ namespace mwg using LayerScene = rendering::detail::LayerScene; + struct CachedLayerScene + { + LayerScene scene; + Extent processingExtent; + /// True for complete scenes and stable failures. False with an + /// empty extent means that the scene is awaiting a valid viewport. + bool complete = true; + }; + + [[nodiscard]] Extent ViewportProcessingExtent() const + { + const Extent visible = _viewport.VisibleExtent(); + const std::optional resolution = _viewport.Resolution(); + if (!visible.IsValid() || !resolution.has_value()) + { + return {}; + } + const double horizontalMarginPixels = + std::max(kMinimumViewportSceneMarginPixels, + static_cast(_viewport.Width()) * + kViewportSceneMarginFraction); + const double verticalMarginPixels = + std::max(kMinimumViewportSceneMarginPixels, + static_cast(_viewport.Height()) * + kViewportSceneMarginFraction); + const double horizontalMargin = horizontalMarginPixels * *resolution; + const double verticalMargin = verticalMarginPixels * *resolution; + return { + visible.xMin - horizontalMargin, + visible.yMin - verticalMargin, + visible.xMax + horizontalMargin, + visible.yMax + verticalMargin}; + } + + [[nodiscard]] bool CacheCoversViewport(const CachedLayerScene& cached) const + { + const Extent visible = _viewport.VisibleExtent(); + if (!visible.IsValid() || cached.complete) + { + return true; + } + if (cached.processingExtent.IsEmpty()) + { + return false; + } + const Extent& processing = cached.processingExtent; + return processing.xMin <= visible.xMin && + processing.yMin <= visible.yMin && + processing.xMax >= visible.xMax && + processing.yMax >= visible.yMax; + } + Map _map; Viewport _viewport; - std::map _layerScenes; + std::map _layerScenes; rendering::MapRenderScene _scene; bool _sceneStale = false; std::optional _pendingFit; @@ -143,15 +200,19 @@ namespace mwg // Stage the cache node before AddLayer can change the map or pending // fit. Updating a node handle's key and inserting it later cannot allocate. - std::map staged; + std::map staged; if (empty) { - staged.emplace(LayerId{}, rendering::SkippedLayer{ - LayerId{}, rendering::LayerSkipReason::NoGeometry, {}}); + staged.emplace(LayerId{}, Impl::CachedLayerScene{ + rendering::SkippedLayer{ + LayerId{}, rendering::LayerSkipReason::NoGeometry, {}}, + {}, true}); } else { - staged.emplace(LayerId{}, rendering::LayerRenderScene{LayerId{}, scene}); + staged.emplace(LayerId{}, Impl::CachedLayerScene{ + rendering::LayerRenderScene{LayerId{}, scene}, + {}, true}); } auto cachedScene = staged.extract(staged.begin()); @@ -159,11 +220,11 @@ namespace mwg cachedScene.key() = id; if (empty) { - std::get(cachedScene.mapped()).layerId = id; + std::get(cachedScene.mapped().scene).layerId = id; } else { - std::get(cachedScene.mapped()).layerId = id; + std::get(cachedScene.mapped().scene).layerId = id; } _impl->_layerScenes.insert(std::move(cachedScene)); if (empty) @@ -287,8 +348,30 @@ namespace mwg const rendering::MapRenderScene& MapView::Scene() { - if (_impl->_sceneStale) + const Extent processingExtent = _impl->ViewportProcessingExtent(); + bool refreshScene = _impl->_sceneStale; + if (!refreshScene) + { + for (int position = 0; position < _impl->_map.LayerCount(); ++position) + { + const MapLayer& layer = _impl->_map.Layer(position); + if (!layer.IsVisible()) + { + continue; + } + const auto cached = _impl->_layerScenes.find(layer.Id()); + if (cached == _impl->_layerScenes.end() || + !_impl->CacheCoversViewport(cached->second)) + { + refreshScene = true; + break; + } + } + } + + if (refreshScene) { + _impl->_sceneStale = true; rendering::MapRenderScene scene; scene.layers.reserve(static_cast(_impl->_map.LayerCount())); scene.skippedLayers.reserve(static_cast(_impl->_map.LayerCount())); @@ -304,12 +387,47 @@ namespace mwg } auto cached = _impl->_layerScenes.find(layer.Id()); - if (cached == _impl->_layerScenes.end()) + if (cached == _impl->_layerScenes.end() || + !_impl->CacheCoversViewport(cached->second)) { diagnostics::PerformanceDiagnostics::IncrementCounter( diagnostics::PerformanceCounter::SceneCacheMisses); - cached = _impl->_layerScenes.emplace( - layer.Id(), rendering::detail::BuildLayerRenderScene(layer)).first; + rendering::VectorRenderSceneOptions options; + const bool canFilter = + processingExtent.IsValid() && + detail::VectorLayerAccess::HasFastSpatialFilter(layer.Source()); + if (canFilter) + { + options.spatialFilter = processingExtent; + } + Impl::LayerScene layerScene = + rendering::detail::BuildLayerRenderScene(layer, options); + bool complete = processingExtent.IsValid() && !canFilter; + if (canFilter) + { + const auto* skipped = + std::get_if(&layerScene); + if (skipped != nullptr && + skipped->reason == rendering::LayerSkipReason::Failed) + { + layerScene = + rendering::detail::BuildLayerRenderScene(layer, {}); + complete = true; + } + } + else if (const auto* skipped = + std::get_if(&layerScene); + skipped != nullptr && + skipped->reason == rendering::LayerSkipReason::Failed) + { + complete = true; + } + cached = _impl->_layerScenes.insert_or_assign( + layer.Id(), + Impl::CachedLayerScene{ + std::move(layerScene), + canFilter && !complete ? processingExtent : Extent{}, + complete}).first; } else { @@ -318,14 +436,14 @@ namespace mwg } if (const auto* drawable = - std::get_if(&cached->second)) + std::get_if(&cached->second.scene)) { scene.layers.push_back(*drawable); } else { scene.skippedLayers.push_back( - std::get(cached->second)); + std::get(cached->second.scene)); } } diff --git a/src/MapWinGIS.Core/src/rendering/MapRenderScene.cpp b/src/MapWinGIS.Core/src/rendering/MapRenderScene.cpp index 86acfac..14a65aa 100644 --- a/src/MapWinGIS.Core/src/rendering/MapRenderScene.cpp +++ b/src/MapWinGIS.Core/src/rendering/MapRenderScene.cpp @@ -40,7 +40,10 @@ namespace mwg::rendering if (scene.polygons.empty()) { - return SkippedLayer{layer.Id(), LayerSkipReason::NoGeometry, {}}; + const LayerSkipReason reason = options.spatialFilter.has_value() + ? LayerSkipReason::OutsideViewport + : LayerSkipReason::NoGeometry; + return SkippedLayer{layer.Id(), reason, {}}; } return LayerRenderScene{layer.Id(), std::make_shared(std::move(scene))}; } @@ -54,6 +57,7 @@ namespace mwg::rendering const Map& map, const VectorRenderSceneOptions& options) { + detail::ValidateVectorRenderSceneOptions(options); MapRenderScene result; for (int position = 0; position < map.LayerCount(); ++position) { diff --git a/src/MapWinGIS.Core/src/rendering/VectorRenderScene.cpp b/src/MapWinGIS.Core/src/rendering/VectorRenderScene.cpp index 9fe9237..2970bdf 100644 --- a/src/MapWinGIS.Core/src/rendering/VectorRenderScene.cpp +++ b/src/MapWinGIS.Core/src/rendering/VectorRenderScene.cpp @@ -239,13 +239,17 @@ namespace mwg::rendering { const diagnostics::PerformanceScope scope( diagnostics::PerformanceOperation::SceneBuild); + detail::ValidateVectorRenderSceneOptions(options); if (BaseShapeType(layer.Type()) != ShapeType::Polygon) { throw CoreError("Vector rendering supports polygon layers only"); } VectorRenderScene scene; - const bool hasFastExtent = mwg::detail::VectorLayerAccess::HasFastExtent(layer); + const bool supportsFastExtent = + mwg::detail::VectorLayerAccess::HasFastExtent(layer); + const bool hasFastExtent = + !options.spatialFilter.has_value() && supportsFastExtent; if (hasFastExtent) { scene.extent = layer.GetExtent(); @@ -259,7 +263,8 @@ namespace mwg::rendering diagnostics::PerformanceOperation::GeometryConversion); builder.AppendGeometry(geometry); }, - hasFastExtent ? nullptr : &scene.extent); + hasFastExtent ? nullptr : &scene.extent, + options.spatialFilter ? &*options.spatialFilter : nullptr); if (!options.prepareFillMeshes) { @@ -282,6 +287,15 @@ namespace mwg::rendering return scene; } + void detail::ValidateVectorRenderSceneOptions( + const VectorRenderSceneOptions& options) + { + if (options.spatialFilter.has_value() && !options.spatialFilter->IsValid()) + { + throw InvalidArgument("Vector scene spatial filter extent must be valid"); + } + } + VectorRenderScene CreateVectorRenderScene(const VectorLayer& layer) { return CreateVectorRenderScene(layer, {}); diff --git a/src/MapWinGIS.Core/src/vector/VectorDataset.cpp b/src/MapWinGIS.Core/src/vector/VectorDataset.cpp index 1ffabe0..6c26b73 100644 --- a/src/MapWinGIS.Core/src/vector/VectorDataset.cpp +++ b/src/MapWinGIS.Core/src/vector/VectorDataset.cpp @@ -466,9 +466,120 @@ namespace mwg std::int64_t detail::VectorLayerAccess::ForEachGeometry( const VectorLayer& layer, const std::function& callback, - Extent* extent) + Extent* extent, + const Extent* spatialFilter) { OGRLayer& ogrLayer = *layer._impl->_layer; + GIntBig unfilteredFeatureCount = -1; + if (spatialFilter != nullptr && + diagnostics::PerformanceDiagnostics::IsEnabled() && + detail::VectorLayerAccess::HasFastSpatialFilter(layer)) + { + const GDALDriver* const driver = + layer._impl->_dataset.GetDriver(); + const char* const driverName = + driver != nullptr ? driver->GetDescription() : nullptr; + // The Shapefile total can include deleted DBF records that OGR + // iteration never returns. + if (driverName == nullptr || + std::string_view(driverName) != "ESRI Shapefile") + { + GdalEnvironment::ClearLastError(); + unfilteredFeatureCount = ogrLayer.GetFeatureCount(FALSE); + GdalEnvironment::RethrowLogException(); + } + } + + struct SpatialFilterReset final + { + explicit SpatialFilterReset(OGRLayer& source, const int field) + : layer(source), geometryField(field) + { + } + + ~SpatialFilterReset() + { + if (!applied) + { + return; + } + try + { + Restore(); + } + catch (...) + { + // An original exception is already in flight; normal + // completion checks restoration and propagates its error. + } + } + + void Restore() + { + if (!applied) + { + return; + } + GdalEnvironment::ClearLastError(); + const OGRErr result = + layer.SetSpatialFilter(geometryField, previous.get()); + GdalEnvironment::RethrowLogException(); + if (result != OGRERR_NONE) + { + std::string message = "Cannot restore vector layer spatial filter"; + if (const std::string detail = GdalEnvironment::LastErrorMessage(); + !detail.empty()) + { + message += ": " + detail; + } + throw CoreError(message); + } + applied = false; + } + + OGRLayer& layer; + int geometryField; + OGRGeometryUniquePtr previous; + bool applied = false; + } spatialFilterReset{ogrLayer, ogrLayer.GetGeomFieldFilter()}; + + if (spatialFilter != nullptr) + { + GdalEnvironment::ClearLastError(); + if (const OGRGeometry* previous = ogrLayer.GetSpatialFilter(); + previous != nullptr) + { + spatialFilterReset.previous.reset(previous->clone()); + if (spatialFilterReset.previous == nullptr) + { + throw std::bad_alloc(); + } + } + GdalEnvironment::RethrowLogException(); + + // Arm restoration before applying: some drivers may mutate their + // filter state before returning an error. + spatialFilterReset.applied = true; + GdalEnvironment::ClearLastError(); + const OGRErr result = ogrLayer.SetSpatialFilterRect( + spatialFilterReset.geometryField, + spatialFilter->xMin, + spatialFilter->yMin, + spatialFilter->xMax, + spatialFilter->yMax); + GdalEnvironment::RethrowLogException(); + if (result != OGRERR_NONE) + { + std::string message = "Cannot apply vector layer spatial filter"; + if (const std::string detail = GdalEnvironment::LastErrorMessage(); + !detail.empty()) + { + message += ": " + detail; + } + throw CoreError(message); + } + } + const VectorLayer::Impl::IgnoredFields ignoredFields( ogrLayer, layer._impl->_fields, false); ogrLayer.ResetReading(); @@ -517,10 +628,23 @@ namespace mwg if (extent != nullptr) { *extent = computedExtent.value_or(Extent{}); - layer._impl->_extent = *extent; - layer._impl->_extentNeedsExactRecalculation = false; + if (spatialFilter == nullptr) + { + layer._impl->_extent = *extent; + layer._impl->_extentNeedsExactRecalculation = false; + } + } + if (spatialFilter == nullptr) + { + layer._impl->_featureCount = count; } - layer._impl->_featureCount = count; + else if (unfilteredFeatureCount >= count) + { + diagnostics::PerformanceDiagnostics::IncrementCounter( + diagnostics::PerformanceCounter::FeaturesSkippedOutsideViewport, + unfilteredFeatureCount - count); + } + spatialFilterReset.Restore(); return count; } @@ -529,6 +653,15 @@ namespace mwg return layer._impl->_layer->TestCapability(OLCFastGetExtent) != FALSE; } + bool detail::VectorLayerAccess::HasFastSpatialFilter(const VectorLayer& layer) + { + OGRLayer& ogrLayer = *layer._impl->_layer; + const OGRFeatureDefn* definition = ogrLayer.GetLayerDefn(); + return definition != nullptr && + definition->GetGeomFieldCount() == 1 && + ogrLayer.TestCapability(OLCFastSpatialFilter) != FALSE; + } + VectorLayer::VectorLayer(std::unique_ptr impl) : _impl(std::move(impl)) { diff --git a/tests/MapWinGIS.Core.Tests/MapRenderSceneTests.cpp b/tests/MapWinGIS.Core.Tests/MapRenderSceneTests.cpp index 9600f67..a24de9f 100644 --- a/tests/MapWinGIS.Core.Tests/MapRenderSceneTests.cpp +++ b/tests/MapWinGIS.Core.Tests/MapRenderSceneTests.cpp @@ -20,6 +20,7 @@ #include #include "TestData.h" +#include "mapwingis/core/Error.h" #include "mapwingis/gdal/GdalEnvironment.h" #include "mapwingis/map/Map.h" #include "mapwingis/map/MapView.h" @@ -223,6 +224,17 @@ TEST_F(MapRenderSceneTest, SkipsLayersWithoutGeometry) EXPECT_EQ(scene.skippedLayers[0].reason, rendering::LayerSkipReason::NoGeometry); } +TEST_F(MapRenderSceneTest, RejectsInvalidOptionsBeforeBuildingLayers) +{ + _map.AddLayer(OpenRectangles({{0.0, 0.0, 1.0, 1.0}})); + + EXPECT_THROW( + (void)rendering::CreateMapRenderScene( + _map, + rendering::VectorRenderSceneOptions{.spatialFilter = Extent{}}), + InvalidArgument); +} + TEST_F(MapRenderSceneTest, LayerThatCannotBeRenderedDoesNotStopTheOthers) { const LayerId below = _map.AddLayer(OpenRectangles({{0.0, 0.0, 1.0, 1.0}})); diff --git a/tests/MapWinGIS.Core.Tests/MapViewTests.cpp b/tests/MapWinGIS.Core.Tests/MapViewTests.cpp index 8c17b8f..902b3ff 100644 --- a/tests/MapWinGIS.Core.Tests/MapViewTests.cpp +++ b/tests/MapWinGIS.Core.Tests/MapViewTests.cpp @@ -302,18 +302,21 @@ TEST_F(MapViewTest, MapChangesRebuildTheSceneAndReportARedraw) EXPECT_FALSE(_view.SetLayerVisible(second, true)); } -TEST_F(MapViewTest, SceneIsReusedUntilTheMapChanges) +TEST_F(MapViewTest, SceneIsReusedWhileViewportCoverageRemainsValid) { + ASSERT_TRUE(_view.Resize(300, 200)); _view.AddLayer(OpenRectangles({{0.0, 0.0, 1.0, 1.0}})); const rendering::MapRenderScene& scene = _view.Scene(); - const auto* polygons = scene.layers.front().scene->polygons.Coordinates().data(); + const std::shared_ptr layerScene = + scene.layers.front().scene; - ASSERT_TRUE(_view.Resize(300, 200)); - EXPECT_EQ(_view.Scene().layers.front().scene->polygons.Coordinates().data(), polygons); + ASSERT_TRUE(_view.Pan(*_view.GetViewport().Resolution(), 0.0)); + EXPECT_EQ(_view.Scene().layers.front().scene, layerScene); EXPECT_TRUE(_view.InvalidateScene()); EXPECT_EQ(&_view.Scene(), &scene); EXPECT_EQ(scene.layers.size(), 1U); + EXPECT_NE(scene.layers.front().scene, layerScene); } TEST_F(MapViewTest, PreparedLayersRetainTheirGeometryUntilInvalidated) @@ -546,6 +549,35 @@ TEST_F(MapViewTest, AllocationFailurePreservesThePublishedSceneAndAllowsRetry) EXPECT_EQ(scene.layers[1].layerId, second); } +TEST_F(MapViewTest, InterruptedViewportRefreshPreservesThePublishedSceneAndRetries) +{ + VectorReadTestDriver driver; + driver.fastSpatialFilter = true; + std::shared_ptr dataset = + VectorDataset::Open(VectorReadTestDriver::kPath); + MapView view; + ASSERT_TRUE(view.Resize(300, 200)); + const LayerId layer = view.AddLayer(dataset); + const auto& published = view.Scene(); + ASSERT_EQ(published.layers.size(), 1U); + EXPECT_EQ(published.layers.front().layerId, layer); + const std::shared_ptr original = + published.layers.front().scene; + + ASSERT_TRUE(view.Pan(1000.0, 0.0)); + driver.failExtentCapabilityAllocation = true; + + EXPECT_THROW((void)view.Scene(), std::bad_alloc); + EXPECT_EQ(published.layers.front().scene, original); + + driver.failExtentCapabilityAllocation = false; + const auto& refreshed = view.Scene(); + ASSERT_EQ(refreshed.layers.size(), 1U); + EXPECT_EQ(refreshed.layers.front().layerId, layer); + EXPECT_NE(refreshed.layers.front().scene, original); + EXPECT_TRUE(refreshed.skippedLayers.empty()); +} + TEST_F(MapViewTest, ComplexSceneMeshesSurviveViewportChanges) { const std::shared_ptr dataset = OpenComplexPolygons(); @@ -588,8 +620,11 @@ TEST_F(MapViewTest, ComplexSceneMeshesSurviveViewportChanges) EXPECT_EQ(navigated.fillMeshes[1]->indices.size(), holedMeshIndices); EXPECT_EQ(navigated.polygons[1].size(), holedPolygonRings); - // Reassembly keeps the cached meshes and original rings for outlines and GDI. - const LayerId second = _view.AddLayer(OpenRectangles({{100.0, 0.0, 110.0, 10.0}})); + // Reassembly keeps complete prepared meshes and original rings for + // outlines and GDI, even when that scene lies outside the current view. + const auto secondDataset = OpenRectangles({{100.0, 0.0, 110.0, 10.0}}); + const LayerId second = _view.AddLayer( + secondDataset, rendering::CreateVectorRenderScene(*secondDataset)); ASSERT_EQ(_view.Scene().layers.size(), 2U); const rendering::VectorRenderScene& rebuilt = *_view.Scene().layers.front().scene; ASSERT_EQ(rebuilt.polygons.size(), 2U); @@ -603,6 +638,199 @@ TEST_F(MapViewTest, ComplexSceneMeshesSurviveViewportChanges) EXPECT_TRUE(_view.Scene().layers.front().scene->fillMeshes[1].has_value()); } +TEST_F(MapViewTest, FiltersAutomaticScenesToThePaddedViewportAndReusesSmallPans) +{ + ASSERT_TRUE(_view.Resize(100, 100)); + const auto nearDataset = OpenRectangles({{0.0, 0.0, 10.0, 10.0}}); + const auto farDataset = OpenRectangles({{1000.0, 0.0, 1010.0, 10.0}}); + const LayerId near = _view.AddLayer(nearDataset); + const LayerId far = _view.AddLayer(farDataset); + + const rendering::MapRenderScene& firstScene = _view.Scene(); + ASSERT_EQ(firstScene.layers.size(), 1U); + EXPECT_EQ(firstScene.layers.front().layerId, near); + ASSERT_EQ(firstScene.skippedLayers.size(), 1U); + EXPECT_EQ(firstScene.skippedLayers.front().layerId, far); + EXPECT_EQ(firstScene.skippedLayers.front().reason, + rendering::LayerSkipReason::OutsideViewport); + const void* coordinates = firstScene.layers.front().scene->polygons.Coordinates().data(); + + ASSERT_TRUE(_view.Pan(1.0, 0.0)); + EXPECT_EQ(&_view.Scene(), &firstScene); + EXPECT_EQ(_view.Scene().layers.front().scene->polygons.Coordinates().data(), + coordinates); + + ASSERT_TRUE(_view.Pan(1000.0, 0.0)); + const rendering::MapRenderScene& movedScene = _view.Scene(); + ASSERT_EQ(movedScene.layers.size(), 1U); + EXPECT_EQ(movedScene.layers.front().layerId, far); + ASSERT_EQ(movedScene.skippedLayers.size(), 1U); + EXPECT_EQ(movedScene.skippedLayers.front().layerId, near); +} + +TEST_F(MapViewTest, ReusesGeometryThatBecomesVisibleInsideTheProcessingMargin) +{ + ASSERT_TRUE(_view.Resize(100, 100)); + const LayerId near = _view.AddLayer( + OpenRectangles({{0.0, 0.0, 10.0, 10.0}})); + ASSERT_EQ(_view.Scene().layers.size(), 1U); + + const Viewport& viewport = _view.GetViewport(); + const Extent visible = viewport.VisibleExtent(); + const double resolution = *viewport.Resolution(); + const Extent marginFeature{ + visible.xMax + resolution, + visible.yMin, + visible.xMax + 2.0 * resolution, + visible.yMin + 2.0 * resolution}; + const LayerId margin = _view.AddLayer(OpenRectangles({marginFeature})); + + const auto& prepared = _view.Scene(); + ASSERT_EQ(prepared.layers.size(), 2U); + EXPECT_EQ(prepared.layers[0].layerId, near); + EXPECT_EQ(prepared.layers[1].layerId, margin); + const std::shared_ptr marginScene = + prepared.layers[1].scene; + EXPECT_FALSE(IsVisible(viewport, marginFeature)); + + ASSERT_TRUE(_view.Pan(3.0 * resolution, 0.0)); + const auto& panned = _view.Scene(); + EXPECT_EQ(panned.layers[1].scene, marginScene); + EXPECT_TRUE(IsVisible(_view.GetViewport(), marginFeature)); +} + +TEST_F(MapViewTest, RebuildsFilteredScenesWhenTheViewportGrowsOrZoomsOut) +{ + ASSERT_TRUE(_view.Resize(100, 100)); + const LayerId layer = _view.AddLayer( + OpenRectangles({{0.0, 0.0, 10.0, 10.0}})); + const auto& initial = _view.Scene(); + ASSERT_EQ(initial.layers.size(), 1U); + EXPECT_EQ(initial.layers.front().layerId, layer); + const std::shared_ptr initialScene = + initial.layers.front().scene; + + ASSERT_TRUE(_view.Resize(400, 400)); + const auto& resized = _view.Scene(); + ASSERT_EQ(resized.layers.size(), 1U); + EXPECT_NE(resized.layers.front().scene, initialScene); + const std::shared_ptr resizedScene = + resized.layers.front().scene; + + ASSERT_TRUE(_view.ZoomOut(4.0)); + const auto& zoomed = _view.Scene(); + ASSERT_EQ(zoomed.layers.size(), 1U); + EXPECT_NE(zoomed.layers.front().scene, resizedScene); +} + +TEST_F(MapViewTest, AwaitingViewportSceneIsRefilteredAfterResize) +{ + MapView view; + view.AddLayer(OpenRectangles({{0.0, 0.0, 10.0, 10.0}, + {20.0, 20.0, 30.0, 30.0}})); + const auto& withoutViewport = view.Scene(); + ASSERT_EQ(withoutViewport.layers.size(), 1U); + ASSERT_EQ(withoutViewport.layers.front().scene->polygons.size(), 2U); + const std::shared_ptr complete = + withoutViewport.layers.front().scene; + + ASSERT_TRUE(view.Resize(100, 100)); + const auto& resized = view.Scene(); + ASSERT_EQ(resized.layers.size(), 1U); + EXPECT_NE(resized.layers.front().scene, complete); +} + +TEST_F(MapViewTest, DriverWithoutFastSpatialFilterKeepsItsCompleteScene) +{ + VectorReadTestDriver driver; + driver.fastExtent = true; + MapView view; + ASSERT_TRUE(view.Resize(100, 100)); + const LayerId layer = view.AddLayer( + VectorDataset::Open(VectorReadTestDriver::kPath)); + const auto& initial = view.Scene(); + ASSERT_EQ(initial.layers.size(), 1U); + EXPECT_EQ(initial.layers.front().layerId, layer); + const std::shared_ptr complete = + initial.layers.front().scene; + + ASSERT_TRUE(view.Pan(1000.0, 0.0)); + const auto& panned = view.Scene(); + ASSERT_EQ(panned.layers.size(), 1U); + EXPECT_EQ(panned.layers.front().scene, complete); + EXPECT_EQ(panned.layers.front().scene->sourceFeatureCount, 3); + EXPECT_EQ(driver.readCalls, 4); +} + +TEST_F(MapViewTest, SpatialFilterFailureFallsBackToACompleteScene) +{ + VectorReadTestDriver driver; + driver.fastExtent = true; + driver.fastSpatialFilter = true; + driver.failSpatialFilter = true; + MapView view; + ASSERT_TRUE(view.Resize(100, 100)); + const LayerId layer = view.AddLayer( + VectorDataset::Open(VectorReadTestDriver::kPath)); + const GdalEnvironment::QuietScope quiet; + + const auto& scene = view.Scene(); + ASSERT_EQ(scene.layers.size(), 1U); + EXPECT_EQ(scene.layers.front().layerId, layer); + EXPECT_EQ(scene.layers.front().scene->sourceFeatureCount, 3); + EXPECT_TRUE(scene.skippedLayers.empty()); + EXPECT_GE(driver.spatialFilterCalls, 2); + + const std::shared_ptr complete = + scene.layers.front().scene; + ASSERT_TRUE(view.Pan(1000.0, 0.0)); + EXPECT_EQ(view.Scene().layers.front().scene, complete); +} + +TEST_F(MapViewTest, PreparedSceneRemainsCompleteAfterALargePan) +{ + ASSERT_TRUE(_view.Resize(100, 100)); + const auto dataset = OpenRectangles({{0.0, 0.0, 10.0, 10.0}}); + const LayerId layer = _view.AddLayer( + dataset, rendering::CreateVectorRenderScene(*dataset)); + const auto& initial = _view.Scene(); + ASSERT_EQ(initial.layers.size(), 1U); + EXPECT_EQ(initial.layers.front().layerId, layer); + const std::shared_ptr complete = + initial.layers.front().scene; + + ASSERT_TRUE(_view.Pan(1000.0, 0.0)); + const auto& panned = _view.Scene(); + ASSERT_EQ(panned.layers.size(), 1U); + EXPECT_EQ(panned.layers.front().scene, complete); +} + +TEST_F(MapViewTest, ShowingALayerAfterPanRebuildsItsFilteredSelection) +{ + ASSERT_TRUE(_view.Resize(100, 100)); + const LayerId near = _view.AddLayer( + OpenRectangles({{0.0, 0.0, 10.0, 10.0}})); + const LayerId far = _view.AddLayer( + OpenRectangles({{1000.0, 0.0, 1010.0, 10.0}})); + const auto& initial = _view.Scene(); + ASSERT_EQ(initial.layers.size(), 1U); + const std::shared_ptr nearScene = + initial.layers.front().scene; + + ASSERT_TRUE(_view.SetLayerVisible(near, false)); + ASSERT_EQ(_view.Scene().skippedLayers.size(), 2U); + ASSERT_TRUE(_view.Pan(1000.0, 0.0)); + ASSERT_TRUE(_view.SetLayerVisible(near, true)); + const auto& shown = _view.Scene(); + ASSERT_EQ(shown.layers.size(), 1U); + EXPECT_EQ(shown.layers.front().layerId, far); + ASSERT_TRUE(_view.Pan(-1000.0, 0.0)); + const auto& returned = _view.Scene(); + ASSERT_EQ(returned.layers.size(), 1U); + EXPECT_EQ(returned.layers.front().layerId, near); + EXPECT_NE(returned.layers.front().scene, nearScene); +} + TEST_F(MapViewTest, PreparedEmptyLayerPreservesExistingAndStaleScenes) { const LayerId first = _view.AddLayer(OpenRectangles({{0, 0, 1, 1}})); diff --git a/tests/MapWinGIS.Core.Tests/PerformanceDiagnosticsTests.cpp b/tests/MapWinGIS.Core.Tests/PerformanceDiagnosticsTests.cpp index e31e49c..986d0eb 100644 --- a/tests/MapWinGIS.Core.Tests/PerformanceDiagnosticsTests.cpp +++ b/tests/MapWinGIS.Core.Tests/PerformanceDiagnosticsTests.cpp @@ -129,6 +129,31 @@ TEST_F(PerformanceDiagnosticsTest, DoesNotTriangulateScenesByDefault) EXPECT_EQ(snapshot.Counter(PerformanceCounter::PolygonsTriangulated), 0); } +TEST_F(PerformanceDiagnosticsTest, CountsFeaturesExcludedBySpatialFilter) +{ + TempDirectory directory; + constexpr std::array rectangles{ + {{0, 0, 10, 10}, {20, 20, 30, 30}, {40, 40, 50, 50}}}; + const std::filesystem::path path = + MakeRectanglesDataset(directory.Path(), "viewport.gpkg", rectangles); + const std::unique_ptr dataset = VectorDataset::Open(path); + + PerformanceDiagnostics::Reset(); + const rendering::VectorRenderScene scene = + rendering::CreateVectorRenderScene( + *dataset, + rendering::VectorRenderSceneOptions{ + .spatialFilter = Extent{20, 20, 20, 20}}); + + ASSERT_EQ(scene.polygons.size(), 1U); + const PerformanceSnapshot snapshot = PerformanceDiagnostics::Snapshot(); + EXPECT_EQ(snapshot.Counter(PerformanceCounter::FeaturesProcessed), 1); + EXPECT_EQ(snapshot.Counter(PerformanceCounter::GeometriesLoaded), 1); + EXPECT_EQ( + snapshot.Counter(PerformanceCounter::FeaturesSkippedOutsideViewport), + 2); +} + TEST_F(PerformanceDiagnosticsTest, RecordsSceneCacheMissesAndHits) { TempDirectory directory; diff --git a/tests/MapWinGIS.Core.Tests/TestData.cpp b/tests/MapWinGIS.Core.Tests/TestData.cpp index e93c39c..b94344c 100644 --- a/tests/MapWinGIS.Core.Tests/TestData.cpp +++ b/tests/MapWinGIS.Core.Tests/TestData.cpp @@ -47,6 +47,7 @@ namespace mwg::test { _definition->Reference(); _definition->SetGeomType(wkbPolygon); + _state.openedLayer = this; OGRFieldDefn nameField("NAME", OFTString); _definition->AddFieldDefn(&nameField); OGRFieldDefn valueField("VALUE", OFTInteger); @@ -55,6 +56,10 @@ namespace mwg::test ~VectorReadTestLayer() override { + if (_state.openedLayer == this) + { + _state.openedLayer = nullptr; + } _definition->Release(); } @@ -141,6 +146,11 @@ namespace mwg::test throw std::bad_alloc(); return _state.fastExtent ? TRUE : FALSE; } + if (capability != nullptr && + std::string_view(capability) == OLCFastSpatialFilter) + { + return _state.fastSpatialFilter ? TRUE : FALSE; + } return capability != nullptr && std::string_view(capability) == OLCRandomWrite ? TRUE @@ -148,6 +158,21 @@ namespace mwg::test } protected: + OGRErr ISetSpatialFilter( + const int geometryField, + const OGRGeometry* filter) override + { + ++_state.spatialFilterCalls; + if (_state.failSpatialFilter) + { + _state.failSpatialFilter = false; + CPLError(CE_Failure, CPLE_AppDefined, + "Simulated spatial filter failure"); + return OGRERR_FAILURE; + } + return OGRLayer::ISetSpatialFilter(geometryField, filter); + } + OGRErr ISetFeature(OGRFeature* feature) override { if (_state.failSetFeature) diff --git a/tests/MapWinGIS.Core.Tests/TestData.h b/tests/MapWinGIS.Core.Tests/TestData.h index 6995c9c..0e43902 100644 --- a/tests/MapWinGIS.Core.Tests/TestData.h +++ b/tests/MapWinGIS.Core.Tests/TestData.h @@ -18,6 +18,7 @@ #include "mapwingis/core/Extent.h" class GDALDriver; +class OGRLayer; namespace mwg::test { @@ -45,9 +46,12 @@ namespace mwg::test bool onlyEmptyGeometries = false; bool unknownCount = false; bool fastExtent = false; + bool fastSpatialFilter = false; + bool failSpatialFilter = false; bool failExtentCapabilityAllocation = false; bool ignoredFields = false; bool ignoredGeometry = false; + OGRLayer* openedLayer = nullptr; std::string layerName = "features"; std::string storedName = "Original"; int storedValue = 0; @@ -56,6 +60,7 @@ namespace mwg::test int attributeReadCalls = 0; int countCalls = 0; int extentCalls = 0; + int spatialFilterCalls = 0; int recomputeExtentCalls = 0; std::string recomputeExtentStatement; diff --git a/tests/MapWinGIS.Core.Tests/VectorRenderSceneTests.cpp b/tests/MapWinGIS.Core.Tests/VectorRenderSceneTests.cpp index 538828c..a8adbb9 100644 --- a/tests/MapWinGIS.Core.Tests/VectorRenderSceneTests.cpp +++ b/tests/MapWinGIS.Core.Tests/VectorRenderSceneTests.cpp @@ -333,6 +333,136 @@ TEST_P(VectorRenderSceneTest, CopiesPolygonCoordinatesAndExtent) EXPECT_DOUBLE_EQ(scene.polygons.front().front().back().y, Provinces::kMinY); } +TEST(VectorRenderScene, SpatialFilterReadsOnlyIntersectingFeatures) +{ + TempDirectory directory; + const std::vector rectangles{ + {0.0, 0.0, 1.0, 1.0}, + {10.0, 10.0, 11.0, 11.0}, + {20.0, 20.0, 21.0, 21.0}}; + const auto dataset = VectorDataset::Open(MakeRectanglesDataset( + directory.Path(), "spatial-filter.gpkg", rectangles)); + EXPECT_EQ(dataset->Layer(0).FeatureCount(), 3); + const Extent fullExtent = dataset->Layer(0).GetExtent(); + EXPECT_DOUBLE_EQ(fullExtent.xMin, 0.0); + EXPECT_DOUBLE_EQ(fullExtent.yMin, 0.0); + EXPECT_DOUBLE_EQ(fullExtent.xMax, 21.0); + EXPECT_DOUBLE_EQ(fullExtent.yMax, 21.0); + + const rendering::VectorRenderScene scene = + rendering::CreateVectorRenderScene( + dataset->Layer(0), + rendering::VectorRenderSceneOptions{ + .spatialFilter = Extent{10.0, 10.0, 10.0, 10.0}}); + + ASSERT_EQ(scene.polygons.size(), 1U); + EXPECT_EQ(scene.sourceFeatureCount, 1); + EXPECT_DOUBLE_EQ(scene.extent.xMin, 10.0); + EXPECT_DOUBLE_EQ(scene.extent.yMin, 10.0); + EXPECT_DOUBLE_EQ(scene.extent.xMax, 11.0); + EXPECT_DOUBLE_EQ(scene.extent.yMax, 11.0); + EXPECT_EQ(dataset->Layer(0).FeatureCount(), 3); + const Extent cachedExtent = dataset->Layer(0).GetExtent(); + EXPECT_DOUBLE_EQ(cachedExtent.xMin, fullExtent.xMin); + EXPECT_DOUBLE_EQ(cachedExtent.yMin, fullExtent.yMin); + EXPECT_DOUBLE_EQ(cachedExtent.xMax, fullExtent.xMax); + EXPECT_DOUBLE_EQ(cachedExtent.yMax, fullExtent.yMax); +} + +TEST(VectorRenderScene, RejectsInvalidSpatialFilter) +{ + TempDirectory directory; + const std::vector rectangles{{0.0, 0.0, 1.0, 1.0}}; + const auto dataset = VectorDataset::Open(MakeRectanglesDataset( + directory.Path(), "invalid-filter.gpkg", rectangles)); + + EXPECT_THROW( + (void)rendering::CreateVectorRenderScene( + dataset->Layer(0), + rendering::VectorRenderSceneOptions{.spatialFilter = Extent{}}), + InvalidArgument); +} + +TEST(VectorRenderScene, RestoresTheSourceSpatialFilter) +{ + VectorReadTestDriver driver; + const auto dataset = VectorDataset::Open(VectorReadTestDriver::kPath); + ASSERT_NE(driver.openedLayer, nullptr); + + OGRPolygon previous; + OGRLinearRing ring; + ring.addPoint(100.0, 100.0); + ring.addPoint(101.0, 100.0); + ring.addPoint(101.0, 101.0); + ring.addPoint(100.0, 101.0); + ring.closeRings(); + ASSERT_EQ(previous.addRing(&ring), OGRERR_NONE); + ASSERT_EQ(driver.openedLayer->SetSpatialFilter(&previous), OGRERR_NONE); + + const rendering::VectorRenderScene scene = + rendering::CreateVectorRenderScene( + dataset->Layer(0), + rendering::VectorRenderSceneOptions{ + .spatialFilter = Extent{0.0, 0.0, 1.0, 1.0}}); + EXPECT_EQ(scene.polygons.size(), 1U); + + const OGRGeometry* restored = driver.openedLayer->GetSpatialFilter(); + ASSERT_NE(restored, nullptr); + EXPECT_TRUE(restored->Equals(&previous)); + EXPECT_EQ(driver.nextFeature, 0); + + const rendering::VectorRenderScene unfiltered = + rendering::CreateVectorRenderScene(dataset->Layer(0)); + EXPECT_EQ(unfiltered.polygons.size(), 1U); + EXPECT_EQ(unfiltered.sourceFeatureCount, 3); + EXPECT_EQ(driver.nextFeature, 0); +} + +TEST(VectorRenderScene, RestoresFilterCursorAndCachedMetadataAfterReadFailure) +{ + VectorReadTestDriver driver; + driver.fastExtent = true; + driver.failOnSecondRead = true; + const auto dataset = VectorDataset::Open(VectorReadTestDriver::kPath); + ASSERT_NE(driver.openedLayer, nullptr); + EXPECT_EQ(dataset->Layer(0).FeatureCount(), 3); + const Extent fullExtent = dataset->Layer(0).GetExtent(); + + OGRPolygon previous; + OGRLinearRing ring; + ring.addPoint(0.0, 0.0); + ring.addPoint(1.0, 0.0); + ring.addPoint(1.0, 1.0); + ring.addPoint(0.0, 1.0); + ring.closeRings(); + ASSERT_EQ(previous.addRing(&ring), OGRERR_NONE); + ASSERT_EQ(driver.openedLayer->SetSpatialFilter(&previous), OGRERR_NONE); + const GdalEnvironment::QuietScope quiet; + + EXPECT_THROW( + (void)rendering::CreateVectorRenderScene( + dataset->Layer(0), + rendering::VectorRenderSceneOptions{ + .spatialFilter = Extent{0.0, 0.0, 1.0, 1.0}}), + CoreError); + + const OGRGeometry* restored = driver.openedLayer->GetSpatialFilter(); + ASSERT_NE(restored, nullptr); + EXPECT_TRUE(restored->Equals(&previous)); + EXPECT_EQ(driver.nextFeature, 0); + EXPECT_EQ(dataset->Layer(0).FeatureCount(), 3); + const Extent cachedExtent = dataset->Layer(0).GetExtent(); + EXPECT_EQ(cachedExtent.xMin, fullExtent.xMin); + EXPECT_EQ(cachedExtent.yMin, fullExtent.yMin); + EXPECT_EQ(cachedExtent.xMax, fullExtent.xMax); + EXPECT_EQ(cachedExtent.yMax, fullExtent.yMax); + + driver.failOnSecondRead = false; + EXPECT_EQ(rendering::CreateVectorRenderScene(dataset->Layer(0)).sourceFeatureCount, + 3); + EXPECT_EQ(driver.nextFeature, 0); +} + TEST(VectorRenderScene, AcceptsPolygonZAndPolygonM) { GdalEnvironment::Initialize();