diff --git a/.ai/memory/architecture/activex.md b/.ai/memory/architecture/activex.md index 28a19de..4211109 100644 --- a/.ai/memory/architecture/activex.md +++ b/.ai/memory/architecture/activex.md @@ -48,6 +48,18 @@ while a changed scene for one layer invalidates only that entry. The coordinator prunes removed IDs before every backend choice, and explicit layer or scene invalidation releases the retained CPU mesh storage. +The screen OpenGL renderer also caches context-local vertex and index buffers +for immutable layer geometry when OpenGL 1.5 or +`GL_ARB_vertex_buffer_object` is available. Stored vertices are localized to +one origin for the layer, so pan and zoom change a model-view transform without +reuploading coordinates. Scene changes and explicit invalidation release the +affected buffers; the client-array path remains the fallback. Temporary +renderers share CPU fill meshes but own separate GPU buffers because buffer +names belong to their OpenGL contexts. A framebuffer readback remains required +for GDI presentation, but the bottom-up BGRA buffer can be passed to a +bottom-up DIB without a CPU row reversal. See +`OpenGlVectorLayerRenderer.cpp`. + Core objects are not thread-safe by default. The control serializes their use. ActiveX-specific implementation units are also compiled into `MapWinGIS.ActiveX.Impl.lib`, allowing native tests to exercise them without diff --git a/.github/plans/Vector-Rendering-Performance-Improvement.md b/.github/plans/Vector-Rendering-Performance-Improvement.md index ad7a8f3..ba5627b 100644 --- a/.github/plans/Vector-Rendering-Performance-Improvement.md +++ b/.github/plans/Vector-Rendering-Performance-Improvement.md @@ -22,8 +22,12 @@ Copilot: Update this checklist as each phase is implemented. Only mark a phase c - OpenGL lazy fill meshes are cached per stable layer ID and immutable scene identity, surviving viewport changes, layer reordering, temporary draws, visibility changes, and backend selection. - Scene replacement, explicit per-layer invalidation, removed-layer pruning, and clear-all invalidation release only the affected generated mesh storage; retained mesh bytes are tracked for tests. - Limitation: no cache-size limit or eviction policy was added because measurements did not establish that the additional complexity is justified. -- [ ] **Phase 5 – Introduce viewport-aware geometry processing** (PR 5) -- [ ] **Phase 6 – Optimize OpenGL rendering and data transfer** (PR 6) +- [x] **Phase 5 – Introduce viewport-aware geometry processing** (PR 5) +- [x] **Phase 6 – Optimize OpenGL rendering and data transfer** (PR 6) + - The screen OpenGL renderer caches immutable fill and outline geometry in vertex and index buffers per stable layer and scene, retaining a client-array fallback for systems without buffer objects. + - Viewport navigation reuses uploaded coordinates through a matrix transform; direct bottom-up DIB presentation removes the CPU row reversal, while the required `glReadPixels` transfer remains. + - On the generated 2,459-feature Release grid, steady, pan, and zoom frames measured 2.5 / 2.3 / 2.3 ms versus 2.7 / 2.6 / 2.6 ms before; eight readbacks measured 13.5 ms versus 18.3 ms. First-frame buffer and context setup remains noise-sensitive and did not improve. + - Limitation: the FBO-to-CPU readback remains required by the GDI presentation path, and temporary renderers own separate GPU buffers because OpenGL buffer names are context-local. - [ ] **Phase 7 – Testing and regression prevention** (PR 7) **Target branch:** `development` diff --git a/README.md b/README.md index 6194944..ff92c92 100644 --- a/README.md +++ b/README.md @@ -44,6 +44,9 @@ datasets or triangulating polygons again. OpenGL generates missing fill meshes on the first fill draw and caches them per stable map layer. Viewport changes, backend selection, layer reordering, and temporary draws reuse valid entries; changed or removed layers release or replace only their own meshes. +The screen OpenGL renderer uploads immutable fill and outline geometry to +reusable GPU buffers, then changes only its viewport transform on pan and zoom. +Systems without buffer-object support keep the client-array fallback. ## Build and test diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 800cdda..6bcd49a 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -351,19 +351,26 @@ mode draws the source rings without requiring fill meshes. GDI checks each layer before drawing it; a layer with non-finite or out-of-range device coordinates is skipped and reported (`GetFailedLayers`, `RenderingStatus`) while the other layers are still drawn. -OpenGL uses a context created on a hidden, never-presented window, draws with -fixed-function calls into a framebuffer object (OpenGL 3.0 or -`GL_EXT_framebuffer_object`), and reads pixels back in BGRA order into a CPU -buffer before copying them to the host device context. +OpenGL uses a context created on a hidden, never-presented window. When OpenGL +buffer objects are available (OpenGL 1.5 or `GL_ARB_vertex_buffer_object`), it +uploads each layer's immutable, scene-localized fill and outline coordinates +once to a reusable vertex buffer and indices to an element buffer. Pan and zoom +change the fixed-function model-view transform without rebuilding the source +coordinates. The client-side transformed-array path remains as a compatibility +fallback. Drawing uses a framebuffer object (OpenGL 3.0 or +`GL_EXT_framebuffer_object`) and reads pixels back in bottom-up BGRA order into +a CPU buffer before copying them to the host device context. BGRA stores blue, green, red, and alpha bytes in that order. The screen renderer retains its staging allocation and GPU framebuffer. Alternate-size draws use a temporary OpenGL renderer that releases both after the draw and shares the screen renderer's lazy fill meshes, leaving the screen -resources unchanged. -A separate vertex buffer is reused across polygons within each layer. -This avoids a fresh allocation for every polygon's transformed triangle vertices. +CPU, framebuffer, and geometry-buffer resources unchanged. Temporary renderers +use their own context-local GPU geometry buffers because OpenGL buffer names are +not portable between contexts. Rendering into a framebuffer object avoids undefined pixels from window -pixel-ownership rules. Presentation still copies pixels through GDI. +pixel-ownership rules. `SetDIBitsToDevice` consumes the bottom-up OpenGL scanlines +without a second CPU row-swap pass, so presentation still requires one readback +but not an additional full-frame copy. Interior rings and concave boundaries draw identically in both backends because both consume the same scene. A failed lazy triangulation, an unusable explicitly prepared mesh, missing framebuffer-object support, initialization @@ -498,7 +505,10 @@ 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. Replacing one layer scene invalidates only that layer's entry; removed layers -and explicit invalidation release their generated mesh storage. +and explicit invalidation release their generated mesh storage. A parallel +context-owned GPU buffer cache uses the same layer and scene identity. Scene +replacement, context recreation, and coordinator invalidation release or queue +the affected vertex and index buffers; viewport changes do not. When a driver cannot provide a fast extent, scene preparation computes bounds during the geometry traversal. It caches those bounds on the vector layer, so a later map fit does not scan the layer again. @@ -524,7 +534,8 @@ 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 polygons. OpenGL fills every polygon from a supplied or lazily generated -triangle mesh and copies each frame through CPU memory. Its reusable CPU +triangle mesh and copies each frame through CPU memory because the ActiveX +offscreen-DIB composition contract still presents through GDI. Its reusable CPU staging buffer is limited to 64 MiB per frame; target dimensions are also limited by the detected framebuffer and viewport capabilities. GDI is the supported Windows CPU fallback; Core has no independent platform-neutral renderer. diff --git a/docs/TESTING.md b/docs/TESTING.md index 595e164..29e2cf2 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -130,7 +130,8 @@ They cover whole-pixel cached pan draws, fractional and oversized offsets, failed-resize cache invalidation and redraw notifications, and screen-buffer preservation across scaled draws. Renderer tests cover BGRA color and row order, temporary staging buffers, -and context-initialization retry delays and resize-triggered retries. +reused GPU geometry buffers across pan, zoom, and render-mode changes, and +context-initialization retry delays and resize-triggered retries. Diagnostic conversion tests verify that malformed UTF-8 and embedded NULs are replaced instead of rejecting a completed operation's result. Its registered-control host test also sends a wheel zoom and captured drag to @@ -218,9 +219,10 @@ opening, layer metadata, OGR feature reads, internal geometry conversion, scene construction, GEOS validation, triangulation, OpenGL geometry submission, complete backend rendering, and `glReadPixels`. It also records feature/geometry counts, triangles, invalid and failed triangulations, -viewport skips, and scene-cache hits and misses. OpenGL currently submits -client-side transformed arrays with `glDrawElements`; there is no persistent -GPU buffer-upload stage to measure yet. +viewport skips, and scene-cache hits and misses. OpenGL records GPU-buffer +preparation and draw submission in the geometry-submission scope. On systems +with OpenGL 1.5 or the ARB buffer-object extension, unchanged source geometry +is uploaded once; other systems retain the client-array fallback. `RenderingBaseline.MeasuresComplexPolygonCosts` generates a second dataset — concave L-shaped polygons, holed rectangles where every feature is a @@ -309,6 +311,25 @@ The pre-triangulation measurements are retained for comparison: | OpenGL frame (median) | 10.0 ms | 82.3 ms | 80.5 ms | | Private memory, total | 91.7 MiB | 167.4 MiB | 167.2 MiB | +Phase 6 was measured again on the same developer workstation against the +`development` commit immediately before this phase, using a Release build and +the generated 2,459-feature grid: + +| OpenGL measurement | Before | Phase 6 | +|---|---:|---:| +| First frame (context + draw) | 158.8 ms | 161.3 ms | +| Steady frame (median) | 2.7 ms | 2.5 ms | +| Pan | 2.6 ms | 2.3 ms | +| Zoom | 2.6 ms | 2.3 ms | +| Eight framebuffer readbacks | 18.3 ms | 13.5 ms | + +The first-frame timings are noise-sensitive and include one-time context and +buffer setup. The Phase 6 geometry-submission scope covers the initial GPU +upload plus eight draws, so it is not directly comparable with the old +per-frame transformed client-array submission total. The frame still requires +`glReadPixels` because the control presents through GDI; this phase removes the +extra CPU scanline reversal, not the required GPU-to-CPU transfer. + Scene preparation reads geometries sequentially through OGR and copies their coordinates directly, avoiding indexed lookups, WKT serialization, and reparsing. The 100k-feature measurement dropped from 15,225 ms to 91.5 ms on diff --git a/src/MapWinGIS.ActiveX/OpenGlVectorLayerRenderer.cpp b/src/MapWinGIS.ActiveX/OpenGlVectorLayerRenderer.cpp index 3c53d60..28234d8 100644 --- a/src/MapWinGIS.ActiveX/OpenGlVectorLayerRenderer.cpp +++ b/src/MapWinGIS.ActiveX/OpenGlVectorLayerRenderer.cpp @@ -11,7 +11,9 @@ * rings and do not require meshes. Each polygon is drawn completely before * the next one, matching the GDI backend's painter order. Fill scenes whose * mesh preparation fails, or systems without framebuffer objects, return - * S_FALSE so the coordinator can use GDI. + * S_FALSE so the coordinator can use GDI. On systems that expose buffer + * objects, immutable source geometry is uploaded once and reused across + * viewport changes. */ #include "OpenGlVectorLayerRenderer.h" @@ -50,6 +52,9 @@ namespace mwg::activex constexpr std::size_t kMaxStagingBufferBytes = 64U * 1024U * 1024U; constexpr std::size_t kBytesPerPixel = 4; constexpr GLenum kBgra = 0x80E1; + constexpr GLenum kArrayBuffer = 0x8892; + constexpr GLenum kElementArrayBuffer = 0x8893; + constexpr GLenum kStaticDraw = 0x88E4; constexpr unsigned int kInitializationRetryDraws = 60; } @@ -115,6 +120,60 @@ namespace mwg::activex } }; + struct OpenGlVectorLayerRenderer::BufferFunctions final + { + using GenBuffers = void(APIENTRY*)(GLsizei, GLuint*); + using DeleteBuffers = void(APIENTRY*)(GLsizei, const GLuint*); + using BindBuffer = void(APIENTRY*)(GLenum, GLuint); + using BufferData = + void(APIENTRY*)(GLenum, std::ptrdiff_t, const void*, GLenum); + + GenBuffers genBuffers{}; + DeleteBuffers deleteBuffers{}; + BindBuffer bindBuffer{}; + BufferData bufferData{}; + + [[nodiscard]] bool Load() noexcept + { + return LoadSet("") || LoadSet("ARB"); + } + + private: + template + [[nodiscard]] static bool LoadFunction( + Function& function, + const char* name, + const char* suffix) noexcept + { + char fullName[64]{}; + const int written = + std::snprintf(fullName, sizeof(fullName), "%s%s", name, suffix); + if (written <= 0 || static_cast(written) >= sizeof(fullName)) + { + return false; + } + + const PROC address = wglGetProcAddress(fullName); + const auto value = reinterpret_cast(address); + if (value == 0 || value == 1 || value == 2 || value == 3 || value == -1) + { + function = nullptr; + return false; + } + + function = reinterpret_cast(address); + return true; + } + + [[nodiscard]] bool LoadSet(const char* suffix) noexcept + { + return LoadFunction(genBuffers, "glGenBuffers", suffix) && + LoadFunction(deleteBuffers, "glDeleteBuffers", suffix) && + LoadFunction(bindBuffer, "glBindBuffer", suffix) && + LoadFunction(bufferData, "glBufferData", suffix); + } + }; + namespace { class ScopedCurrentContext final @@ -379,6 +438,35 @@ namespace mwg::activex std::uint64_t nextPreparationToken = 0; }; + struct OpenGlVectorLayerRenderer::GpuBufferCache final + { + struct Ring final + { + GLint first = 0; + GLsizei count = 0; + }; + + struct Polygon final + { + rendering::Point origin; + GLsizei indexCount = 0; + std::size_t indexOffset = 0; + std::vector rings; + }; + + struct Layer final + { + std::weak_ptr scene; + GLuint vertexBuffer = 0; + GLuint indexBuffer = 0; + bool hasFill = false; + std::vector polygons; + }; + + std::map layers; + std::vector deletedBuffers; + }; + bool OpenGlVectorLayerRenderer::IsSceneSupported( const rendering::MapRenderScene& scene, const VectorRenderMode renderMode) noexcept @@ -544,6 +632,19 @@ namespace mwg::activex return false; } + try + { + _bufferFunctions = std::make_unique(); + if (!_bufferFunctions->Load()) + { + _bufferFunctions.reset(); + } + } + catch (const std::bad_alloc&) + { + _bufferFunctions.reset(); + } + while (glGetError() != GL_NO_ERROR) { } @@ -601,8 +702,10 @@ namespace mwg::activex void OpenGlVectorLayerRenderer::Release() noexcept { - // The context is not shared, so deleting it also frees the - // framebuffer and renderbuffer objects. + // The context is not shared, so deleting it also frees all framebuffer + // and geometry buffer objects. + _gpuBufferCache.reset(); + _bufferFunctions.reset(); _framebufferFunctions.reset(); _framebuffer = 0; _renderbuffer = 0; @@ -634,6 +737,426 @@ namespace mwg::activex } } + void OpenGlVectorLayerRenderer::FlushDeletedGpuBuffers() noexcept + { + if (_gpuBufferCache == nullptr || _bufferFunctions == nullptr || + _gpuBufferCache->deletedBuffers.empty()) + { + return; + } + + std::vector& buffers = _gpuBufferCache->deletedBuffers; + std::size_t offset = 0; + while (offset < buffers.size()) + { + const std::size_t count = + std::min( + buffers.size() - offset, + static_cast(std::numeric_limits::max())); + _bufferFunctions->deleteBuffers( + static_cast(count), + buffers.data() + offset); + offset += count; + } + buffers.clear(); + } + + void OpenGlVectorLayerRenderer::QueueDeletedGpuBuffer( + const unsigned int buffer) noexcept + { + if (buffer == 0 || _gpuBufferCache == nullptr) + { + return; + } + try + { + _gpuBufferCache->deletedBuffers.push_back(buffer); + } + catch (const std::bad_alloc&) + { + _contextInvalid = true; + } + } + + HRESULT OpenGlVectorLayerRenderer::DrawLayerWithGpuBuffers( + const LayerId layerId, + const std::shared_ptr& scene, + const std::span> fillMeshes, + const ViewTransform& transform, + const VectorRenderMode renderMode) noexcept + { + if (_bufferFunctions == nullptr) + { + return S_FALSE; + } + + try + { + if (_gpuBufferCache == nullptr) + { + _gpuBufferCache = std::make_unique(); + } + + auto cached = _gpuBufferCache->layers.find(layerId); + const bool needFill = renderMode == VectorRenderMode::Fill; + if (cached != _gpuBufferCache->layers.end() && + (cached->second.scene.lock() != scene || + (needFill && !cached->second.hasFill))) + { + QueueDeletedGpuBuffer(cached->second.vertexBuffer); + QueueDeletedGpuBuffer(cached->second.indexBuffer); + (void)_gpuBufferCache->layers.erase(cached); + cached = _gpuBufferCache->layers.end(); + FlushDeletedGpuBuffers(); + } + + if (cached == _gpuBufferCache->layers.end()) + { + GpuBufferCache::Layer prepared; + prepared.scene = scene; + prepared.hasFill = needFill; + + std::vector vertices; + std::vector indices; + std::size_t vertexCount = 0; + prepared.polygons.reserve(scene->polygons.size()); + for (std::size_t polygonIndex = 0; + polygonIndex < scene->polygons.size(); + ++polygonIndex) + { + GpuBufferCache::Polygon polygon; + const std::size_t meshVertexOffset = vertexCount; + const rendering::PolygonView rings = + scene->polygons[polygonIndex]; + for (std::size_t ringIndex = 0; + ringIndex < rings.size(); + ++ringIndex) + { + const std::span ring = + rings[ringIndex]; + if (!ring.empty()) + { + polygon.origin = ring.front(); + break; + } + } + if (needFill) + { + const rendering::TriangleMesh& mesh = + *fillMeshes[polygonIndex]; + if (mesh.vertices.size() > + static_cast( + std::numeric_limits::max()) - + vertexCount) + { + return E_OUTOFMEMORY; + } + if (mesh.indices.size() > + static_cast(std::numeric_limits::max())) + { + return E_OUTOFMEMORY; + } + polygon.indexOffset = indices.size(); + polygon.indexCount = static_cast(mesh.indices.size()); + for (const rendering::Point& point : mesh.vertices) + { + vertices.push_back(point.x - polygon.origin.x); + vertices.push_back(point.y - polygon.origin.y); + } + for (const std::uint32_t index : mesh.indices) + { + indices.push_back( + static_cast(meshVertexOffset) + index); + } + vertexCount += mesh.vertices.size(); + } + + polygon.rings.reserve(rings.size()); + for (std::size_t ringIndex = 0; + ringIndex < rings.size(); + ++ringIndex) + { + const std::span ring = rings[ringIndex]; + std::size_t count = ring.size(); + if (count > 1 && + ring.front().x == ring.back().x && + ring.front().y == ring.back().y) + { + --count; + } + if (count < 3) + { + continue; + } + if (count > + static_cast( + std::numeric_limits::max()) - + vertexCount || + count > + static_cast( + std::numeric_limits::max())) + { + return E_OUTOFMEMORY; + } + for (std::size_t index = 0; index < count; ++index) + { + vertices.push_back( + ring[index].x - polygon.origin.x); + vertices.push_back( + ring[index].y - polygon.origin.y); + } + polygon.rings.push_back({ + static_cast(vertexCount), + static_cast(count)}); + vertexCount += count; + } + prepared.polygons.push_back(std::move(polygon)); + } + + const std::size_t vertexBytes = + vertices.size() * sizeof(GLdouble); + const std::size_t indexBytes = + indices.size() * sizeof(std::uint32_t); + if (vertexBytes > + static_cast( + std::numeric_limits::max()) || + indexBytes > + static_cast( + std::numeric_limits::max())) + { + return E_OUTOFMEMORY; + } + + while (glGetError() != GL_NO_ERROR) + { + } + _bufferFunctions->genBuffers(1, &prepared.vertexBuffer); + _bufferFunctions->bindBuffer(kArrayBuffer, prepared.vertexBuffer); + _bufferFunctions->bufferData( + kArrayBuffer, + static_cast(vertexBytes), + vertices.data(), + kStaticDraw); + if (needFill) + { + _bufferFunctions->genBuffers(1, &prepared.indexBuffer); + _bufferFunctions->bindBuffer( + kElementArrayBuffer, + prepared.indexBuffer); + _bufferFunctions->bufferData( + kElementArrayBuffer, + static_cast(indexBytes), + indices.data(), + kStaticDraw); + } + const bool uploadFailed = glGetError() != GL_NO_ERROR || + prepared.vertexBuffer == 0 || + (needFill && prepared.indexBuffer == 0); + while (glGetError() != GL_NO_ERROR) + { + } + if (uploadFailed) + { + QueueDeletedGpuBuffer(prepared.vertexBuffer); + QueueDeletedGpuBuffer(prepared.indexBuffer); + FlushDeletedGpuBuffers(); + _bufferFunctions->bindBuffer(kArrayBuffer, 0); + _bufferFunctions->bindBuffer(kElementArrayBuffer, 0); + return S_FALSE; + } + + cached = _gpuBufferCache->layers.emplace( + layerId, std::move(prepared)).first; + ++_gpuBufferUploadCount; + } + + const diagnostics::PerformanceScope submissionScope( + diagnostics::PerformanceOperation::OpenGlGeometrySubmission); + const GpuBufferCache::Layer& layer = cached->second; + const double inverseResolution = 1.0 / transform.resolution; + + glEnableClientState(GL_VERTEX_ARRAY); + _bufferFunctions->bindBuffer(kArrayBuffer, layer.vertexBuffer); + glVertexPointer(2, GL_DOUBLE, 0, nullptr); + if (needFill) + { + _bufferFunctions->bindBuffer( + kElementArrayBuffer, + layer.indexBuffer); + } + for (const GpuBufferCache::Polygon& polygon : layer.polygons) + { + const double translateX = + transform.halfWidth + + (polygon.origin.x - transform.centerX) * inverseResolution; + const double translateY = + transform.halfHeight - + (polygon.origin.y - transform.centerY) * inverseResolution; + glMatrixMode(GL_MODELVIEW); + glLoadIdentity(); + glTranslated(translateX, translateY, 0.0); + glScaled(inverseResolution, -inverseResolution, 1.0); + + if (needFill) + { + glColor3ub(61, 122, 169); + glDrawElements( + GL_TRIANGLES, + polygon.indexCount, + GL_UNSIGNED_INT, + reinterpret_cast( + static_cast( + polygon.indexOffset * sizeof(std::uint32_t)))); + } + glColor3ub(24, 58, 82); + for (const GpuBufferCache::Ring& ring : polygon.rings) + { + glDrawArrays(GL_LINE_LOOP, ring.first, ring.count); + } + } + glDisableClientState(GL_VERTEX_ARRAY); + _bufferFunctions->bindBuffer(kArrayBuffer, 0); + _bufferFunctions->bindBuffer(kElementArrayBuffer, 0); + } + catch (const std::bad_alloc&) + { + _contextInvalid = true; + return E_OUTOFMEMORY; + } + catch (const std::length_error&) + { + _contextInvalid = true; + return E_OUTOFMEMORY; + } + return S_OK; + } + + bool OpenGlVectorLayerRenderer::PruneGpuBufferCache( + const rendering::MapRenderScene& scene) noexcept + { + const bool contextWasInvalid = _contextInvalid; + try + { + if (_gpuBufferCache == nullptr) + { + return true; + } + + std::map< + LayerId, + std::shared_ptr> drawableLayers; + std::set hiddenLayers; + for (const rendering::LayerRenderScene& layer : scene.layers) + { + drawableLayers.insert_or_assign(layer.layerId, layer.scene); + } + for (const rendering::SkippedLayer& layer : scene.skippedLayers) + { + if (layer.reason == rendering::LayerSkipReason::Hidden) + { + hiddenLayers.insert(layer.layerId); + } + } + + for (auto cached = _gpuBufferCache->layers.begin(); + cached != _gpuBufferCache->layers.end();) + { + const auto drawable = drawableLayers.find(cached->first); + if (drawable != drawableLayers.end()) + { + if (!cached->second.scene.expired() && + cached->second.scene.lock() == drawable->second) + { + ++cached; + continue; + } + } + else if (hiddenLayers.contains(cached->first) && + !cached->second.scene.expired()) + { + ++cached; + continue; + } + + QueueDeletedGpuBuffer(cached->second.vertexBuffer); + QueueDeletedGpuBuffer(cached->second.indexBuffer); + cached = _gpuBufferCache->layers.erase(cached); + } + } + catch (const std::bad_alloc&) + { + _lastFailureReason = + L"The OpenGL backend could not allocate its GPU-cache index."; + return false; + } + catch (const std::length_error&) + { + _lastFailureReason = + L"The OpenGL backend could not represent its GPU-cache index."; + return false; + } + return contextWasInvalid || !_contextInvalid; + } + + void OpenGlVectorLayerRenderer::ClearGpuBufferCache() noexcept + { + if (_gpuBufferCache == nullptr) + { + return; + } + for (const auto& [layerId, layer] : _gpuBufferCache->layers) + { + (void)layerId; + QueueDeletedGpuBuffer(layer.vertexBuffer); + QueueDeletedGpuBuffer(layer.indexBuffer); + } + _gpuBufferCache->layers.clear(); + const ScopedCurrentContext currentContext( + _deviceContext, _renderingContext); + if (currentContext.IsValid()) + { + FlushDeletedGpuBuffers(); + } + } + + void OpenGlVectorLayerRenderer::ClearLayerGpuBufferCache( + const LayerId layerId) noexcept + { + if (_gpuBufferCache == nullptr) + { + return; + } + const auto cached = _gpuBufferCache->layers.find(layerId); + if (cached == _gpuBufferCache->layers.end()) + { + return; + } + QueueDeletedGpuBuffer(cached->second.vertexBuffer); + QueueDeletedGpuBuffer(cached->second.indexBuffer); + (void)_gpuBufferCache->layers.erase(cached); + const ScopedCurrentContext currentContext( + _deviceContext, _renderingContext); + if (currentContext.IsValid()) + { + FlushDeletedGpuBuffers(); + } + } + + bool OpenGlVectorLayerRenderer::HasGpuBufferCache() const noexcept + { + return _gpuBufferCache != nullptr; + } + + std::size_t OpenGlVectorLayerRenderer::GpuBufferCacheSize() const noexcept + { + return _gpuBufferCache == nullptr ? 0U : _gpuBufferCache->layers.size(); + } + + std::size_t OpenGlVectorLayerRenderer::GpuBufferUploadCount() const noexcept + { + return _gpuBufferUploadCount; + } + OpenGlVectorLayerRenderer::TargetValidation OpenGlVectorLayerRenderer::ValidateTarget( const HDC deviceContext, @@ -886,6 +1409,24 @@ namespace mwg::activex bool OpenGlVectorLayerRenderer::PruneFillMeshCache( const rendering::MapRenderScene& scene) noexcept { + if (_gpuBufferCache != nullptr) + { + const ScopedCurrentContext currentContext( + _deviceContext, _renderingContext); + if (currentContext.IsValid()) + { + FlushDeletedGpuBuffers(); + } + if (!PruneGpuBufferCache(scene)) + { + return false; + } + if (currentContext.IsValid()) + { + FlushDeletedGpuBuffers(); + } + } + if (_fillMeshCache == nullptr) { return true; @@ -953,10 +1494,12 @@ namespace mwg::activex { if (_fillMeshCache == nullptr) { + ClearGpuBufferCache(); return; } _fillMeshCache->layers.clear(); ++_fillMeshCache->generation; + ClearGpuBufferCache(); } void OpenGlVectorLayerRenderer::ClearLayerFillMeshCache( @@ -964,9 +1507,11 @@ namespace mwg::activex { if (_fillMeshCache == nullptr) { + ClearLayerGpuBufferCache(layerId); return; } (void)_fillMeshCache->layers.erase(layerId); + ClearLayerGpuBufferCache(layerId); } std::size_t OpenGlVectorLayerRenderer::FillMeshCacheSize() const noexcept @@ -1045,6 +1590,13 @@ namespace mwg::activex return S_FALSE; } + if (_contextInvalid) + { + _lastFailureReason = + L"OpenGL could not retain its geometry-buffer invalidation state."; + return E_FAIL; + } + while (glGetError() != GL_NO_ERROR) { } @@ -1090,12 +1642,27 @@ namespace mwg::activex L"this frame was rendered with GDI."; return S_FALSE; } - const HRESULT layerResult = - DrawLayer( - *layer.scene, + HRESULT layerResult = S_FALSE; + if (_bufferFunctions != nullptr) + { + layerResult = DrawLayerWithGpuBuffers( + layer.layerId, + layer.scene, fillMeshes, *transform, renderMode); + } + if (layerResult == S_FALSE) + { + glMatrixMode(GL_MODELVIEW); + glLoadIdentity(); + layerResult = + DrawLayer( + *layer.scene, + fillMeshes, + *transform, + renderMode); + } if (FAILED(layerResult)) { _lastFailureReason = L"OpenGL could not allocate its vertex buffers."; @@ -1103,7 +1670,6 @@ namespace mwg::activex } } - glFlush(); glReadBuffer(kColorAttachment0); { const diagnostics::PerformanceScope readbackScope( @@ -1134,31 +1700,14 @@ namespace mwg::activex const RECT& bounds, const Target& target) noexcept { - for (std::size_t row = 0; row < target.pixelHeight / 2; ++row) - { - for (std::size_t column = 0; column < target.pixelWidth; ++column) - { - const std::size_t topPixel = - (row * target.pixelWidth + column) * kBytesPerPixel; - const std::size_t bottomPixel = - ((target.pixelHeight - row - 1) * target.pixelWidth + column) * - kBytesPerPixel; - for (std::size_t channel = 0; channel < kBytesPerPixel; ++channel) - { - std::swap( - _pixelBuffer[topPixel + channel], - _pixelBuffer[bottomPixel + channel]); - } - } - } - - // GL_BGRA matches the little-endian 32-bit BI_RGB DIB byte - // order; only the OpenGL bottom-up row order needs reversing. + // GL_BGRA matches the little-endian 32-bit BI_RGB DIB byte order. + // Positive BI_RGB height tells GDI that the first scanline is the + // bottom row, matching glReadPixels without a CPU row-copy pass. BITMAPINFO bitmapInfo{}; bitmapInfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); bitmapInfo.bmiHeader.biWidth = target.width; - bitmapInfo.bmiHeader.biHeight = -target.height; + bitmapInfo.bmiHeader.biHeight = target.height; bitmapInfo.bmiHeader.biPlanes = 1; bitmapInfo.bmiHeader.biBitCount = 32; bitmapInfo.bmiHeader.biCompression = BI_RGB; diff --git a/src/MapWinGIS.ActiveX/OpenGlVectorLayerRenderer.h b/src/MapWinGIS.ActiveX/OpenGlVectorLayerRenderer.h index 7e1848f..1a38c4b 100644 --- a/src/MapWinGIS.ActiveX/OpenGlVectorLayerRenderer.h +++ b/src/MapWinGIS.ActiveX/OpenGlVectorLayerRenderer.h @@ -5,8 +5,9 @@ * @brief Declares the WGL-backed polygon fill and outline renderer. * * The backend owns a reusable OpenGL context, created on a hidden window that - * is never presented, and renders into a framebuffer object before copying - * the pixels into the host device context. + * is never presented. Immutable scene geometry is cached in GPU buffers, then + * rendered into a framebuffer object before the required pixels are copied to + * the host device context. */ #pragma once @@ -28,6 +29,7 @@ namespace mwg::activex class OpenGlVectorLayerRendererTestAccess; class MapWinGISControlTestAccess; } + struct ViewTransform; class VectorLayerRenderer; class OpenGlVectorLayerRenderer final : public IVectorRenderBackend @@ -115,6 +117,21 @@ namespace mwg::activex [[nodiscard]] bool InitializeFramebuffer() noexcept; [[nodiscard]] bool ResizeFramebuffer(int width, int height) noexcept; void Release() noexcept; + void QueueDeletedGpuBuffer(unsigned int buffer) noexcept; + void FlushDeletedGpuBuffers() noexcept; + [[nodiscard]] HRESULT DrawLayerWithGpuBuffers( + LayerId layerId, + const std::shared_ptr& scene, + std::span> fillMeshes, + const ViewTransform& transform, + VectorRenderMode renderMode) noexcept; + [[nodiscard]] bool PruneGpuBufferCache( + const rendering::MapRenderScene& scene) noexcept; + void ClearGpuBufferCache() noexcept; + void ClearLayerGpuBufferCache(LayerId layerId) noexcept; + [[nodiscard]] bool HasGpuBufferCache() const noexcept; + [[nodiscard]] std::size_t GpuBufferCacheSize() const noexcept; + [[nodiscard]] std::size_t GpuBufferUploadCount() const noexcept; [[nodiscard]] TargetValidation ValidateTarget( HDC deviceContext, const RECT& bounds, @@ -150,6 +167,8 @@ namespace mwg::activex HDC _deviceContext{}; HGLRC _renderingContext{}; std::unique_ptr _framebufferFunctions; + struct BufferFunctions; + std::unique_ptr _bufferFunctions; unsigned int _framebuffer{}; unsigned int _renderbuffer{}; int _framebufferWidth{}; @@ -164,6 +183,9 @@ namespace mwg::activex std::vector _pixelBuffer; struct FillMeshCache; std::shared_ptr _fillMeshCache; + struct GpuBufferCache; + std::unique_ptr _gpuBufferCache; + std::size_t _gpuBufferUploadCount = 0; int _retryTargetWidth = 0; int _retryTargetHeight = 0; unsigned int _initializationRetryDrawsRemaining = 0; diff --git a/tests/MapWinGIS.ActiveX.Tests/OpenGlVectorLayerRendererTestAccess.h b/tests/MapWinGIS.ActiveX.Tests/OpenGlVectorLayerRendererTestAccess.h index d30c186..f3e30bb 100644 --- a/tests/MapWinGIS.ActiveX.Tests/OpenGlVectorLayerRendererTestAccess.h +++ b/tests/MapWinGIS.ActiveX.Tests/OpenGlVectorLayerRendererTestAccess.h @@ -48,6 +48,24 @@ namespace mwg::activex::testing renderer.SimulateContextLoss(); } + [[nodiscard]] static bool HasGpuBufferCache( + const OpenGlVectorLayerRenderer& renderer) noexcept + { + return renderer.HasGpuBufferCache(); + } + + [[nodiscard]] static std::size_t GpuBufferCacheSize( + const OpenGlVectorLayerRenderer& renderer) noexcept + { + return renderer.GpuBufferCacheSize(); + } + + [[nodiscard]] static std::size_t GpuBufferUploadCount( + const OpenGlVectorLayerRenderer& renderer) noexcept + { + return renderer.GpuBufferUploadCount(); + } + /// Checks scene support without activating an OpenGL context. [[nodiscard]] static bool IsSceneSupported( const rendering::MapRenderScene& scene, @@ -86,5 +104,18 @@ namespace mwg::activex::testing { renderer.ClearLayerFillMeshCache(layerId); } + + static void InvalidateSceneCache( + OpenGlVectorLayerRenderer& renderer) noexcept + { + renderer.ClearFillMeshCache(); + } + + [[nodiscard]] static bool PruneCaches( + OpenGlVectorLayerRenderer& renderer, + const rendering::MapRenderScene& scene) noexcept + { + return renderer.PruneFillMeshCache(scene); + } }; } diff --git a/tests/MapWinGIS.ActiveX.Tests/VectorLayerRendererTests.cpp b/tests/MapWinGIS.ActiveX.Tests/VectorLayerRendererTests.cpp index b306cad..f4c20e2 100644 --- a/tests/MapWinGIS.ActiveX.Tests/VectorLayerRendererTests.cpp +++ b/tests/MapWinGIS.ActiveX.Tests/VectorLayerRendererTests.cpp @@ -1817,6 +1817,162 @@ TEST(VectorLayerRenderer, AlternateSizeDrawPreservesScreenStaging) ExpectTwoLayerPixels(surface.Get(), screenViewport); } +TEST(VectorLayerRenderer, OpenGlReusesGpuBuffersAcrossViewportAndModeChanges) +{ + using Access = mwg::activex::testing::OpenGlVectorLayerRendererTestAccess; + BitmapSurface surface(120, 100); + ASSERT_TRUE(surface.IsValid()); + mwg::rendering::MapRenderScene scene = MakeTwoLayerScene(); + const RECT bounds{0, 0, 120, 100}; + mwg::Viewport viewport = FitViewport(bounds, kTwoLayerExtent); + mwg::activex::OpenGlVectorLayerRenderer renderer; + + const HRESULT first = renderer.Draw(surface.Get(), bounds, scene, viewport); + if (first == S_FALSE) + { + GTEST_SKIP() << "No OpenGL context with framebuffer objects is available."; + } + ASSERT_EQ(first, S_OK); + if (!Access::HasGpuBufferCache(renderer)) + { + GTEST_SKIP() << "OpenGL buffer objects are unavailable."; + } + EXPECT_EQ(Access::GpuBufferCacheSize(renderer), 2U); + const std::size_t uploads = Access::GpuBufferUploadCount(renderer); + ASSERT_EQ(uploads, 2U); + + ASSERT_TRUE(viewport.ZoomOut(2.0)); + ASSERT_EQ(renderer.Draw(surface.Get(), bounds, scene, viewport), S_OK); + EXPECT_EQ(Access::GpuBufferUploadCount(renderer), uploads); + ExpectTwoLayerPixels(surface.Get(), viewport); + ASSERT_TRUE(viewport.Zoom(2.0)); + ASSERT_EQ(renderer.Draw(surface.Get(), bounds, scene, viewport), S_OK); + EXPECT_EQ(Access::GpuBufferUploadCount(renderer), uploads); + ExpectTwoLayerPixels(surface.Get(), viewport); + + ASSERT_TRUE(viewport.Pan(0.5, -0.25)); + ASSERT_EQ(renderer.Draw(surface.Get(), bounds, scene, viewport), S_OK); + ASSERT_EQ( + renderer.Draw( + surface.Get(), + bounds, + scene, + viewport, + true, + mwg::activex::VectorRenderMode::Outline), + S_OK); + EXPECT_EQ(Access::GpuBufferCacheSize(renderer), 2U); + EXPECT_EQ(Access::GpuBufferUploadCount(renderer), uploads); + + (void)Edit(scene.layers.front()); + ASSERT_EQ(renderer.Draw(surface.Get(), bounds, scene, viewport), S_OK); + EXPECT_EQ(Access::GpuBufferCacheSize(renderer), 2U); + EXPECT_EQ(Access::GpuBufferUploadCount(renderer), uploads + 1); + ExpectTwoLayerPixels(surface.Get(), viewport); + + Access::InvalidateLayerSceneCache(renderer, scene.layers.front().layerId); + EXPECT_EQ(Access::GpuBufferCacheSize(renderer), 1U); + ASSERT_EQ(renderer.Draw(surface.Get(), bounds, scene, viewport), S_OK); + EXPECT_EQ(Access::GpuBufferCacheSize(renderer), 2U); + EXPECT_EQ(Access::GpuBufferUploadCount(renderer), uploads + 2); + ExpectTwoLayerPixels(surface.Get(), viewport); + + Access::InvalidateSceneCache(renderer); + EXPECT_EQ(Access::GpuBufferCacheSize(renderer), 0U); + ASSERT_EQ(renderer.Draw(surface.Get(), bounds, scene, viewport), S_OK); + EXPECT_EQ(Access::GpuBufferCacheSize(renderer), 2U); + EXPECT_EQ(Access::GpuBufferUploadCount(renderer), uploads + 4); + ExpectTwoLayerPixels(surface.Get(), viewport); + + scene.layers.pop_back(); + ASSERT_TRUE(Access::PruneCaches(renderer, scene)); + EXPECT_EQ(Access::GpuBufferCacheSize(renderer), 1U); +} + +TEST(VectorLayerRenderer, OpenGlReuploadsEveryLayerForFillModeUpgrade) +{ + using Access = mwg::activex::testing::OpenGlVectorLayerRendererTestAccess; + BitmapSurface surface(120, 100); + ASSERT_TRUE(surface.IsValid()); + const auto scene = MakeTwoLayerScene(); + const RECT bounds{0, 0, 120, 100}; + const auto viewport = FitViewport(bounds, kTwoLayerExtent); + mwg::activex::OpenGlVectorLayerRenderer renderer; + + const HRESULT outline = renderer.Draw( + surface.Get(), + bounds, + scene, + viewport, + true, + mwg::activex::VectorRenderMode::Outline); + if (outline == S_FALSE) + { + GTEST_SKIP() << "No OpenGL context with framebuffer objects is available."; + } + ASSERT_EQ(outline, S_OK); + if (!Access::HasGpuBufferCache(renderer)) + { + GTEST_SKIP() << "OpenGL buffer objects are unavailable."; + } + const std::size_t uploads = Access::GpuBufferUploadCount(renderer); + ASSERT_EQ(Access::GpuBufferCacheSize(renderer), 2U); + ASSERT_EQ(uploads, 2U); + + ASSERT_EQ(renderer.Draw(surface.Get(), bounds, scene, viewport), S_OK); + EXPECT_EQ(Access::GpuBufferCacheSize(renderer), 2U); + EXPECT_EQ(Access::GpuBufferUploadCount(renderer), uploads + 2); + ExpectTwoLayerPixels(surface.Get(), viewport); +} + +TEST(VectorLayerRenderer, OpenGlPreservesPolygonPrecisionFarFromLayerOrigin) +{ + using Access = mwg::activex::testing::OpenGlVectorLayerRendererTestAccess; + BitmapSurface surface(120, 100); + ASSERT_TRUE(surface.IsValid()); + mwg::rendering::VectorRenderScene layer; + layer.extent = {-2e-5, -2e-5, 1e12 + 2.0, 1e12 + 2.0}; + layer.sourceFeatureCount = 2; + layer.polygons = { + {{{1e12, 1e12}, + {1e12 + 2.0, 1e12}, + {1e12 + 2.0, 1e12 + 2.0}, + {1e12, 1e12 + 2.0}, + {1e12, 1e12}}}, + {{{-2e-5, -2e-5}, + {2e-5, -2e-5}, + {2e-5, 2e-5}, + {-2e-5, 2e-5}, + {-2e-5, -2e-5}}}}; + const auto scene = MakeMapScene({std::move(layer)}); + const RECT bounds{0, 0, 120, 100}; + const mwg::Extent visibleExtent{-4e-5, -4e-5, 4e-5, 4e-5}; + const auto viewport = FitViewport(bounds, visibleExtent); + mwg::activex::OpenGlVectorLayerRenderer renderer; + + const HRESULT outline = renderer.Draw( + surface.Get(), + bounds, + scene, + viewport, + true, + mwg::activex::VectorRenderMode::Outline); + if (outline == S_FALSE) + { + GTEST_SKIP() << "No OpenGL context with framebuffer objects is available."; + } + ASSERT_EQ(outline, S_OK); + if (!Access::HasGpuBufferCache(renderer)) + { + GTEST_SKIP() << "OpenGL buffer objects are unavailable."; + } + constexpr COLORREF kOutline = RGB(24, 58, 82); + EXPECT_GT(CountPixels(surface.Get(), bounds, kOutline), 20U); + + ASSERT_EQ(renderer.Draw(surface.Get(), bounds, scene, viewport), S_OK); + EXPECT_EQ(MapPixel(surface.Get(), viewport, 0.0, 0.0), kFill); +} + TEST(VectorLayerRenderer, FailedContextRecoveryBacksOffAndRetriesAfterTheDelayOrResize) { using Access = mwg::activex::testing::OpenGlVectorLayerRendererTestAccess;