From 3cfcde2ac0ee0a6973fa21a7f21f77e1ecf4253d Mon Sep 17 00:00:00 2001 From: Paul Meems Date: Wed, 28 Oct 2026 08:46:43 +0100 Subject: [PATCH 1/2] Add MSBuild compilation database config Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .gitignore | 3 +++ msbuild-extractor.json | 6 ++++++ 2 files changed, 9 insertions(+) create mode 100644 msbuild-extractor.json diff --git a/.gitignore b/.gitignore index 2753665..1f51f99 100644 --- a/.gitignore +++ b/.gitignore @@ -430,3 +430,6 @@ FodyWeavers.xsd # vcpkg installed libraries vcpkg_installed/ + +# C++ language server compilation database +.mscppls/ diff --git a/msbuild-extractor.json b/msbuild-extractor.json new file mode 100644 index 0000000..b9dfe7d --- /dev/null +++ b/msbuild-extractor.json @@ -0,0 +1,6 @@ +{ + "solutions": ["MapWinGIS6.slnx"], + "configuration": "Debug", + "platform": "x64", + "output": ".mscppls\\compile_commands.json" +} From 8248ee0f8d0bb701866bf25912a1af66c608dbf9 Mon Sep 17 00:00:00 2001 From: Paul Meems Date: Wed, 28 Oct 2026 14:26:06 +0100 Subject: [PATCH 2/2] Merge conficts --- .github/copilot-instructions.md | 38 +- AGENTS.md | 28 +- README.md | 13 +- docs/ARCHITECTURE.md | 99 ++- docs/PORTING.md | 71 +- docs/TESTING.md | 19 + samples/CSharp/ActiveXTestHost/MainForm.cs | 51 +- .../GdiVectorLayerRenderer.cpp | 273 +++++++ .../GdiVectorLayerRenderer.h | 24 + src/MapWinGIS.ActiveX/MapWinGIS.ActiveX.idl | 26 +- .../MapWinGIS.ActiveX.vcxproj | 5 + src/MapWinGIS.ActiveX/MapWinGISControl.cpp | 104 ++- src/MapWinGIS.ActiveX/MapWinGISControl.h | 15 +- .../OpenGlVectorLayerRenderer.cpp | 768 ++++++++++++++++++ .../OpenGlVectorLayerRenderer.h | 88 ++ src/MapWinGIS.ActiveX/VectorLayerRenderer.cpp | 212 +---- src/MapWinGIS.ActiveX/VectorLayerRenderer.h | 52 +- src/MapWinGIS.ActiveX/VectorRenderBackend.h | 42 + .../src/vector/VectorDataset.cpp | 11 +- .../ActiveXActivationTests.cpp | 43 +- .../MapWinGIS.Core.Tests.vcxproj | 6 +- .../VectorLayerRendererTests.cpp | 259 ++++++ 22 files changed, 1935 insertions(+), 312 deletions(-) create mode 100644 src/MapWinGIS.ActiveX/GdiVectorLayerRenderer.cpp create mode 100644 src/MapWinGIS.ActiveX/GdiVectorLayerRenderer.h create mode 100644 src/MapWinGIS.ActiveX/OpenGlVectorLayerRenderer.cpp create mode 100644 src/MapWinGIS.ActiveX/OpenGlVectorLayerRenderer.h create mode 100644 src/MapWinGIS.ActiveX/VectorRenderBackend.h create mode 100644 tests/MapWinGIS.Core.Tests/VectorLayerRendererTests.cpp diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index cefaadb..3d0a4dc 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -6,8 +6,8 @@ Follow [AGENTS.md](../AGENTS.md) and the detailed standards linked there. They take precedence over the general guidance below. `MapWinGIS.Core` is a C++20 DLL. It must not use COM, ATL, or MFC. -The ActiveX wrapper is not implemented yet. COM/ActiveX guidance below -applies only to that future wrapper and to preserving the MapWinGIS 5 contract. +The ActiveX wrapper has an initial implementation. COM/ActiveX guidance below +applies to the implemented subset and any future compatibility work. ## Project Context @@ -60,21 +60,23 @@ Use `CoreError` subclasses for operational failures. Use `TryX` companions when failure is a normal probe result. Use `std::optional` for absent values, not for operational failures. -When porting behavior, use MapWinGIS 5 as the behavioral reference. Keep -feature indexes 0-based and preserve numeric values for matching type-library -enums. Preserve legacy value formatting and error information unless a change -is deliberate and documented. +Use MapWinGIS 5 to understand established behavior, but optimize the v6 +structure and APIs first. Backward compatibility is desirable only where it +fits the new design without undue complexity or limiting meaningful improvements. +Document intentional behavior/API differences and their rationale. Keep +compatibility at the appropriate boundary rather than importing legacy +architecture into the core. When working in this repository, prioritize: -* Correctness and preservation of existing MapWinGIS behavior. -* API and backwards compatibility where applicable. -* Clear, maintainable modern C++. -* Small, focused changes. -* Understanding existing code before changing it. -* Avoiding unnecessary changes outside the requested scope. +* Clear, maintainable, performant modern C++ and a sound architecture. +* Correctness and tests for the intended v6 behavior. +* Selective, explicitly considered backward compatibility. +* Small, focused changes with evidence for the chosen design. +* Understanding related code before changing it. +* Avoiding unrelated changes outside the requested scope. -Do not assume that a modernization task is an opportunity to redesign unrelated functionality. +Do not redesign unrelated functionality, but do not preserve a poor design solely for compatibility. --- @@ -85,7 +87,7 @@ Before changing code: 1. Understand the responsibility of the relevant class, component, or subsystem. 2. Inspect related declarations, implementations, and call sites when necessary. 3. Consider whether the code is part of the public COM/ActiveX API. -4. Preserve existing behavior unless the task explicitly requests a behavioral change. +4. Preserve existing behavior when it fits the v6 design and requirements; do not treat legacy behavior as immutable when modernization justifies a deliberate, documented change. 5. Identify compatibility implications before changing public APIs. When making changes: @@ -314,8 +316,8 @@ MapWinGIS exposes a long-lived COM/ActiveX API. When modifying code that is part of the public API: -* Treat compatibility as an important consideration. -* Avoid changing public interfaces without an explicit requirement. +* Consider compatibility, but do not let it dictate the internal architecture. +* Avoid accidental public-interface changes; deliberate design improvements may justify a documented API difference. * Be careful with COM-visible types, interfaces, methods, properties, enums, DISPIDs, and related contracts. * Consider existing external applications that may depend on legacy behavior. * Document compatibility constraints when they are important to understanding the implementation. @@ -349,9 +351,9 @@ However: * Do not introduce abstractions without a clear benefit. * Do not change behavior unintentionally. * Consider COM/ActiveX ownership and lifetime semantics carefully before replacing existing pointer-based patterns. -* Consider ABI/API compatibility before changing public types or interfaces. +* Consider ABI/API compatibility, while prioritizing a sound v6 design over legacy parity when the two conflict. -When migrating a legacy component, preserve externally observable behavior unless the modernization task explicitly calls for a change. +When migrating a legacy component, preserve externally observable behavior when it fits the v6 design. If compatibility would impose undue complexity or block a worthwhile improvement, prefer the better design and document the difference. --- diff --git a/AGENTS.md b/AGENTS.md index d0ef67e..01461a0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -18,12 +18,16 @@ ActiveX GIS control — as modern C++: - **`MapWinGIS.Core.dll`** — the mapping engine as a plain C++ DLL. No COM, ATL or MFC. Usable and testable on its own. -- **`MapWinGIS.ocx`** — a thin ActiveX/COM wrapper over the core that keeps - the MapWinGIS 5 API. Not started yet. +- **`MapWinGIS.ocx`** — a thin ActiveX/COM wrapper over the core. The initial + vertical slice supports COM activation, control lifecycle, vector loading, and + basic polygon rendering; broader MapWinGIS 5 API compatibility remains future + work. -[MapWinGIS 5](https://github.com/MapWindow/MapWinGIS) is the reference -implementation and the behavioral ground truth. Port its functionality; do -not transliterate its code. +[MapWinGIS 5](https://github.com/MapWindow/MapWinGIS) is a reference for +functionality and established behavior, not a constraint on the new architecture. +Optimize the structure and API for a maintainable modern version first; preserve +backward compatibility second, where it fits that design without imposing undue +complexity or limiting improvements. Do not transliterate the legacy code. ## Repository layout @@ -51,12 +55,14 @@ and switches: [docs/BUILDING.md](docs/BUILDING.md). 1. **Modernize, don't transliterate.** MapWinGIS 5 code is a behavior reference. Rewrite it as clean C++20 in the style already in this tree. 2. **Core stays pure.** No COM, ATL or MFC in `MapWinGIS.Core`; COM concerns - belong to the future ActiveX layer. -3. **Match existing conventions.** SPDX header, Doxygen file block, `mwg` - namespace, PImpl classes, `[[nodiscard]]`, exceptions with `TryX` - companions. Full list: [docs/CODING-STANDARDS.md](docs/CODING-STANDARDS.md). -4. **Preserve the MapWinGIS 5 contract.** 0-based feature indexes, enum - values pinned to the v5 type library, error semantics. + belong to the ActiveX layer. +3. **Modernize the structure first.** Prefer a clean, maintainable C++20 design + over matching the legacy architecture or signatures. Compatibility is a + secondary goal and must not burden the new design. +4. **Preserve compatibility selectively and deliberately.** Keep established + behavior when it is valuable and fits the design; document intentional + differences. Treat 0-based indexes, legacy enum values, and error semantics + as compatibility requirements only where the relevant API contract needs them. See [docs/PORTING.md](docs/PORTING.md). 5. **Tests with every feature.** GoogleTest with generated fixtures via `TestData.h`. Conventions: [docs/TESTING.md](docs/TESTING.md). diff --git a/README.md b/README.md index ba694d3..3006e5e 100644 --- a/README.md +++ b/README.md @@ -8,19 +8,20 @@ splits that into two layers: - **`MapWinGIS.Core.dll`** — the mapping engine as a normal C++ DLL, with no COM, ATL or MFC. It can be used and tested on its own. -- **`MapWinGIS.ocx`** — a thin ActiveX/COM wrapper over the core, keeping the - existing API so that current C#, VB.NET, WPF, Delphi and VB6 applications - keep working. +- **`MapWinGIS.ocx`** — a thin ActiveX/COM wrapper over the core, exposing + selected legacy API compatibility where it fits the v6 design. -MapWinGIS 5.x stays available and remains the reference implementation during -the migration. +MapWinGIS 5.x remains available as a behavioral reference. MapWinGIS6 prioritizes +a clean, maintainable modern architecture; backward compatibility is pursued +selectively and must not prevent structural improvements. ## Status Early. The core currently includes GDAL setup and OGR-backed vector dataset and layer access, including feature and field reading and updates. Available formats depend on the GDAL drivers enabled in the build; tests cover shapefiles -and GeoPackage. The ActiveX layer has not been added yet. +and GeoPackage. The ActiveX layer supports an initial slice of COM activation, +control lifecycle, vector loading, and basic polygon rendering. ## Build and test diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 8410612..b24ea62 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -105,39 +105,56 @@ these responsibilities do not require separate DLLs. |---|---|---| | `MapWinGIS.Core` | Own GIS data, reusable map/layer state, and backend-neutral render data. Keep its public API independent of windowing, COM, and graphics APIs. | COM, ATL, MFC, windowing APIs, OpenGL, OpenCL | | `MapWinGIS.ocx` | Own COM activation, host-facing control lifecycle, and translation between the external API and core operations. Integrate core rendering with the host surface and selected backend. | GIS rules, core data ownership, rendering-specific types in its public COM contract | -| Rendering coordinator (initially internal to the OCX) | Bind core render requests to the control's target; select a backend and coordinate host-specific drawing and recovery. Keep this native component independent of COM activation. | GIS rules, COM interface layout, backend-specific resource types outside the backend | -| Initial GDI renderer (in the OCX) | Paint backend-neutral polygon scenes into the host drawing context. This is a first visible-map path, not the planned interchangeable backend abstraction. | Core dataset ownership, COM interface layout | -| Future CPU backend (in Core) | Provide the supported rendering path when GPU rendering is unavailable or disabled. | GPU or OpenCL availability | -| OpenGL backend (in the OCX) | Provide optional accelerated drawing and own its context and GPU resources. | Core GIS data ownership and public COM interfaces | +| Rendering coordinator (in the OCX) | Try OpenGL for supported scenes and use GDI when OpenGL is unavailable or the scene is unsupported. Keep backend selection independent of COM activation. | GIS rules, COM interface layout, backend-specific resource types outside the backend | +| GDI backend (in the OCX) | Paint all currently supported polygon scene geometry, including interior rings, into a device context. | Core dataset ownership, COM interface layout, GPU availability | +| OpenGL backend (in the OCX) | Render convex single-ring polygons through a reusable WGL context, then copy pixels to the host device context. | Core GIS data ownership and public COM interfaces | +| Future CPU backend (in Core) | Provide a platform-independent rendering path if later justified by other clients. | GPU or OpenCL availability | | Future compute work | Host optional compute acceleration only for workloads justified by profiling. | OpenGL being installed or selected | -The OCX is the initial composition root for control and host-specific graphics -context lifetimes. The control owns its core-side map/session object; that -object owns open dataset handles, and each `VectorDataset` owns its -`VectorLayer` objects. Core creates backend-neutral render input from map -state; the coordinator binds it to the current control target and backend. -Backends must not retain pointers or references to dataset-owned objects after -a draw. Core dataset and layer objects are not thread-safe, so the initial -control must serialize their use. Backend-specific contexts, buffers, and -other GPU resources belong to the OpenGL backend and are released when that -backend or its control surface is destroyed. Resizing updates the render -target and viewport without changing ownership of the map data. +The OCX is the composition root for control, render-coordinator, and +host-specific graphics-context lifetimes. The control owns its core-side +map/session object; that object owns open dataset handles, and each +`VectorDataset` owns its `VectorLayer` objects. Core creates backend-neutral +render input from map state; the coordinator binds it to the current control +target and backend. Backends must not retain pointers or references to +dataset-owned objects after a draw. Core dataset and layer objects are not +thread-safe, so the initial control must serialize their use. The OpenGL +backend owns its WGL context and reusable pixel buffers; those resources are +released with the control. Resizing updates the OpenGL viewport and staging +buffers without changing ownership of map data. Rendering consumes backend-neutral input prepared from core data; neither the -coordinator nor a backend loads datasets or implements GIS rules. Core now +coordinator nor a backend loads datasets or implements GIS rules. Core converts Polygon and MultiPolygon features into an owned vector scene. The -initial OCX GDI painter consumes that scene without retaining layer-owned -objects. This vertical slice renders source coordinates directly and does not -reproject data. Scene preparation currently supports polygon layers only. - -Backend choice is internal to the rendering coordinator and is observable -through diagnostics, not through a graphics-specific COM API. A caller or -test can request CPU rendering; otherwise the coordinator may try OpenGL when -the target supports it. It must use runtime capability and initialization -results, not GPU vendor or presence alone. If OpenGL cannot initialize or -loses its context, release its resources, record the reason, and select the -CPU backend. Switching backends must not discard map state. The CPU backend -remains usable without a GPU, OpenGL, or OpenCL runtime. +coordinator tries the OpenGL backend for simple convex polygons with one ring. +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 into a reusable CPU buffer +before copying them to the host device context; this is a working backend +boundary, not an end-to-end accelerated presentation path. Rendering into a +framebuffer object avoids undefined pixels from window pixel-ownership rules. +Interior rings, concave or self-intersecting rings, missing framebuffer-object +support, initialization failures, and drawing failures use the GDI +backend. The GDI backend can draw the scene's existing polygon and interior +ring structure. Both backends render source coordinates directly without +reprojection, and scene preparation currently supports polygon layers only. + +The `RenderingBackendPreference` automation property is configurable as +`Automatic`, `OpenGL`, or `GDI`. `Automatic` and `OpenGL` try the OpenGL +backend first and fall back to GDI when the scene, hardware, allocation, or +drawing operation is unsupported. The control reports the active backend and +the reason for a fallback through `RenderingBackend` and `RenderingStatus`. +These rendering properties are on `IMapWinGISControl2`, the coclass default +interface, which derives from `IMapWinGISControl`; the original interface and +its IID are left unchanged so clients built against it keep working. +OpenGL capability detection checks framebuffer-object entry points, the +maximum renderbuffer size, and the maximum viewport dimensions at runtime; +targets exceeding either limit use GDI. CPU staging for OpenGL readback is +limited to one 64 MiB buffer per frame, including retained capacity and +reallocation peaks; larger targets use GDI instead. A failed rendering context +is recreated on later draws until a replacement initializes successfully. Switching backends does not +discard map state. The GDI backend remains usable without a GPU or OpenGL +runtime; Core itself has no graphics-runtime dependency. Test core scene preparation and CPU drawing through the core with deterministic input and output. Test the native OCX coordinator without COM activation by @@ -146,14 +163,16 @@ verify backend selection and failure recovery there. OpenGL-specific integration checks may require a real context, but they must not be required for core or CPU-rendering tests. -At the COM boundary, preserve established MapWinGIS behavior where it is -intentionally implemented, including the existing 0-based feature-index -contract and error translation. Before implementing a legacy interface, -inspect its type-library identifiers and signatures; retain identifiers only -for compatible interfaces. Full legacy API parity, the historical MFC/ATL -class hierarchy and rendering pipeline, and OpenCL integration are deferred. -Document intentional compatibility gaps as the corresponding interfaces are -introduced. +Design the v6 architecture and APIs for clarity, maintainability, and +performance first; backward compatibility is secondary and must not force the +new version to reproduce legacy structure. At the COM boundary, preserve +selected established behaviors where they fit the supported compatibility +surface, including 0-based feature indexes where required and appropriate error +translation. Before implementing a legacy interface, inspect its type-library +identifiers and signatures; retain identifiers only when the interface is +actually compatible. Full legacy API parity, the historical MFC/ATL class +hierarchy and rendering pipeline, and OpenCL integration are deferred. Document +intentional compatibility gaps and the rationale when interfaces are introduced. ## Current state @@ -161,6 +180,8 @@ The tree is early: GDAL environment setup and vector reading/editing (`VectorDataset`, `VectorLayer`, backed by OGR) are the first core slices. The OCX supports COM activation and the ATL resize/paint lifecycle. It can load the first polygon layer from a vector dataset through Core and display -its geometry with a simple GDI painter. An interchangeable rendering -abstraction, CPU fallback backend, backend selection, and OpenGL remain -unimplemented. +its geometry through an internal OpenGL/GDI renderer boundary. OpenGL is +limited to convex single-ring polygons and currently incurs a full pixel +readback before presentation; all other supported polygon scenes use GDI. +Explicit hardware capability detection, configurable backend selection, +context-loss recovery, and performance/resource policies remain for Phase 6. diff --git a/docs/PORTING.md b/docs/PORTING.md index ee45773..aa2dd11 100644 --- a/docs/PORTING.md +++ b/docs/PORTING.md @@ -1,41 +1,50 @@ # Porting from MapWinGIS 5 -[MapWinGIS 5](https://github.com/MapWindow/MapWinGIS) is a single large -MFC/ATL project (the `CMapView` control plus COM classes, with the type -library in `MapWinGIS.odl`). It is the **reference implementation**: when -re-creating a feature, its behavior is the specification. The goal is a -modern rewrite, not a line-by-line translation. +[MapWinGIS 5](https://github.com/MapWindow/MapWinGIS) is a large MFC/ATL +project (the `CMapView` control plus COM classes, with the type library in +`MapWinGIS.odl`). It is a source of behavioral knowledge, not the blueprint +for the new architecture. + +**Design priority: optimize the new version first, preserve backward +compatibility second.** Build clean modern APIs and architecture around the +actual needs of MapWinGIS6. Retain legacy behavior or API compatibility when it +provides value and fits the design; do not add complexity, preserve flawed +structures, or constrain improvements solely for parity. Where compatibility +is intentionally not retained, document the difference and rationale. For GDAL-specific migration guidance, see [GDAL migration](gdal-migration.md). ## What "port" means here -1. **Study the v5 behavior.** Read the v5 sources for the feature: what the - public API accepts and returns, edge cases, error behavior, units, - coordinate order and defaults. -2. **Design the core API first.** Express it with the current conventions - (PImpl class in `include/mapwingis//`, `std::optional`, exceptions - with `TryX` companions). Resist mirroring v5 class hierarchies and COM - signatures. -3. **Implement in the core and test against the spec.** Add GoogleTest - coverage for the ported behavior, including edge cases and failures. -4. **Leave COM mapping to the ActiveX layer.** Later, the wrapper maps core - types and exceptions onto the v5 COM API and error codes. - -## Behavioral contract to preserve - -The ActiveX layer will be a mechanical translation, so the core must keep the -following true: - -- **Feature/shape indexes are 0-based** and match v5 shape indexes exactly. -- **Enums that correspond to v5 type-library enums keep identical numeric - values** (see `ShapeType`/`FieldType` in `mapwingis/core/Enums.h`). Add the - same pinning note to every new ported enum. -- **Error semantics**: v5 reports failures via error codes and - `LastErrorMessage`-style state; the core throws or returns - `std::optional`, with the same information in the exception message. -- **Formatting**: where v5 formats values for display (e.g. `CellValue` - text), the core keeps the same textual output. +1. **Understand the legacy behavior.** Inspect v5 sources and tests to learn + expected semantics, edge cases, units, coordinate order, and defaults. +2. **Design for MapWinGIS6 first.** Choose clean modern C++ APIs and modular + responsibilities. Do not mirror legacy class hierarchies or COM signatures + unless there is a concrete compatibility benefit. +3. **Choose compatibility deliberately.** Preserve behavior that matters and + fits the new design. If parity would distort the architecture, add needless + complexity, or block a worthwhile improvement, prefer the better v6 design + and document the difference. +4. **Implement and test.** Add GoogleTest coverage for intended behavior, + including edge cases and failures. Keep COM mapping in the ActiveX layer; + implement legacy API compatibility incrementally where justified. + +## Compatibility decisions + +Compatibility is a design consideration, not an absolute rule that overrides +architecture or maintainability. For each legacy behavior or API surface, +choose deliberately whether it belongs in v6 and document important departures. + +- **Indexes:** use 0-based feature/shape indexes where that remains the chosen + v6 API contract. +- **Enums:** pin numeric values to the v5 type library when an enum is intended + to map directly to that COM contract; unrelated v6 enums need not inherit + legacy numbering. +- **Errors:** prefer clear, structured core errors and modern result patterns. + Translate them to legacy error codes at the COM boundary only where needed + for a supported compatibility surface. +- **Formatting:** preserve legacy display formatting when existing consumers + rely on it; otherwise prefer a consistent, documented v6 representation. ## Anti-patterns diff --git a/docs/TESTING.md b/docs/TESTING.md index a6f3056..ee64efa 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -64,6 +64,25 @@ GeoJSON layer, sampling both polygon fills and the gap between them, and reloading and repainting after control recreation. These integration checks require an interactive Windows desktop and are not currently part of CI. +### Phase 5 validation + +The native renderer tests exercise the OpenGL backend directly when a WGL +context with framebuffer objects is available, then verify that the +coordinator selects it. They also verify that polygons with interior rings use +the GDI fallback and that concave rings hidden by duplicate vertices and +self-intersecting rings are rejected by OpenGL. Scenes with non-finite or +out-of-range device coordinates fail with `E_INVALIDARG` before GDI draws +anything. The OpenGL drawing test skips +only when the backend reports that no suitable target is available (`S_FALSE`); +drawing, readback, or presentation failures fail it. The GDI fallback test +does not require OpenGL. The Debug x64 build completed without compiler +warnings, and the native suite ran 143 tests: 141 passed and 2 were skipped +(the opt-in network test and registered-host check). The +registration-free C# host activated the control, loaded the test layer, and +resized it, but its screen-pixel checks could not be verified in this +noninteractive session because the host window was absent from the captured +desktop. Rerun that check from an interactive Windows desktop. + ## Conventions - One test file per area under test (`VectorDatasetTests.cpp`, diff --git a/samples/CSharp/ActiveXTestHost/MainForm.cs b/samples/CSharp/ActiveXTestHost/MainForm.cs index 97802a9..4ce9645 100644 --- a/samples/CSharp/ActiveXTestHost/MainForm.cs +++ b/samples/CSharp/ActiveXTestHost/MainForm.cs @@ -100,9 +100,13 @@ private void RecreateManually() DisposeHostedControl(); CreateHostedControl(); LoadTestLayer(); + _host!.Update(); + Application.DoEvents(); bool initialized = ReadCoreInitialized(); - _statusLabel.Text = - $"Active: {ProgId}; CoreInitialized={initialized}; polygon features loaded"; + dynamic automation = _host.AutomationObject!; + _statusLabel.Text = initialized + ? $"Active: {ProgId}; backend={automation.RenderingBackend}; {automation.RenderingStatus}" + : $"Active: {ProgId}; CoreInitialized=false"; } catch (Exception exception) { @@ -128,7 +132,9 @@ private void RequestManualRepaint() _host.Invalidate(true); _host.Update(); _surfacePanel.Update(); - _statusLabel.Text = "Repaint requested."; + dynamic automation = _host.AutomationObject!; + _statusLabel.Text = + $"backend={automation.RenderingBackend}; {automation.RenderingStatus}"; } private async Task RunAutomatedAsync() @@ -143,6 +149,7 @@ private async Task RunAutomatedAsync() _statusLabel.Text = $"Active: {ProgId}; CoreInitialized={initialized}"; }); RecordCheck("Load vector layer", LoadTestLayer); + RecordCheck("CPU backend preference and status", VerifyCpuBackendSelection); RecordCheck("Resize", VerifyResize); await RecordCheckAsync("Repaint", VerifyRepaintAsync); @@ -345,6 +352,44 @@ private void VerifyCoreInitialized(string activation) } } + private void VerifyCpuBackendSelection() + { + if (_host?.AutomationObject is not object automationObject) + { + throw new InvalidOperationException("The ActiveX automation object is unavailable."); + } + + dynamic automation = automationObject; + string previousPreference = automation.RenderingBackendPreference; + try + { + automation.RenderingBackendPreference = "GDI"; + RepaintHost(); + + string activeBackend = automation.RenderingBackend; + string renderingStatus = automation.RenderingStatus; + if (activeBackend != "GDI" || + renderingStatus != "GDI was selected by the rendering preference.") + { + throw new InvalidOperationException( + $"The requested CPU backend was not reported. Backend='{activeBackend}', status='{renderingStatus}'."); + } + } + finally + { + // Later resize/repaint checks must exercise the default backend path. + automation.RenderingBackendPreference = previousPreference; + RepaintHost(); + } + } + + private void RepaintHost() + { + _host?.Invalidate(true); + _host?.Update(); + Application.DoEvents(); + } + private void VerifyResize() { if (_host is null) diff --git a/src/MapWinGIS.ActiveX/GdiVectorLayerRenderer.cpp b/src/MapWinGIS.ActiveX/GdiVectorLayerRenderer.cpp new file mode 100644 index 0000000..4cf34cb --- /dev/null +++ b/src/MapWinGIS.ActiveX/GdiVectorLayerRenderer.cpp @@ -0,0 +1,273 @@ +// SPDX-License-Identifier: MPL-2.0 + +/** + * @file GdiVectorLayerRenderer.cpp + * @brief Draws polygon render scenes into a Windows GDI device context. + * + * Fits source coordinates into the control bounds and paints polygon fills + * and outlines without retaining scene or host resources. + */ +#include "GdiVectorLayerRenderer.h" + +#include +#include +#include +#include +#include +#include + +namespace mwg::activex +{ + namespace + { + constexpr int kMargin = 12; + constexpr COLORREF kFillColor = RGB(61, 122, 169); + constexpr COLORREF kOutlineColor = RGB(24, 58, 82); + + class ScopedDcState + { + public: + explicit ScopedDcState(HDC deviceContext) + : _deviceContext(deviceContext), _state(SaveDC(deviceContext)) + { + } + + ~ScopedDcState() + { + if (_state != 0) + { + RestoreDC(_deviceContext, _state); + } + } + + [[nodiscard]] bool IsValid() const noexcept { return _state != 0; } + + private: + HDC _deviceContext; + int _state; + }; + + class ScopedGdiObject + { + public: + explicit ScopedGdiObject(HGDIOBJ object) noexcept + : _object(object) + { + } + + ~ScopedGdiObject() + { + if (_object != nullptr) + { + DeleteObject(_object); + } + } + + [[nodiscard]] HGDIOBJ Get() const noexcept { return _object; } + + private: + HGDIOBJ _object; + }; + + class ScopedSelection + { + public: + ScopedSelection(HDC deviceContext, HGDIOBJ object) noexcept + : _deviceContext(deviceContext), _previous(SelectObject(deviceContext, object)) + { + } + + ~ScopedSelection() + { + if (_previous != nullptr && _previous != HGDI_ERROR) + { + SelectObject(_deviceContext, _previous); + } + } + + [[nodiscard]] bool IsValid() const noexcept + { + return _previous != nullptr && _previous != HGDI_ERROR; + } + + private: + HDC _deviceContext; + HGDIOBJ _previous; + }; + + // GDI on Windows NT only accepts coordinates within a signed 27-bit range. + constexpr double kMaximumGdiCoordinate = 134217727.0; + + [[nodiscard]] double ToDeviceX( + const rendering::Point& point, + const rendering::VectorRenderScene& scene, + const double scale, + const double left) noexcept + { + return left + (point.x - scene.extent.xMin) * scale; + } + + [[nodiscard]] double ToDeviceY( + const rendering::Point& point, + const rendering::VectorRenderScene& scene, + const double scale, + const double top) noexcept + { + return top + (scene.extent.yMax - point.y) * scale; + } + + [[nodiscard]] bool IsDrawableCoordinate(const double value) noexcept + { + return std::isfinite(value) && + value >= -kMaximumGdiCoordinate && + value <= kMaximumGdiCoordinate; + } + + /// Checks every vertex before drawing so invalid geometry fails the + /// whole scene instead of being partially rasterized. + [[nodiscard]] bool HasDrawableCoordinates( + const rendering::VectorRenderScene& scene, + const double scale, + const double left, + const double top) noexcept + { + for (const rendering::Polygon& polygon : scene.polygons) + { + for (const rendering::Ring& ring : polygon) + { + for (const rendering::Point& point : ring) + { + if (!IsDrawableCoordinate(ToDeviceX(point, scene, scale, left)) || + !IsDrawableCoordinate(ToDeviceY(point, scene, scale, top))) + { + return false; + } + } + } + } + + return true; + } + + [[nodiscard]] POINT ToPoint( + const rendering::Point& point, + const rendering::VectorRenderScene& scene, + const double scale, + const double left, + const double top) noexcept + { + return { + static_cast(std::lround(ToDeviceX(point, scene, scale, left))), + static_cast(std::lround(ToDeviceY(point, scene, scale, top)))}; + } + } + + HRESULT GdiVectorLayerRenderer::Draw( + const HDC deviceContext, + const RECT& bounds, + const rendering::VectorRenderScene& scene) noexcept + { + if (deviceContext == nullptr || scene.extent.IsEmpty() || + scene.extent.Width() <= 0.0 || scene.extent.Height() <= 0.0) + { + return E_INVALIDARG; + } + + const double availableWidth = static_cast(bounds.right - bounds.left - 2 * kMargin); + const double availableHeight = static_cast(bounds.bottom - bounds.top - 2 * kMargin); + if (availableWidth <= 0.0 || availableHeight <= 0.0) + { + return S_OK; + } + + const double scale = std::min( + availableWidth / scene.extent.Width(), + availableHeight / scene.extent.Height()); + if (!std::isfinite(scale) || scale <= 0.0) + { + return E_INVALIDARG; + } + + const double drawingWidth = scene.extent.Width() * scale; + const double drawingHeight = scene.extent.Height() * scale; + const double left = static_cast(bounds.left) + + (static_cast(bounds.right - bounds.left) - drawingWidth) / 2.0; + const double top = static_cast(bounds.top) + + (static_cast(bounds.bottom - bounds.top) - drawingHeight) / 2.0; + if (!HasDrawableCoordinates(scene, scale, left, top)) + { + return E_INVALIDARG; + } + + const ScopedDcState savedState(deviceContext); + if (!savedState.IsValid()) + { + return E_FAIL; + } + + const ScopedGdiObject brush(CreateSolidBrush(kFillColor)); + const ScopedGdiObject pen(CreatePen(PS_SOLID, 1, kOutlineColor)); + if (brush.Get() == nullptr || pen.Get() == nullptr) + { + return E_OUTOFMEMORY; + } + + const ScopedSelection selectedBrush(deviceContext, brush.Get()); + const ScopedSelection selectedPen(deviceContext, pen.Get()); + if (!selectedBrush.IsValid() || !selectedPen.IsValid() || + SetPolyFillMode(deviceContext, ALTERNATE) == 0) + { + return E_FAIL; + } + + try + { + for (const rendering::Polygon& polygon : scene.polygons) + { + std::vector points; + std::vector ringCounts; + for (const rendering::Ring& ring : polygon) + { + if (ring.size() < 3) + { + continue; + } + + const std::size_t maximumPoints = + static_cast(std::numeric_limits::max()); + if (ring.size() > maximumPoints || + points.size() > maximumPoints - ring.size()) + { + return E_INVALIDARG; + } + + ringCounts.push_back(static_cast(ring.size())); + for (const rendering::Point& point : ring) + { + points.push_back(ToPoint(point, scene, scale, left, top)); + } + } + + if (!points.empty() && + PolyPolygon( + deviceContext, + points.data(), + ringCounts.data(), + static_cast(ringCounts.size())) == FALSE) + { + return E_FAIL; + } + } + } + catch (const std::bad_alloc&) + { + return E_OUTOFMEMORY; + } + catch (const std::length_error&) + { + return E_OUTOFMEMORY; + } + + return S_OK; + } +} diff --git a/src/MapWinGIS.ActiveX/GdiVectorLayerRenderer.h b/src/MapWinGIS.ActiveX/GdiVectorLayerRenderer.h new file mode 100644 index 0000000..8e5238b --- /dev/null +++ b/src/MapWinGIS.ActiveX/GdiVectorLayerRenderer.h @@ -0,0 +1,24 @@ +// SPDX-License-Identifier: MPL-2.0 + +/** + * @file GdiVectorLayerRenderer.h + * @brief Declares the GDI backend for polygon render scenes. + * + * The backend paints supported vector scene geometry into the supplied + * device context and does not retain host or scene resources. + */ +#pragma once + +#include "VectorRenderBackend.h" + +namespace mwg::activex +{ + class GdiVectorLayerRenderer final : public IVectorRenderBackend + { + public: + [[nodiscard]] HRESULT Draw( + HDC deviceContext, + const RECT& bounds, + const rendering::VectorRenderScene& scene) noexcept override; + }; +} diff --git a/src/MapWinGIS.ActiveX/MapWinGIS.ActiveX.idl b/src/MapWinGIS.ActiveX/MapWinGIS.ActiveX.idl index 5c60396..60a265d 100644 --- a/src/MapWinGIS.ActiveX/MapWinGIS.ActiveX.idl +++ b/src/MapWinGIS.ActiveX/MapWinGIS.ActiveX.idl @@ -33,12 +33,36 @@ library MapWinGISActiveXLib HRESULT FeatureCount([out, retval] hyper* count); }; + // Published interfaces are immutable; new members go on a derived + // interface with its own IID so clients never call missing vtable slots. + [ + object, + dual, + oleautomation, + uuid(2C386A29-C378-45C1-B8D5-5624500CCFF2), + pointer_default(unique) + ] + interface IMapWinGISControl2 : IMapWinGISControl + { + [propget, id(5)] + HRESULT RenderingBackend([out, retval] BSTR* backend); + + [propget, id(6)] + HRESULT RenderingStatus([out, retval] BSTR* status); + + [propget, id(7)] + HRESULT RenderingBackendPreference([out, retval] BSTR* preference); + + [propput, id(7)] + HRESULT RenderingBackendPreference([in] BSTR preference); + }; + [ uuid(2F0AB6FC-F7C0-4E42-A002-A61F9C6F294F), control ] coclass MapWinGISControl { - [default] interface IMapWinGISControl; + [default] interface IMapWinGISControl2; }; }; diff --git a/src/MapWinGIS.ActiveX/MapWinGIS.ActiveX.vcxproj b/src/MapWinGIS.ActiveX/MapWinGIS.ActiveX.vcxproj index d86d3f9..1513908 100644 --- a/src/MapWinGIS.ActiveX/MapWinGIS.ActiveX.vcxproj +++ b/src/MapWinGIS.ActiveX/MapWinGIS.ActiveX.vcxproj @@ -66,14 +66,19 @@ + + + + + diff --git a/src/MapWinGIS.ActiveX/MapWinGISControl.cpp b/src/MapWinGIS.ActiveX/MapWinGISControl.cpp index 403c1e2..daf044e 100644 --- a/src/MapWinGIS.ActiveX/MapWinGISControl.cpp +++ b/src/MapWinGIS.ActiveX/MapWinGISControl.cpp @@ -11,12 +11,57 @@ #include #include #include +#include #include -#include "VectorLayerRenderer.h" #include "mapwingis/core/Error.h" #include "mapwingis/gdal/GdalEnvironment.h" +namespace +{ + [[nodiscard]] HRESULT CopyToBstr(const std::wstring_view value, BSTR* result) noexcept + { + if (result == nullptr) + { + return E_POINTER; + } + + *result = ::SysAllocStringLen( + value.data(), + static_cast(value.size())); + return *result != nullptr ? S_OK : E_OUTOFMEMORY; + } + + [[nodiscard]] const wchar_t* BackendName( + const std::optional backend) noexcept + { + if (!backend.has_value()) + { + return L"Not rendered"; + } + + return *backend == mwg::activex::VectorRenderBackendKind::OpenGL + ? L"OpenGL" + : L"GDI"; + } + + [[nodiscard]] const wchar_t* PreferenceName( + const mwg::activex::VectorRenderBackendPreference preference) noexcept + { + switch (preference) + { + case mwg::activex::VectorRenderBackendPreference::Automatic: + return L"Automatic"; + case mwg::activex::VectorRenderBackendPreference::OpenGL: + return L"OpenGL"; + case mwg::activex::VectorRenderBackendPreference::Gdi: + return L"GDI"; + default: + return L"Automatic"; + } + } +} + STDMETHODIMP CMapWinGISControl::get_CoreInitialized(VARIANT_BOOL* initialized) { if (initialized == nullptr) @@ -99,6 +144,61 @@ STDMETHODIMP CMapWinGISControl::get_FeatureCount(LONGLONG* count) return S_OK; } +STDMETHODIMP CMapWinGISControl::get_RenderingBackend(BSTR* backend) +{ + return CopyToBstr(BackendName(_renderer.GetActiveBackend()), backend); +} + +STDMETHODIMP CMapWinGISControl::get_RenderingStatus(BSTR* status) +{ + return CopyToBstr(_renderer.GetDiagnostic(), status); +} + +STDMETHODIMP CMapWinGISControl::get_RenderingBackendPreference(BSTR* preference) +{ + return CopyToBstr(PreferenceName(_renderer.GetPreference()), preference); +} + +STDMETHODIMP CMapWinGISControl::put_RenderingBackendPreference(BSTR preference) +{ + if (preference == nullptr) + { + return E_INVALIDARG; + } + + const UINT length = ::SysStringLen(preference); + auto equals = [preference, length](const wchar_t* value, const int valueLength) + { + return length == static_cast(valueLength) && + ::CompareStringOrdinal( + preference, + static_cast(length), + value, + valueLength, + TRUE) == CSTR_EQUAL; + }; + + if (equals(L"Automatic", 9)) + { + _renderer.SetPreference(mwg::activex::VectorRenderBackendPreference::Automatic); + } + else if (equals(L"OpenGL", 6)) + { + _renderer.SetPreference(mwg::activex::VectorRenderBackendPreference::OpenGL); + } + else if (equals(L"GDI", 3)) + { + _renderer.SetPreference(mwg::activex::VectorRenderBackendPreference::Gdi); + } + else + { + return E_INVALIDARG; + } + + FireViewChange(); + return S_OK; +} + LRESULT CMapWinGISControl::OnSize( UINT, WPARAM, @@ -132,6 +232,6 @@ HRESULT CMapWinGISControl::OnDraw(ATL_DRAWINFO& drawInfo) } return _scene.has_value() - ? mwg::activex::DrawVectorRenderScene(drawInfo.hdcDraw, bounds, *_scene) + ? _renderer.Draw(drawInfo.hdcDraw, bounds, *_scene) : S_OK; } diff --git a/src/MapWinGIS.ActiveX/MapWinGISControl.h b/src/MapWinGIS.ActiveX/MapWinGISControl.h index bb5945c..f78ef40 100644 --- a/src/MapWinGIS.ActiveX/MapWinGISControl.h +++ b/src/MapWinGIS.ActiveX/MapWinGISControl.h @@ -4,8 +4,8 @@ * @file MapWinGISControl.h * @brief Declares the COM-creatable MapWinGIS ActiveX control. * - * Provides automation for loading a vector dataset and painting its initial - * polygon layer into the host drawing surface. + * Provides automation for loading vector data, selecting a rendering backend, + * reporting render status, and painting the initial polygon layer. */ #pragma once @@ -19,6 +19,7 @@ #include "mapwingis/rendering/VectorRenderScene.h" #include "mapwingis/vector/VectorDataset.h" +#include "VectorLayerRenderer.h" class ATL_NO_VTABLE CMapWinGISControl : public ATL::CComObjectRootEx, @@ -31,8 +32,8 @@ class ATL_NO_VTABLE CMapWinGISControl : public ATL::IOleInPlaceObjectWindowlessImpl, public ATL::IPersistStreamInitImpl, public ATL::IDispatchImpl< - IMapWinGISControl, - &IID_IMapWinGISControl, + IMapWinGISControl2, + &IID_IMapWinGISControl2, &LIBID_MapWinGISActiveXLib, 1, 0> @@ -43,6 +44,7 @@ class ATL_NO_VTABLE CMapWinGISControl : DECLARE_PROTECT_FINAL_CONSTRUCT() BEGIN_COM_MAP(CMapWinGISControl) + COM_INTERFACE_ENTRY(IMapWinGISControl2) COM_INTERFACE_ENTRY(IMapWinGISControl) COM_INTERFACE_ENTRY(IDispatch) COM_INTERFACE_ENTRY(IViewObjectEx) @@ -72,6 +74,10 @@ class ATL_NO_VTABLE CMapWinGISControl : STDMETHOD(LoadVectorDataset)(BSTR path) override; STDMETHOD(get_LayerLoaded)(VARIANT_BOOL* loaded) override; STDMETHOD(get_FeatureCount)(LONGLONG* count) override; + STDMETHOD(get_RenderingBackend)(BSTR* backend) override; + STDMETHOD(get_RenderingStatus)(BSTR* status) override; + STDMETHOD(get_RenderingBackendPreference)(BSTR* preference) override; + STDMETHOD(put_RenderingBackendPreference)(BSTR preference) override; LRESULT OnSize(UINT, WPARAM, LPARAM, BOOL& handled); HRESULT OnDraw(ATL_DRAWINFO& drawInfo); @@ -79,6 +85,7 @@ class ATL_NO_VTABLE CMapWinGISControl : private: std::unique_ptr _dataset; std::optional _scene; + mwg::activex::VectorLayerRenderer _renderer; LONGLONG _featureCount = 0; }; diff --git a/src/MapWinGIS.ActiveX/OpenGlVectorLayerRenderer.cpp b/src/MapWinGIS.ActiveX/OpenGlVectorLayerRenderer.cpp new file mode 100644 index 0000000..21a4952 --- /dev/null +++ b/src/MapWinGIS.ActiveX/OpenGlVectorLayerRenderer.cpp @@ -0,0 +1,768 @@ +// SPDX-License-Identifier: MPL-2.0 + +/** + * @file OpenGlVectorLayerRenderer.cpp + * @brief Renders convex polygon scenes with WGL and copies pixels to GDI. + * + * Owns one reusable OpenGL context and draws into a framebuffer object so + * pixel readback is not subject to window pixel-ownership rules. Scenes that + * need unsupported polygon features, or systems without framebuffer objects, + * return S_FALSE so the coordinator can use its GDI backend. + */ +#include "OpenGlVectorLayerRenderer.h" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#pragma comment(lib, "opengl32.lib") + +namespace mwg::activex +{ + // OpenGL 3.0 and GL_EXT_framebuffer_object share these enum values. + namespace + { + constexpr GLenum kFramebuffer = 0x8D40; + constexpr GLenum kRenderbuffer = 0x8D41; + constexpr GLenum kColorAttachment0 = 0x8CE0; + constexpr GLenum kFramebufferComplete = 0x8CD5; + constexpr GLenum kRgba8 = 0x8058; + constexpr GLenum kMaxRenderbufferSize = 0x84E8; + constexpr std::size_t kMaxStagingBufferBytes = 64U * 1024U * 1024U; + constexpr std::size_t kBytesPerPixel = 4; + } + + struct OpenGlVectorLayerRenderer::FramebufferFunctions final + { + using GenObjects = void(APIENTRY*)(GLsizei, GLuint*); + using BindObject = void(APIENTRY*)(GLenum, GLuint); + using RenderbufferStorage = void(APIENTRY*)(GLenum, GLenum, GLsizei, GLsizei); + using FramebufferRenderbuffer = void(APIENTRY*)(GLenum, GLenum, GLenum, GLuint); + using CheckFramebufferStatus = GLenum(APIENTRY*)(GLenum); + + GenObjects genFramebuffers{}; + BindObject bindFramebuffer{}; + GenObjects genRenderbuffers{}; + BindObject bindRenderbuffer{}; + RenderbufferStorage renderbufferStorage{}; + FramebufferRenderbuffer framebufferRenderbuffer{}; + CheckFramebufferStatus checkFramebufferStatus{}; + + /// Loads the core entry points or, failing that, the EXT ones. + /// Requires the owning context to be current. + [[nodiscard]] bool Load() noexcept + { + return LoadSet("") || LoadSet("EXT"); + } + + 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); + // Some drivers report failure with small sentinel values instead of null. + 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(genFramebuffers, "glGenFramebuffers", suffix) && + LoadFunction(bindFramebuffer, "glBindFramebuffer", suffix) && + LoadFunction(genRenderbuffers, "glGenRenderbuffers", suffix) && + LoadFunction(bindRenderbuffer, "glBindRenderbuffer", suffix) && + LoadFunction(renderbufferStorage, "glRenderbufferStorage", suffix) && + LoadFunction(framebufferRenderbuffer, "glFramebufferRenderbuffer", suffix) && + LoadFunction(checkFramebufferStatus, "glCheckFramebufferStatus", suffix); + } + }; + + namespace + { + constexpr int kMargin = 12; + + class ScopedCurrentContext final + { + public: + explicit ScopedCurrentContext(HDC deviceContext, HGLRC renderingContext) noexcept + : _previousDeviceContext(wglGetCurrentDC()), + _previousRenderingContext(wglGetCurrentContext()), + _valid(wglMakeCurrent(deviceContext, renderingContext) != FALSE) + { + } + + ~ScopedCurrentContext() + { + // A failed wglMakeCurrent still detaches the caller's context, + // so restore it even when activation did not succeed. + wglMakeCurrent(_previousDeviceContext, _previousRenderingContext); + } + + [[nodiscard]] bool IsValid() const noexcept { return _valid; } + + private: + HDC _previousDeviceContext; + HGLRC _previousRenderingContext; + bool _valid; + }; + + [[nodiscard]] bool IsSamePoint( + const rendering::Point& first, + const rendering::Point& second) noexcept + { + return first.x == second.x && first.y == second.y; + } + + /// Returns true when the ring is a simple, strictly convex polygon. + /// Consecutive duplicate vertices are ignored so they cannot hide a + /// concave corner, and the total turning angle must be one full turn + /// so self-intersecting rings with consistent turns are rejected. + [[nodiscard]] bool IsConvex(const rendering::Ring& ring) noexcept + { + std::vector vertices; + try + { + vertices.reserve(ring.size()); + for (const rendering::Point& point : ring) + { + if (vertices.empty() || !IsSamePoint(vertices.back(), point)) + { + vertices.push_back(point); + } + } + } + catch (const std::bad_alloc&) + { + return false; + } + + while (vertices.size() > 1 && IsSamePoint(vertices.front(), vertices.back())) + { + vertices.pop_back(); + } + + const std::size_t count = vertices.size(); + if (count < 3) + { + return false; + } + + constexpr double kPi = 3.14159265358979323846; + double orientation = 0.0; + double totalTurn = 0.0; + for (std::size_t index = 0; index < count; ++index) + { + const rendering::Point& first = vertices[index]; + const rendering::Point& second = vertices[(index + 1) % count]; + const rendering::Point& third = vertices[(index + 2) % count]; + const double cross = + (second.x - first.x) * (third.y - second.y) - + (second.y - first.y) * (third.x - second.x); + const double dot = + (second.x - first.x) * (third.x - second.x) + + (second.y - first.y) * (third.y - second.y); + if (!std::isfinite(cross) || !std::isfinite(dot)) + { + return false; + } + + if (cross == 0.0) + { + // Collinear vertices are fine, but a reversal is a spike + // whose overlapping edges GL_POLYGON cannot represent. + if (dot < 0.0) + { + return false; + } + continue; + } + + if (orientation == 0.0) + { + orientation = cross; + } + else if ((orientation > 0.0) != (cross > 0.0)) + { + return false; + } + + totalTurn += std::atan2(cross, dot); + } + + // With consistent turn signs the total is a multiple of 2*pi; + // only a single full turn describes a simple ring. + return orientation != 0.0 && std::abs(totalTurn) < 3.0 * kPi; + } + + [[nodiscard]] bool IsSupported(const rendering::VectorRenderScene& scene) noexcept + { + for (const rendering::Polygon& polygon : scene.polygons) + { + if (polygon.size() != 1 || !IsConvex(polygon.front())) + { + return false; + } + + for (const rendering::Point& point : polygon.front()) + { + if (!std::isfinite(point.x) || !std::isfinite(point.y)) + { + return false; + } + } + } + + return true; + } + + [[nodiscard]] std::int64_t GetWidth(const RECT& bounds) noexcept + { + return static_cast(bounds.right) - bounds.left; + } + + [[nodiscard]] std::int64_t GetHeight(const RECT& bounds) noexcept + { + return static_cast(bounds.bottom) - bounds.top; + } + } + + OpenGlVectorLayerRenderer::OpenGlVectorLayerRenderer() noexcept = default; + + OpenGlVectorLayerRenderer::~OpenGlVectorLayerRenderer() + { + Release(); + } + + bool OpenGlVectorLayerRenderer::IsTargetWithinLimits( + const int width, + const int height, + const int maximumWidth, + const int maximumHeight, + std::wstring_view& rejectionReason) noexcept + { + if (width <= 0 || height <= 0) + { + rejectionReason = L"The OpenGL target dimensions must be positive."; + return false; + } + + if (maximumWidth <= 0 || maximumHeight <= 0) + { + rejectionReason = L"OpenGL did not report a usable maximum framebuffer size."; + return false; + } + + if (width > maximumWidth || height > maximumHeight) + { + rejectionReason = + L"The OpenGL target exceeds the detected maximum framebuffer or viewport size."; + return false; + } + + const std::size_t pixelWidth = static_cast(width); + const std::size_t pixelHeight = static_cast(height); + if (pixelWidth > std::numeric_limits::max() / pixelHeight || + pixelWidth * pixelHeight > kMaxStagingBufferBytes / kBytesPerPixel) + { + rejectionReason = + L"The OpenGL frame exceeds the 64 MiB CPU staging-buffer budget."; + return false; + } + + rejectionReason = {}; + return true; + } + + bool OpenGlVectorLayerRenderer::Initialize() noexcept + { + if (_renderingContext != nullptr) + { + return true; + } + if (_initializationFailed) + { + _lastFailureReason = _initializationFailureReason; + return false; + } + + _window = CreateWindowExW( + 0, + L"STATIC", + L"MapWinGIS OpenGL render target", + WS_POPUP, + 0, + 0, + 1, + 1, + nullptr, + nullptr, + GetModuleHandleW(nullptr), + nullptr); + if (_window == nullptr) + { + _initializationFailed = true; + _lastFailureReason = L"OpenGL could not create its render target window."; + _initializationFailureReason = _lastFailureReason; + OutputDebugStringW(L"MapWinGIS: could not create the OpenGL render target window.\n"); + Release(); + return false; + } + + _deviceContext = GetDC(_window); + if (_deviceContext == nullptr) + { + _initializationFailed = true; + _lastFailureReason = L"OpenGL could not acquire its render target device context."; + _initializationFailureReason = _lastFailureReason; + OutputDebugStringW(L"MapWinGIS: could not acquire the OpenGL render target DC.\n"); + Release(); + return false; + } + + PIXELFORMATDESCRIPTOR descriptor{}; + descriptor.nSize = sizeof(descriptor); + descriptor.nVersion = 1; + descriptor.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL; + descriptor.iPixelType = PFD_TYPE_RGBA; + descriptor.cColorBits = 32; + descriptor.cAlphaBits = 8; + descriptor.iLayerType = PFD_MAIN_PLANE; + + const int pixelFormat = ChoosePixelFormat(_deviceContext, &descriptor); + if (pixelFormat == 0 || SetPixelFormat(_deviceContext, pixelFormat, &descriptor) == FALSE) + { + _initializationFailed = true; + _lastFailureReason = L"OpenGL could not select a compatible pixel format."; + _initializationFailureReason = _lastFailureReason; + OutputDebugStringW(L"MapWinGIS: could not select an OpenGL pixel format.\n"); + Release(); + return false; + } + + _renderingContext = wglCreateContext(_deviceContext); + if (_renderingContext == nullptr) + { + _initializationFailed = true; + _lastFailureReason = L"OpenGL could not create a rendering context."; + _initializationFailureReason = _lastFailureReason; + OutputDebugStringW(L"MapWinGIS: could not create an OpenGL rendering context.\n"); + Release(); + return false; + } + + if (!InitializeFramebuffer()) + { + _initializationFailed = true; + if (_lastFailureReason == L"OpenGL was not selected for this frame.") + { + _lastFailureReason = + L"OpenGL framebuffer objects are unavailable on this system."; + } + _initializationFailureReason = _lastFailureReason; + OutputDebugStringW(L"MapWinGIS: OpenGL framebuffer objects are unavailable.\n"); + Release(); + return false; + } + + return true; + } + + bool OpenGlVectorLayerRenderer::InitializeFramebuffer() noexcept + { + const ScopedCurrentContext currentContext(_deviceContext, _renderingContext); + if (!currentContext.IsValid()) + { + return false; + } + + _framebufferFunctions.reset(new (std::nothrow) FramebufferFunctions{}); + if (_framebufferFunctions == nullptr || !_framebufferFunctions->Load()) + { + _framebufferFunctions.reset(); + _lastFailureReason = + L"The OpenGL framebuffer-object entry points are unavailable."; + return false; + } + + while (glGetError() != GL_NO_ERROR) + { + } + + GLint maximumFramebufferSize{}; + glGetIntegerv(kMaxRenderbufferSize, &maximumFramebufferSize); + GLint maximumViewportDimensions[2]{}; + glGetIntegerv(GL_MAX_VIEWPORT_DIMS, maximumViewportDimensions); + if (glGetError() != GL_NO_ERROR || maximumFramebufferSize <= 0 || + maximumViewportDimensions[0] <= 0 || maximumViewportDimensions[1] <= 0) + { + _lastFailureReason = + L"OpenGL did not report a usable maximum framebuffer size."; + return false; + } + _maximumTargetWidth = std::min(maximumFramebufferSize, maximumViewportDimensions[0]); + _maximumTargetHeight = std::min(maximumFramebufferSize, maximumViewportDimensions[1]); + + _framebufferFunctions->genFramebuffers(1, &_framebuffer); + _framebufferFunctions->genRenderbuffers(1, &_renderbuffer); + _framebufferFunctions->bindRenderbuffer(kRenderbuffer, _renderbuffer); + _framebufferFunctions->bindFramebuffer(kFramebuffer, _framebuffer); + _framebufferFunctions->framebufferRenderbuffer( + kFramebuffer, + kColorAttachment0, + kRenderbuffer, + _renderbuffer); + return glGetError() == GL_NO_ERROR && _framebuffer != 0 && _renderbuffer != 0; + } + + bool OpenGlVectorLayerRenderer::ResizeFramebuffer(const int width, const int height) noexcept + { + _framebufferFunctions->bindFramebuffer(kFramebuffer, _framebuffer); + _framebufferFunctions->bindRenderbuffer(kRenderbuffer, _renderbuffer); + if (width != _framebufferWidth || height != _framebufferHeight) + { + _framebufferWidth = 0; + _framebufferHeight = 0; + while (glGetError() != GL_NO_ERROR) + { + } + + _framebufferFunctions->renderbufferStorage(kRenderbuffer, kRgba8, width, height); + if (glGetError() != GL_NO_ERROR) + { + return false; + } + + _framebufferWidth = width; + _framebufferHeight = height; + } + + return _framebufferFunctions->checkFramebufferStatus(kFramebuffer) == kFramebufferComplete; + } + + void OpenGlVectorLayerRenderer::Release() noexcept + { + // The context is not shared, so deleting it also frees the + // framebuffer and renderbuffer objects. + _framebufferFunctions.reset(); + _framebuffer = 0; + _renderbuffer = 0; + _framebufferWidth = 0; + _framebufferHeight = 0; + _maximumTargetWidth = 0; + _maximumTargetHeight = 0; + + if (_renderingContext != nullptr) + { + if (wglGetCurrentContext() == _renderingContext) + { + wglMakeCurrent(nullptr, nullptr); + } + wglDeleteContext(_renderingContext); + _renderingContext = nullptr; + } + + if (_deviceContext != nullptr && _window != nullptr) + { + ReleaseDC(_window, _deviceContext); + _deviceContext = nullptr; + } + + if (_window != nullptr) + { + DestroyWindow(_window); + _window = nullptr; + } + } + + HRESULT OpenGlVectorLayerRenderer::Draw( + const HDC deviceContext, + const RECT& bounds, + const rendering::VectorRenderScene& scene) noexcept + { + _lastFailureReason = L"OpenGL did not render this frame."; + if (deviceContext == nullptr) + { + _lastFailureReason = L"The OpenGL target device context is invalid."; + return E_INVALIDARG; + } + + if (!IsSupported(scene)) + { + _lastFailureReason = + L"The scene uses geometry that the OpenGL backend does not support."; + return S_FALSE; + } + + if (scene.extent.IsEmpty() || + scene.extent.Width() <= 0.0 || + scene.extent.Height() <= 0.0) + { + _lastFailureReason = L"The scene extent is invalid for OpenGL rendering."; + return E_INVALIDARG; + } + + const std::int64_t width = GetWidth(bounds); + const std::int64_t height = GetHeight(bounds); + if (width <= 2 * kMargin || height <= 2 * kMargin || + width > std::numeric_limits::max() || + height > std::numeric_limits::max()) + { + _lastFailureReason = L"The OpenGL target has invalid or too-small dimensions."; + return S_FALSE; + } + + const std::size_t pixelWidth = static_cast(width); + const std::size_t pixelHeight = static_cast(height); + std::wstring_view rejectionReason; + if (!IsTargetWithinLimits( + static_cast(width), + static_cast(height), + std::numeric_limits::max(), + std::numeric_limits::max(), + rejectionReason)) + { + _lastFailureReason = rejectionReason; + return S_FALSE; + } + + // Keep the flag set until a replacement context initializes, so a + // transient recreation failure is retried on later draws. + if (_contextInvalid) + { + Release(); + _initializationFailed = false; + _initializationFailureReason = {}; + } + + if (!Initialize()) + { + return S_FALSE; + } + _contextInvalid = false; + + if (!IsTargetWithinLimits( + static_cast(width), + static_cast(height), + _maximumTargetWidth, + _maximumTargetHeight, + rejectionReason)) + { + _lastFailureReason = rejectionReason; + return S_FALSE; + } + + const std::size_t pixelCount = pixelWidth * pixelHeight; + const std::size_t stagingBytes = pixelCount * kBytesPerPixel; + try + { + // Allocate exactly the accepted size and free the old buffer + // first, so neither retained capacity nor the resize peak can + // exceed the staging budget enforced by IsTargetWithinLimits. + if (_rgbaPixels.capacity() < stagingBytes) + { + std::vector().swap(_rgbaPixels); + _rgbaPixels.reserve(stagingBytes); + } + _rgbaPixels.resize(stagingBytes); + } + catch (const std::bad_alloc&) + { + _lastFailureReason = L"OpenGL could not allocate its CPU staging buffers."; + return S_FALSE; + } + catch (const std::length_error&) + { + _lastFailureReason = L"The OpenGL CPU staging-buffer size is not representable."; + return S_FALSE; + } + + const ScopedCurrentContext currentContext(_deviceContext, _renderingContext); + if (!currentContext.IsValid()) + { + _lastFailureReason = L"OpenGL could not activate its rendering context."; + OutputDebugStringW(L"MapWinGIS: could not activate the OpenGL rendering context.\n"); + _contextInvalid = true; + return E_FAIL; + } + + const int viewportWidth = static_cast(width); + const int viewportHeight = static_cast(height); + if (!ResizeFramebuffer(viewportWidth, viewportHeight)) + { + _lastFailureReason = + L"OpenGL could not allocate a complete framebuffer for this target."; + OutputDebugStringW(L"MapWinGIS: no complete OpenGL framebuffer for this size.\n"); + return S_FALSE; + } + + const double availableWidth = static_cast(width - 2 * kMargin); + const double availableHeight = static_cast(height - 2 * kMargin); + const double scale = std::min( + availableWidth / scene.extent.Width(), + availableHeight / scene.extent.Height()); + if (!std::isfinite(scale) || scale <= 0.0) + { + _lastFailureReason = L"The scene extent cannot be represented in the OpenGL viewport."; + return E_INVALIDARG; + } + + const double drawingWidth = scene.extent.Width() * scale; + const double drawingHeight = scene.extent.Height() * scale; + const double left = (static_cast(width) - drawingWidth) / 2.0; + const double top = (static_cast(height) - drawingHeight) / 2.0; + + while (glGetError() != GL_NO_ERROR) + { + } + + glViewport(0, 0, viewportWidth, viewportHeight); + glMatrixMode(GL_PROJECTION); + glLoadIdentity(); + glOrtho(0.0, static_cast(width), static_cast(height), 0.0, -1.0, 1.0); + glMatrixMode(GL_MODELVIEW); + glLoadIdentity(); + glDisable(GL_DITHER); + glDisable(GL_TEXTURE_2D); + glDisable(GL_BLEND); + glDrawBuffer(kColorAttachment0); + + const COLORREF background = GetSysColor(COLOR_WINDOW); + glClearColor( + static_cast(GetRValue(background)) / 255.0F, + static_cast(GetGValue(background)) / 255.0F, + static_cast(GetBValue(background)) / 255.0F, + 1.0F); + glClear(GL_COLOR_BUFFER_BIT); + + for (const rendering::Polygon& polygon : scene.polygons) + { + const rendering::Ring& ring = polygon.front(); + std::size_t count = ring.size(); + if (count > 1 && + ring.front().x == ring.back().x && + ring.front().y == ring.back().y) + { + --count; + } + + glColor3ub(61, 122, 169); + glBegin(GL_POLYGON); + for (std::size_t index = 0; index < count; ++index) + { + const rendering::Point& point = ring[index]; + const double x = left + (point.x - scene.extent.xMin) * scale; + const double y = top + (scene.extent.yMax - point.y) * scale; + glVertex2d(x, y); + } + glEnd(); + + glColor3ub(24, 58, 82); + glBegin(GL_LINE_LOOP); + for (std::size_t index = 0; index < count; ++index) + { + const rendering::Point& point = ring[index]; + const double x = left + (point.x - scene.extent.xMin) * scale; + const double y = top + (scene.extent.yMax - point.y) * scale; + glVertex2d(x, y); + } + glEnd(); + } + + glFlush(); + glReadBuffer(kColorAttachment0); + glReadPixels( + 0, + 0, + viewportWidth, + viewportHeight, + GL_RGBA, + GL_UNSIGNED_BYTE, + _rgbaPixels.data()); + if (glGetError() != GL_NO_ERROR) + { + _lastFailureReason = + L"OpenGL drawing or pixel readback failed; the context will be recreated."; + OutputDebugStringW(L"MapWinGIS: OpenGL drawing or pixel readback failed.\n"); + _contextInvalid = true; + return E_FAIL; + } + + for (std::size_t row = 0; row < pixelHeight / 2; ++row) + { + for (std::size_t column = 0; column < pixelWidth; ++column) + { + const std::size_t topPixel = (row * pixelWidth + column) * 4; + const std::size_t bottomPixel = + ((pixelHeight - row - 1) * pixelWidth + column) * 4; + for (std::size_t channel = 0; channel < 4; ++channel) + { + std::swap( + _rgbaPixels[topPixel + channel], + _rgbaPixels[bottomPixel + channel]); + } + } + } + + for (std::size_t pixel = 0; pixel < pixelCount; ++pixel) + { + const std::size_t offset = pixel * 4; + std::swap(_rgbaPixels[offset], _rgbaPixels[offset + 2]); + _rgbaPixels[offset + 3] = 255; + } + + BITMAPINFO bitmapInfo{}; + bitmapInfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); + bitmapInfo.bmiHeader.biWidth = viewportWidth; + bitmapInfo.bmiHeader.biHeight = -viewportHeight; + bitmapInfo.bmiHeader.biPlanes = 1; + bitmapInfo.bmiHeader.biBitCount = 32; + bitmapInfo.bmiHeader.biCompression = BI_RGB; + + const int copiedRows = SetDIBitsToDevice( + deviceContext, + bounds.left, + bounds.top, + static_cast(viewportWidth), + static_cast(viewportHeight), + 0, + 0, + 0, + static_cast(viewportHeight), + _rgbaPixels.data(), + &bitmapInfo, + DIB_RGB_COLORS); + if (copiedRows != viewportHeight) + { + _lastFailureReason = + L"OpenGL rendered the frame, but Windows could not present its pixels."; + return E_FAIL; + } + + return S_OK; + } +} diff --git a/src/MapWinGIS.ActiveX/OpenGlVectorLayerRenderer.h b/src/MapWinGIS.ActiveX/OpenGlVectorLayerRenderer.h new file mode 100644 index 0000000..fc01d97 --- /dev/null +++ b/src/MapWinGIS.ActiveX/OpenGlVectorLayerRenderer.h @@ -0,0 +1,88 @@ +// SPDX-License-Identifier: MPL-2.0 + +/** + * @file OpenGlVectorLayerRenderer.h + * @brief Declares the WGL-backed polygon scene 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. + */ +#pragma once + +#include + +#include +#include +#include + +#include "VectorRenderBackend.h" + +namespace mwg::activex +{ + class OpenGlVectorLayerRenderer final : public IVectorRenderBackend + { + public: + OpenGlVectorLayerRenderer() noexcept; + ~OpenGlVectorLayerRenderer() override; + + OpenGlVectorLayerRenderer(const OpenGlVectorLayerRenderer&) = delete; + OpenGlVectorLayerRenderer& operator=(const OpenGlVectorLayerRenderer&) = delete; + + /** + * @brief Checks a target against detected size limits and the staging budget. + * + * @p maximumWidth and @p maximumHeight are the effective per-axis + * limits: the smaller of the renderbuffer size and the viewport + * dimensions, because `glViewport` silently clamps larger targets. + */ + [[nodiscard]] static bool IsTargetWithinLimits( + int width, + int height, + int maximumWidth, + int maximumHeight, + std::wstring_view& rejectionReason) noexcept; + + /** + * @brief Draws a scene of simple convex single-ring polygons. + * + * Returns S_FALSE without drawing when the scene contains unsupported + * geometry or when no OpenGL context with framebuffer-object support + * is available, so callers can fall back to another backend. + */ + [[nodiscard]] HRESULT Draw( + HDC deviceContext, + const RECT& bounds, + const rendering::VectorRenderScene& scene) noexcept override; + + [[nodiscard]] std::wstring_view GetLastFailureReason() const noexcept + { + return _lastFailureReason; + } + + private: + struct FramebufferFunctions; + + [[nodiscard]] bool Initialize() noexcept; + [[nodiscard]] bool InitializeFramebuffer() noexcept; + [[nodiscard]] bool ResizeFramebuffer(int width, int height) noexcept; + void Release() noexcept; + + HWND _window{}; + HDC _deviceContext{}; + HGLRC _renderingContext{}; + std::unique_ptr _framebufferFunctions; + unsigned int _framebuffer{}; + unsigned int _renderbuffer{}; + int _framebufferWidth{}; + int _framebufferHeight{}; + int _maximumTargetWidth{}; + int _maximumTargetHeight{}; + bool _initializationFailed = false; + bool _contextInvalid = false; + std::wstring_view _lastFailureReason = + L"OpenGL was not selected for this frame."; + std::wstring_view _initializationFailureReason; + std::vector _rgbaPixels; + }; +} diff --git a/src/MapWinGIS.ActiveX/VectorLayerRenderer.cpp b/src/MapWinGIS.ActiveX/VectorLayerRenderer.cpp index fe6d44a..d133605 100644 --- a/src/MapWinGIS.ActiveX/VectorLayerRenderer.cpp +++ b/src/MapWinGIS.ActiveX/VectorLayerRenderer.cpp @@ -2,214 +2,54 @@ /** * @file VectorLayerRenderer.cpp - * @brief Draws polygon render scenes into a Windows GDI device context. + * @brief Coordinates OpenGL and GDI rendering for vector scenes. * - * Fits source coordinates into the control bounds and paints polygon fills - * and outlines without retaining scene or host resources. + * Keeps backend selection internal to the ActiveX rendering layer and retries + * with GDI when OpenGL is unavailable or cannot represent the scene. */ #include "VectorLayerRenderer.h" -#include -#include -#include -#include -#include -#include - namespace mwg::activex { - namespace + HRESULT VectorLayerRenderer::Draw( + const HDC deviceContext, + const RECT& bounds, + const rendering::VectorRenderScene& scene) noexcept { - constexpr int kMargin = 12; - constexpr COLORREF kFillColor = RGB(61, 122, 169); - constexpr COLORREF kOutlineColor = RGB(24, 58, 82); + _activeBackend.reset(); - class ScopedDcState + if (_preference != VectorRenderBackendPreference::Gdi) { - public: - explicit ScopedDcState(HDC deviceContext) - : _deviceContext(deviceContext), _state(SaveDC(deviceContext)) + const HRESULT openGlResult = _openGlRenderer.Draw(deviceContext, bounds, scene); + if (openGlResult == S_OK) { + _activeBackend = VectorRenderBackendKind::OpenGL; + _diagnostic = L"OpenGL rendered the frame successfully."; + return S_OK; } - ~ScopedDcState() + _diagnostic = _openGlRenderer.GetLastFailureReason(); + if (FAILED(openGlResult)) { - if (_state != 0) - { - RestoreDC(_deviceContext, _state); - } + ::OutputDebugStringW( + L"MapWinGIS: OpenGL rendering failed; using the GDI backend.\n"); } - - [[nodiscard]] bool IsValid() const noexcept { return _state != 0; } - - private: - HDC _deviceContext; - int _state; - }; - - class ScopedGdiObject - { - public: - explicit ScopedGdiObject(HGDIOBJ object) noexcept - : _object(object) - { - } - - ~ScopedGdiObject() - { - if (_object != nullptr) - { - DeleteObject(_object); - } - } - - [[nodiscard]] HGDIOBJ Get() const noexcept { return _object; } - - private: - HGDIOBJ _object; - }; - - class ScopedSelection - { - public: - ScopedSelection(HDC deviceContext, HGDIOBJ object) noexcept - : _deviceContext(deviceContext), _previous(SelectObject(deviceContext, object)) - { - } - - ~ScopedSelection() - { - if (_previous != nullptr && _previous != HGDI_ERROR) - { - SelectObject(_deviceContext, _previous); - } - } - - [[nodiscard]] bool IsValid() const noexcept - { - return _previous != nullptr && _previous != HGDI_ERROR; - } - - private: - HDC _deviceContext; - HGDIOBJ _previous; - }; - - [[nodiscard]] POINT ToPoint( - const rendering::Point& point, - const rendering::VectorRenderScene& scene, - const double scale, - const double left, - const double top) noexcept - { - return { - static_cast(std::lround(left + (point.x - scene.extent.xMin) * scale)), - static_cast(std::lround(top + (scene.extent.yMax - point.y) * scale))}; } - } - - HRESULT DrawVectorRenderScene( - const HDC deviceContext, - const RECT& bounds, - const rendering::VectorRenderScene& scene) noexcept - { - if (deviceContext == nullptr || scene.extent.IsEmpty() || - scene.extent.Width() <= 0.0 || scene.extent.Height() <= 0.0) - { - return E_INVALIDARG; - } - - const double availableWidth = static_cast(bounds.right - bounds.left - 2 * kMargin); - const double availableHeight = static_cast(bounds.bottom - bounds.top - 2 * kMargin); - if (availableWidth <= 0.0 || availableHeight <= 0.0) - { - return S_OK; - } - - const double scale = std::min( - availableWidth / scene.extent.Width(), - availableHeight / scene.extent.Height()); - if (!std::isfinite(scale) || scale <= 0.0) - { - return E_INVALIDARG; - } - - const double drawingWidth = scene.extent.Width() * scale; - const double drawingHeight = scene.extent.Height() * scale; - const double left = static_cast(bounds.left) + - (static_cast(bounds.right - bounds.left) - drawingWidth) / 2.0; - const double top = static_cast(bounds.top) + - (static_cast(bounds.bottom - bounds.top) - drawingHeight) / 2.0; - - const ScopedDcState savedState(deviceContext); - if (!savedState.IsValid()) - { - return E_FAIL; - } - - const ScopedGdiObject brush(CreateSolidBrush(kFillColor)); - const ScopedGdiObject pen(CreatePen(PS_SOLID, 1, kOutlineColor)); - if (brush.Get() == nullptr || pen.Get() == nullptr) - { - return E_OUTOFMEMORY; - } - - const ScopedSelection selectedBrush(deviceContext, brush.Get()); - const ScopedSelection selectedPen(deviceContext, pen.Get()); - if (!selectedBrush.IsValid() || !selectedPen.IsValid() || - SetPolyFillMode(deviceContext, ALTERNATE) == 0) + else { - return E_FAIL; + _diagnostic = L"GDI was selected by the rendering preference."; } - try - { - for (const rendering::Polygon& polygon : scene.polygons) - { - std::vector points; - std::vector ringCounts; - for (const rendering::Ring& ring : polygon) - { - if (ring.size() < 3) - { - continue; - } - - const std::size_t maximumPoints = - static_cast(std::numeric_limits::max()); - if (ring.size() > maximumPoints || - points.size() > maximumPoints - ring.size()) - { - return E_INVALIDARG; - } - - ringCounts.push_back(static_cast(ring.size())); - for (const rendering::Point& point : ring) - { - points.push_back(ToPoint(point, scene, scale, left, top)); - } - } - - if (!points.empty() && - PolyPolygon( - deviceContext, - points.data(), - ringCounts.data(), - static_cast(ringCounts.size())) == FALSE) - { - return E_FAIL; - } - } - } - catch (const std::bad_alloc&) + const HRESULT gdiResult = _gdiRenderer.Draw(deviceContext, bounds, scene); + if (SUCCEEDED(gdiResult)) { - return E_OUTOFMEMORY; + _activeBackend = VectorRenderBackendKind::Gdi; } - catch (const std::length_error&) + else { - return E_OUTOFMEMORY; + _diagnostic = L"The selected CPU renderer could not draw this frame."; } - return S_OK; + return gdiResult; } } diff --git a/src/MapWinGIS.ActiveX/VectorLayerRenderer.h b/src/MapWinGIS.ActiveX/VectorLayerRenderer.h index 640cf4d..ac95cea 100644 --- a/src/MapWinGIS.ActiveX/VectorLayerRenderer.h +++ b/src/MapWinGIS.ActiveX/VectorLayerRenderer.h @@ -2,21 +2,59 @@ /** * @file VectorLayerRenderer.h - * @brief Declares the initial GDI renderer for backend-neutral vector scenes. + * @brief Declares the backend coordinator for vector scene rendering. * - * The renderer paints polygon scene data into the ActiveX control's host - * drawing context and does not access vector datasets. + * Tries OpenGL rendering first and uses the GDI backend for unsupported + * geometry or when OpenGL cannot be initialized. */ #pragma once #include +#include +#include + +#include "GdiVectorLayerRenderer.h" +#include "OpenGlVectorLayerRenderer.h" +#include "VectorRenderBackend.h" #include "mapwingis/rendering/VectorRenderScene.h" namespace mwg::activex { - [[nodiscard]] HRESULT DrawVectorRenderScene( - HDC deviceContext, - const RECT& bounds, - const rendering::VectorRenderScene& scene) noexcept; + class VectorLayerRenderer final + { + public: + void SetPreference(VectorRenderBackendPreference preference) noexcept + { + _preference = preference; + } + + [[nodiscard]] VectorRenderBackendPreference GetPreference() const noexcept + { + return _preference; + } + + [[nodiscard]] HRESULT Draw( + HDC deviceContext, + const RECT& bounds, + const rendering::VectorRenderScene& scene) noexcept; + + [[nodiscard]] std::optional GetActiveBackend() const noexcept + { + return _activeBackend; + } + + [[nodiscard]] std::wstring_view GetDiagnostic() const noexcept + { + return _diagnostic; + } + + private: + OpenGlVectorLayerRenderer _openGlRenderer; + GdiVectorLayerRenderer _gdiRenderer; + VectorRenderBackendPreference _preference = + VectorRenderBackendPreference::Automatic; + std::optional _activeBackend; + std::wstring_view _diagnostic = L"Rendering has not been attempted."; + }; } diff --git a/src/MapWinGIS.ActiveX/VectorRenderBackend.h b/src/MapWinGIS.ActiveX/VectorRenderBackend.h new file mode 100644 index 0000000..93774ba --- /dev/null +++ b/src/MapWinGIS.ActiveX/VectorRenderBackend.h @@ -0,0 +1,42 @@ +// SPDX-License-Identifier: MPL-2.0 + +/** + * @file VectorRenderBackend.h + * @brief Defines the internal backend contract for vector scene drawing. + * + * Backends consume owned Core render scenes and draw them into a Windows + * device context without accessing datasets or COM interfaces. + */ +#pragma once + +#include + +#include "mapwingis/rendering/VectorRenderScene.h" + +namespace mwg::activex +{ + enum class VectorRenderBackendKind + { + OpenGL, + Gdi + }; + + enum class VectorRenderBackendPreference + { + Automatic, + OpenGL, + Gdi + }; + + class IVectorRenderBackend + { + public: + virtual ~IVectorRenderBackend() = default; + + /// Returns S_FALSE when the backend cannot render this scene or target. + [[nodiscard]] virtual HRESULT Draw( + HDC deviceContext, + const RECT& bounds, + const rendering::VectorRenderScene& scene) noexcept = 0; + }; +} diff --git a/src/MapWinGIS.Core/src/vector/VectorDataset.cpp b/src/MapWinGIS.Core/src/vector/VectorDataset.cpp index 5488506..fc0ffdd 100644 --- a/src/MapWinGIS.Core/src/vector/VectorDataset.cpp +++ b/src/MapWinGIS.Core/src/vector/VectorDataset.cpp @@ -209,7 +209,16 @@ namespace mwg const IgnoreAllButIds ignoreScope(*_layer, _fields); _featureIds.clear(); - _featureIds.reserve(static_cast(std::max(FeatureCount(), 0))); + + // Do not force a full count before scanning every feature for its + // ID. Some drivers implement GetFeatureCount(TRUE) by scanning the + // entire layer, which would make this index build perform two passes. + // Reserve only when the driver can provide a count without forcing it. + const GIntBig count = _layer->GetFeatureCount(FALSE); + if (count > 0 && std::cmp_less_equal(count, _featureIds.max_size())) + { + _featureIds.reserve(static_cast(count)); + } _layer->ResetReading(); while (const OGRFeatureUniquePtr feature{_layer->GetNextFeature()}) diff --git a/tests/MapWinGIS.Core.Tests/ActiveXActivationTests.cpp b/tests/MapWinGIS.Core.Tests/ActiveXActivationTests.cpp index 5d3e1db..fc29214 100644 --- a/tests/MapWinGIS.Core.Tests/ActiveXActivationTests.cpp +++ b/tests/MapWinGIS.Core.Tests/ActiveXActivationTests.cpp @@ -309,14 +309,53 @@ TEST(ActiveXActivation, CreatesControlThroughClassFactory) ASSERT_TRUE(SUCCEEDED(result)); EXPECT_EQ(GetPixel(surface.Get(), 79, 59), GetSysColor(COLOR_WINDOW)); - ComPtr activeXControl; + ComPtr originalInterface; + result = control.As(&originalInterface); + ASSERT_TRUE(SUCCEEDED(result)); + + ComPtr activeXControl; result = control.As(&activeXControl); ASSERT_TRUE(SUCCEEDED(result)); VARIANT_BOOL initialized = VARIANT_FALSE; - result = activeXControl->get_CoreInitialized(&initialized); + result = originalInterface->get_CoreInitialized(&initialized); ASSERT_TRUE(SUCCEEDED(result)); EXPECT_EQ(initialized == VARIANT_TRUE, mwg::GdalEnvironment::IsInitialized()); + + BSTR backendPreference{}; + result = activeXControl->get_RenderingBackendPreference(&backendPreference); + ASSERT_TRUE(SUCCEEDED(result)); + EXPECT_STREQ(backendPreference, L"Automatic"); + SysFreeString(backendPreference); + + backendPreference = SysAllocString(L"SoftwareOnly"); + ASSERT_NE(backendPreference, nullptr); + EXPECT_EQ( + activeXControl->put_RenderingBackendPreference(backendPreference), + E_INVALIDARG); + SysFreeString(backendPreference); + + backendPreference = SysAllocString(L"gdi"); + ASSERT_NE(backendPreference, nullptr); + result = activeXControl->put_RenderingBackendPreference(backendPreference); + SysFreeString(backendPreference); + ASSERT_TRUE(SUCCEEDED(result)); + result = activeXControl->get_RenderingBackendPreference(&backendPreference); + ASSERT_TRUE(SUCCEEDED(result)); + EXPECT_STREQ(backendPreference, L"GDI"); + SysFreeString(backendPreference); + + BSTR renderingBackend{}; + result = activeXControl->get_RenderingBackend(&renderingBackend); + ASSERT_TRUE(SUCCEEDED(result)); + EXPECT_STREQ(renderingBackend, L"Not rendered"); + SysFreeString(renderingBackend); + + BSTR renderingStatus{}; + result = activeXControl->get_RenderingStatus(&renderingStatus); + ASSERT_TRUE(SUCCEEDED(result)); + EXPECT_STREQ(renderingStatus, L"Rendering has not been attempted."); + SysFreeString(renderingStatus); } TEST(ActiveXHosting, ResizesRepaintsAndRecreatesControl) diff --git a/tests/MapWinGIS.Core.Tests/MapWinGIS.Core.Tests.vcxproj b/tests/MapWinGIS.Core.Tests/MapWinGIS.Core.Tests.vcxproj index 59e2b9f..a0fb7ef 100644 --- a/tests/MapWinGIS.Core.Tests/MapWinGIS.Core.Tests.vcxproj +++ b/tests/MapWinGIS.Core.Tests/MapWinGIS.Core.Tests.vcxproj @@ -41,7 +41,7 @@ - $(MwgRepoRoot)src\MapWinGIS.Core\include;$(MwgRepoRoot)obj\MapWinGIS.ActiveX\$(Configuration)\$(Platform);%(AdditionalIncludeDirectories) + $(MwgRepoRoot)src\MapWinGIS.Core\include;$(MwgRepoRoot)src\MapWinGIS.ActiveX;$(MwgRepoRoot)obj\MapWinGIS.ActiveX\$(Configuration)\$(Platform);%(AdditionalIncludeDirectories) Console @@ -62,6 +62,10 @@ + + + + diff --git a/tests/MapWinGIS.Core.Tests/VectorLayerRendererTests.cpp b/tests/MapWinGIS.Core.Tests/VectorLayerRendererTests.cpp new file mode 100644 index 0000000..a793b4b --- /dev/null +++ b/tests/MapWinGIS.Core.Tests/VectorLayerRendererTests.cpp @@ -0,0 +1,259 @@ +// SPDX-License-Identifier: MPL-2.0 + +/** + * @file VectorLayerRendererTests.cpp + * @brief Tests OpenGL rendering and the GDI fallback for vector scenes. + */ +#include + +#include + +#include +#include + +#include "OpenGlVectorLayerRenderer.h" +#include "VectorLayerRenderer.h" + +namespace +{ + class BitmapSurface final + { + public: + BitmapSurface(const int width, const int height) noexcept + { + _screen = GetDC(nullptr); + if (_screen == nullptr) + { + return; + } + + _memory = CreateCompatibleDC(_screen); + if (_memory == nullptr) + { + return; + } + + _bitmap = CreateCompatibleBitmap(_screen, width, height); + if (_bitmap == nullptr) + { + return; + } + + _previous = SelectObject(_memory, _bitmap); + } + + ~BitmapSurface() + { + if (_previous != nullptr && _previous != HGDI_ERROR) + { + SelectObject(_memory, _previous); + } + if (_bitmap != nullptr) + { + DeleteObject(_bitmap); + } + if (_memory != nullptr) + { + DeleteDC(_memory); + } + if (_screen != nullptr) + { + ReleaseDC(nullptr, _screen); + } + } + + BitmapSurface(const BitmapSurface&) = delete; + BitmapSurface& operator=(const BitmapSurface&) = delete; + + [[nodiscard]] bool IsValid() const noexcept + { + return _memory != nullptr && + _bitmap != nullptr && + _previous != nullptr && + _previous != HGDI_ERROR; + } + + [[nodiscard]] HDC Get() const noexcept { return _memory; } + + private: + HDC _screen{}; + HDC _memory{}; + HBITMAP _bitmap{}; + HGDIOBJ _previous{}; + }; + + [[nodiscard]] mwg::rendering::VectorRenderScene MakeConvexPolygonScene() + { + return { + mwg::Extent{0.0, 0.0, 10.0, 10.0}, + {{{{1.0, 1.0}, {9.0, 1.0}, {9.0, 9.0}, {1.0, 9.0}, {1.0, 1.0}}}}}; + } +} + +TEST(VectorLayerRenderer, UsesOpenGlForConvexPolygonWhenAvailable) +{ + BitmapSurface surface(120, 100); + ASSERT_TRUE(surface.IsValid()); + ASSERT_TRUE(PatBlt(surface.Get(), 0, 0, 120, 100, BLACKNESS)); + + const RECT bounds{0, 0, 120, 100}; + const mwg::rendering::VectorRenderScene scene = MakeConvexPolygonScene(); + + // Only an unavailable OpenGL target may skip; drawing, readback or + // presentation failures in the backend must fail the test. + mwg::activex::OpenGlVectorLayerRenderer openGlRenderer; + const HRESULT openGlResult = openGlRenderer.Draw(surface.Get(), bounds, scene); + if (openGlResult == S_FALSE) + { + GTEST_SKIP() << "No OpenGL context with framebuffer objects is available."; + } + ASSERT_EQ(openGlResult, S_OK); + EXPECT_EQ(GetPixel(surface.Get(), 60, 50), RGB(61, 122, 169)); + EXPECT_EQ(GetPixel(surface.Get(), 5, 5), GetSysColor(COLOR_WINDOW)); + + ASSERT_TRUE(PatBlt(surface.Get(), 0, 0, 120, 100, BLACKNESS)); + mwg::activex::VectorLayerRenderer renderer; + ASSERT_EQ(renderer.Draw(surface.Get(), bounds, scene), S_OK); + EXPECT_EQ( + renderer.GetActiveBackend(), + mwg::activex::VectorRenderBackendKind::OpenGL); + EXPECT_EQ(renderer.GetDiagnostic(), L"OpenGL rendered the frame successfully."); + EXPECT_EQ(GetPixel(surface.Get(), 60, 50), RGB(61, 122, 169)); + EXPECT_EQ(GetPixel(surface.Get(), 5, 5), GetSysColor(COLOR_WINDOW)); +} + +TEST(VectorLayerRenderer, OpenGlRejectsConcaveCornerHiddenByDuplicateVertex) +{ + BitmapSurface surface(120, 100); + ASSERT_TRUE(surface.IsValid()); + const RECT bounds{0, 0, 120, 100}; + + mwg::rendering::VectorRenderScene scene = MakeConvexPolygonScene(); + scene.polygons.front().front() = { + {0.0, 0.0}, {10.0, 0.0}, {10.0, 10.0}, {5.0, 5.0}, {5.0, 5.0}, {0.0, 10.0}, {0.0, 0.0}}; + + mwg::activex::OpenGlVectorLayerRenderer renderer; + EXPECT_EQ(renderer.Draw(surface.Get(), bounds, scene), S_FALSE); +} + +TEST(VectorLayerRenderer, OpenGlRejectsSelfIntersectingRing) +{ + BitmapSurface surface(120, 100); + ASSERT_TRUE(surface.IsValid()); + const RECT bounds{0, 0, 120, 100}; + + mwg::rendering::VectorRenderScene scene{ + mwg::Extent{-3.0, -3.0, 3.0, 3.0}, + {{{{0.0, 3.0}, {2.0, -3.0}, {-3.0, 1.0}, {3.0, 1.0}, {-2.0, -3.0}, {0.0, 3.0}}}}}; + + mwg::activex::OpenGlVectorLayerRenderer renderer; + EXPECT_EQ(renderer.Draw(surface.Get(), bounds, scene), S_FALSE); +} + +TEST(VectorLayerRenderer, FailsWithoutDrawingNonFiniteCoordinates) +{ + BitmapSurface surface(120, 100); + ASSERT_TRUE(surface.IsValid()); + ASSERT_TRUE(PatBlt(surface.Get(), 0, 0, 120, 100, BLACKNESS)); + const RECT bounds{0, 0, 120, 100}; + + mwg::rendering::VectorRenderScene scene = MakeConvexPolygonScene(); + scene.polygons.push_back( + {{{1.0, 1.0}, {std::numeric_limits::quiet_NaN(), 5.0}, {9.0, 9.0}, {1.0, 1.0}}}); + + mwg::activex::VectorLayerRenderer renderer; + EXPECT_EQ(renderer.Draw(surface.Get(), bounds, scene), E_INVALIDARG); + EXPECT_FALSE(renderer.GetActiveBackend().has_value()); + EXPECT_EQ(GetPixel(surface.Get(), 60, 50), RGB(0, 0, 0)); +} + +TEST(VectorLayerRenderer, UsesGdiForPolygonWithInteriorRing) +{ + BitmapSurface surface(120, 100); + ASSERT_TRUE(surface.IsValid()); + ASSERT_TRUE(PatBlt(surface.Get(), 0, 0, 120, 100, BLACKNESS)); + const RECT bounds{0, 0, 120, 100}; + ASSERT_NE( + FillRect(surface.Get(), &bounds, GetSysColorBrush(COLOR_WINDOW)), + 0); + + mwg::rendering::VectorRenderScene scene = MakeConvexPolygonScene(); + scene.polygons.front().front() = { + {0.0, 0.0}, {10.0, 0.0}, {10.0, 10.0}, {0.0, 10.0}, {0.0, 0.0}}; + scene.polygons.front().push_back( + {{3.0, 3.0}, {3.0, 7.0}, {7.0, 7.0}, {7.0, 3.0}, {3.0, 3.0}}); + mwg::activex::VectorLayerRenderer renderer; + ASSERT_EQ(renderer.Draw(surface.Get(), bounds, scene), S_OK); + + EXPECT_EQ( + renderer.GetActiveBackend(), + mwg::activex::VectorRenderBackendKind::Gdi); + EXPECT_EQ( + renderer.GetDiagnostic(), + L"The scene uses geometry that the OpenGL backend does not support."); + EXPECT_EQ(GetPixel(surface.Get(), 30, 50), RGB(61, 122, 169)); + EXPECT_EQ(GetPixel(surface.Get(), 60, 50), GetSysColor(COLOR_WINDOW)); +} + +TEST(VectorLayerRenderer, HonorsCpuPreferenceAndReportsTheSelectedBackend) +{ + BitmapSurface surface(120, 100); + ASSERT_TRUE(surface.IsValid()); + const RECT bounds{0, 0, 120, 100}; + const mwg::rendering::VectorRenderScene scene = MakeConvexPolygonScene(); + mwg::activex::VectorLayerRenderer renderer; + renderer.SetPreference(mwg::activex::VectorRenderBackendPreference::Gdi); + + ASSERT_EQ(renderer.Draw(surface.Get(), bounds, scene), S_OK); + + EXPECT_EQ(renderer.GetPreference(), mwg::activex::VectorRenderBackendPreference::Gdi); + EXPECT_EQ(renderer.GetActiveBackend(), mwg::activex::VectorRenderBackendKind::Gdi); + EXPECT_EQ(renderer.GetDiagnostic(), L"GDI was selected by the rendering preference."); +} + +TEST(VectorLayerRenderer, FallsBackToCpuWhenOpenGlStagingBudgetIsExceeded) +{ + BitmapSurface surface(120, 100); + ASSERT_TRUE(surface.IsValid()); + const RECT bounds{0, 0, 5000, 5000}; + const mwg::rendering::VectorRenderScene scene = MakeConvexPolygonScene(); + mwg::activex::VectorLayerRenderer renderer; + + ASSERT_EQ(renderer.Draw(surface.Get(), bounds, scene), S_OK); + + EXPECT_EQ(renderer.GetActiveBackend(), mwg::activex::VectorRenderBackendKind::Gdi); + EXPECT_EQ( + renderer.GetDiagnostic(), + L"The OpenGL frame exceeds the 64 MiB CPU staging-buffer budget."); +} + +TEST(VectorLayerRenderer, AppliesDetectedFramebufferLimitWithoutRequiringOpenGl) +{ + std::wstring_view rejectionReason; + + EXPECT_TRUE(mwg::activex::OpenGlVectorLayerRenderer::IsTargetWithinLimits( + 1280, + 720, + 4096, + 4096, + rejectionReason)); + EXPECT_TRUE(rejectionReason.empty()); + + EXPECT_FALSE(mwg::activex::OpenGlVectorLayerRenderer::IsTargetWithinLimits( + 2048, + 720, + 1024, + 4096, + rejectionReason)); + EXPECT_EQ( + rejectionReason, + L"The OpenGL target exceeds the detected maximum framebuffer or viewport size."); + + // A viewport limit smaller than the renderbuffer limit must also reject. + EXPECT_FALSE(mwg::activex::OpenGlVectorLayerRenderer::IsTargetWithinLimits( + 1024, + 900, + 4096, + 800, + rejectionReason)); +}