diff --git a/CLAUDE.md b/CLAUDE.md index 5f4429f..e2325ed 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -46,6 +46,7 @@ Source layout under `src/OrthoStreamXP/`. Sub-folders are for navigation only: * - `Textures/` — imagery to DDS: `TextureBuilder` (fetch → stitch → resize → sharpen → mipmaps → BC1 encode → atomic write; SkiaSharp is decode-only), `TextureQuality`, `Images`, `Sharpening` (unsharp mask on brightness, not a setting: 100 % for the areas' textures below ZL18, 60 % for the airports' ZL18 and finer) at the root; `Tiles/` (`TileSource`/`TileStore`: download + cache; the low-zoom base is zoom 13 and coarser because Bing's zoom 12 is other, lighter imagery; a tile every provider definitively lacks throws `TileNotAvailableException`, and `TextureBuilder` then makes it from a parent at hand, never coarser than 13), `Dds/` (`Dds` layout/encode/decode; mip levels by `MipFilter` = 2x2 averages in linear light; BC1 by `IspcBc1` = Intel's ISPC `ispc_texcomp.dll` from `native/ispc_texcomp/` (checked in, rebuilt by its `build.ps1`), loaded from the exe's folder, with one-colour blocks and four-colour mode fixed after it and every other block's colours refined by least squares (`Bc1Refinement`); `Dds.EncodeRangeFit` is the fallback without the DLL), `Scheduling/` (priority gates), `Seasons/` (`SeasonModel` calendar, `ObservedSeason` + `GreennessYear`: grass and fields by a place's yearly NDVI against its greenest month, trees by the calendar), `Vegetation/` (`VegetationSource`: NASA GIBS monthly VIIRS NDVI, downloaded and kept under the low-zoom base; `VegetationTile`, `NdviPalette`), `Colour/` (`Exposure`, `Contrast` (fixed 60 % S-curve, always on, not a setting), `ColourTable` = the shared BC1 lookup-table recolouring, `PhotoColours` = season → contrast → exposure as one table (rounded to 565 once) applied as X-Plane reads, also used by the Settings preview). - `Setup/` — `Settings/` (`SettingsDocument`, ini under `%LOCALAPPDATA%\OrthoStreamXP`, `QualityPreset`, `ConnectionTest`), `Cache/` (inventory, areas, eviction), `Packages/` (downloads AutoOrtho's mesh regions from GitHub into the packages folder as `OrthoStream_*` packages: `MeshCatalog`, `AssetDownload`, `ZipUnpacker`, `OverlayPackage`, `RegionInstaller`; the tiles AutoOrtho lacks come from `flysimdev/orthostreamxp-scenery`'s latest-release `supplements.json` (`SupplementCatalog`, `RegionSupplement`) and are merged into their region without replacing any file, at install or, for regions installed before, by `Gui/Packages/SupplementUpdater` at each window start), `Airports/` (the Airports page's flattening, one airport at a time: `AptDatReader` lists the airports of an apt.dat, `AirportSources` + `AirportCatalog` pick each ident from the highest enabled package in scenery_packs.ini (`*GLOBAL_AIRPORTS*` = Global Scenery\Global Airports), `FlattenedAirports` keeps a copy of each flattened airport with `1302 flatten 1` in its own `Custom Scenery\OrthoStreamXP Flattened Airports` package listed above the airport's source; the source files are never changed, Undo removes the copy and the last one removes the package), `Installation/` (`AppPaths`, `AppUpdates`, `LegacyNames` migrating older settings/cache locations, `SystemCheck`, Velopack hooks). - `Tuning/` — flight reports, facts and the preset/setting recommendations. +- Packages page — two tabs: "Build own packages" (`BuildSceneryView`, first and open at the start) and "Download kubilus1 packages" (`PackagesViewModel`, AutoOrtho's mesh regions), held by `Gui/ViewModels/PackagesPageViewModel`. The Build tab makes photo-terrain packages made from X-Plane's own Global Scenery, named `OrthoGlobal__XP` and `OrthoGlobal_Overlays_XP` unlike the downloaded `OrthoStream_*` regions (`GlobalScenery` reads `X-Plane 12 Global Scenery` and `X-Plane 12 Demo Areas`, a tile in both from the former) by OrthoGlobalXP's engine, `lib/OrthoGlobalXP.Core/OrthoGlobalXP.Core.dll` (compiled and checked in by its `build.ps1` from the sibling OrthoGlobalXP repo; needs the `SharpCompress` package at the engine's version). `Gui/ViewModels/BuildSceneryViewModel` drives `PackageBuilder`; the map is `Gui/Map/TileMapView` (Web Mercator over OpenStreetMap, `StreetMapTiles` cached in `%LOCALAPPDATA%\OrthoStreamXP\osm`) with `TileMapModel`; `Gui/Building/RegionSearch` picks by region or country; how tiles are made is fixed, not a choice (ZL16, ZL18 within 2 km of runways, roads kept, DSFs packed, no .ter files, up-to-date tiles skipped: `SceneryBuildPreferences.ToPackageOptions`); the page's choices (target folder, map layers, picked tiles) are `Setup/Building/SceneryBuildPreferences`, kept in `scenery-build.json`. - Logs go to `%LOCALAPPDATA%\OrthoStreamXP\logs`. diff --git a/README.md b/README.md index 497c90a..edb8857 100644 --- a/README.md +++ b/README.md @@ -23,6 +23,7 @@ OrthoStreamXP will always be free. If it has given you a flight worth rememberin Traditional photo scenery often requires downloading and building large areas before you can use them. OrthoStreamXP takes a different approach. - **Scenery on demand** — download imagery as X-Plane needs it, instead of preparing entire regions in advance. +- **Scenery packages for anywhere** — pick the areas you fly on a map, and OrthoStreamXP builds their packages from X-Plane's own Global Scenery in seconds per tile, with no mesh to download. - **Less disk space wasted** — keep the areas you fly and automatically remove older scenery when your cache reaches its limit. - **Better scenery ahead** — OrthoStreamXP follows your aircraft and downloads upcoming areas before you reach them. - **Simple quality settings** — choose Balanced, Sharp, Ultra, or Extra without learning dozens of technical parameters. @@ -33,7 +34,7 @@ Traditional photo scenery often requires downloading and building large areas be - **Towns lit at night** — optionally give the photo scenery street lamps and the light of the houses along X-Plane's roads, so towns glow after dark as on X-Plane's own scenery. You can also skip the detailed photos at night to save downloads, keeping the lights. - **Exposure and a live preview** — tone down photos that look too bright next to X-Plane's own scenery, and see any colour change on a photo from your cache before you fly. - **See what happened during your flight** — review download performance, scenery loading, and your flight route. -- **Your scenery list, without Notepad** — switch X-Plane's scenery packages on or off and drag them into order on the X-Plane Custom Scenery page, and leave any of your photo scenery packages out of a flight with one switch on the Home page. +- **Your scenery list, without Notepad** — switch X-Plane's scenery packages on or off and drag them into order on the X-Plane Custom Scenery page (with a search box for long lists), and leave any of your photo scenery packages out of a flight with one switch on the Home page. - **Level airports** — an airport that sits on a bump or in a hollow of the photo scenery's ground can be flattened on the Airports page, one at a time, without changing the airport's own files. Undo puts it back. ### Designed for everyday flying @@ -53,17 +54,18 @@ Before installing OrthoStreamXP, make sure you have: - **Windows 10 or 11 (64-bit)** - **X-Plane 12** - **WinFsp**, a free Windows component used to make the streamed scenery available to X-Plane. The setup process checks for it and provides a download link. -- **Scenery packages** for the regions you want to fly over: a region's mesh downloaded from within OrthoStreamXP, or your own. +- **Scenery packages** for the regions you want to fly over: built in OrthoStreamXP from X-Plane's own Global Scenery, a region's mesh downloaded from within OrthoStreamXP, or your own. - **An internet connection** for downloading new scenery. - **Disk space for the scenery cache** — 25 GB is a reasonable starting point; more space lets you keep more areas available. - A graphics card with enough memory for your chosen quality preset. The installer also installs the .NET 10 desktop runtime if it is missing. -**Important:** OrthoStreamXP streams imagery onto scenery packages; it does not create terrain meshes itself. There are two ways to get them: +**Important:** OrthoStreamXP streams imagery onto scenery packages. There are three ways to get them: -1. **Download a region from within OrthoStreamXP:** a whole region's mesh (Europe, North America, ...), during setup or later from the **Packages** page. The few tiles AutoOrtho's collection lacks (around Portland, Oregon, and in Tonga) are added to their region from [OrthoStreamXP's own collection](https://github.com/flysimdev/orthostreamxp-scenery). -2. **Use your own packages:** compatible packages can come from tools such as Ortho4XP, OrthoStudio XP, AutoOrtho, and XPME. You can select an existing package folder during setup. +1. **Build your own from X-Plane's Global Scenery:** pick the areas you fly on a map, during setup or later on the **Packages** page, and OrthoStreamXP makes their packages on your PC in a few seconds per tile, keeping X-Plane's relief, water, roads, forests and buildings. Nothing to download but the photos. +2. **Download a region from within OrthoStreamXP:** a whole region's mesh (Europe, North America, ...) from the **Packages** page. The few tiles AutoOrtho's collection lacks (around Portland, Oregon, and in Tonga) are added to their region from [OrthoStreamXP's own collection](https://github.com/flysimdev/orthostreamxp-scenery). +3. **Use your own packages:** compatible packages can come from tools such as Ortho4XP, OrthoStudio XP, AutoOrtho, and XPME. You can select an existing package folder during setup. ## Installation @@ -128,7 +130,7 @@ Choose **Satellite** as the season to colour the grass and fields by NASA's sate OrthoStreamXP is currently in beta. Please keep the following in mind: - **Windows only:** the application depends on WinFsp. -- **Scenery packages are required:** download a region's mesh (6 to 33 GB per region) from the Packages page, or bring your own. +- **Scenery packages are required:** build them from X-Plane's Global Scenery on the Packages page, download a region's mesh (6 to 33 GB per region) there, or bring your own. - **Internet required for new areas:** scenery loads from the internet on first use; subsequent flights can reuse cached imagery. - **Imagery varies by location:** quality, capture date, colours, and transitions between imagery sources may differ. - **Performance depends on your setup:** connection speed, disk performance, and graphics memory affect the experience. diff --git a/docs/OrthoStreamXP-UserGuide.pdf b/docs/OrthoStreamXP-UserGuide.pdf index 2ce13a8..ada703a 100644 Binary files a/docs/OrthoStreamXP-UserGuide.pdf and b/docs/OrthoStreamXP-UserGuide.pdf differ diff --git a/docs/README.md b/docs/README.md index 828b68a..a9361f0 100644 --- a/docs/README.md +++ b/docs/README.md @@ -11,7 +11,7 @@ OrthoStreamXP adds real-world aerial photos to your X-Plane 12 scenery while you 3. [Flying](flying.md): the start order, the Home page, and the report you get after each flight. 4. [Settings](settings.md): quality and ground detail, folders, downloads, colours, seasons and exposure, night lights and photos at night. 5. [Cache](cache.md): how much disk space the scenery uses and how to free it. -6. [Packages](packages.md): downloading the ground mesh of a whole region, the quickest way to get scenery packages. +6. [Packages](packages.md): building scenery packages from X-Plane's own Global Scenery, or downloading the ground mesh of a whole region. 7. [X-Plane Custom Scenery](custom-scenery.md): switching X-Plane's scenery packages on or off and changing their order. 8. [Airports](airports.md): levelling the ground under an airport that sits on a bump or in a hollow, and undoing it. 9. [Troubleshooting](troubleshooting.md): common problems, the log, updates, uninstalling and reporting a bug. @@ -20,7 +20,7 @@ OrthoStreamXP adds real-world aerial photos to your X-Plane 12 scenery while you ## The short version 1. Install [WinFsp](https://winfsp.dev/rel/), then OrthoStreamXP, then restart your computer. -2. Open OrthoStreamXP and finish the setup: X-Plane folder, scenery packages (download a region there, or choose the folder of your own), cache folder, quality. +2. Open OrthoStreamXP and finish the setup: X-Plane folder, scenery packages (build your own there from X-Plane's Global Scenery, or choose the folder of your own), cache folder, quality. 3. Every time you fly, click **Start and fly** in OrthoStreamXP. It starts the scenery first and then X-Plane. 4. Load a flight. A new area takes a few minutes the first time; after that it comes from the cache. diff --git a/docs/faq.md b/docs/faq.md index e38a5cb..346c95c 100644 --- a/docs/faq.md +++ b/docs/faq.md @@ -14,11 +14,11 @@ It is free and open source, and it goes up to imagery zoom level 19 (the **Extra ### Does it make the terrain (the mesh) too? -No, OrthoStreamXP does not make the mesh: it provides the photos. The mesh, the water masks and the coastlines come from scenery packages. Download a whole region's mesh in OrthoStreamXP itself (see [Packages](packages.md)), or use packages you already have, made by Ortho4XP, OrthoStudio XP, AutoOrtho or XPME. See [Installation › What you need](installation.md#what-you-need). +It can. The mesh, the water masks and the coastlines come from scenery packages, and OrthoStreamXP can build them for you from X-Plane's own Global Scenery: pick the areas on the **Packages** page's **Build own packages** tab (see [Packages › Build own packages](packages.md#build-own-packages)). You can also download a whole region's mesh there, or use packages you already have, made by Ortho4XP, OrthoStudio XP, AutoOrtho or XPME. See [Installation › What you need](installation.md#what-you-need). -### Why can't it use the mesh from X-Plane's default scenery? +### Can it use the mesh from X-Plane's default scenery? -Each scenery file (`.dsf`) says exactly which photo texture goes on which part of the ground. X-Plane's default scenery uses generic land textures, not photos, so there is nothing for OrthoStreamXP to put the photos on. Packages made by Ortho4XP and the tools based on it have that layout, so OrthoStreamXP can fill in their photos. +Yes, through the packages it builds. Each scenery file (`.dsf`) says exactly which texture goes on which part of the ground, and X-Plane's default scenery uses generic land textures, not photos, so OrthoStreamXP cannot stream onto it as it is. **Build own packages** makes a copy of each tile you pick, with X-Plane's own relief, water and coastlines, whose ground uses photo textures instead. X-Plane's Global Scenery itself is only read, never changed. ### What is the difference from AutoOrtho or XPME? diff --git a/docs/first-setup.md b/docs/first-setup.md index ccc13ce..97c5c32 100644 --- a/docs/first-setup.md +++ b/docs/first-setup.md @@ -25,19 +25,19 @@ If yours is not listed, click **Choose another folder…** and choose the folder ## 3. Scenery -OrthoStreamXP adds the photos to **scenery packages**: the ground of an area, the shape of the terrain cut in 1° squares. There are two ways to get them. +OrthoStreamXP adds the photos to **scenery packages**: the ground of an area, the shape of the terrain cut in 1° squares. There are two ways to get them here. -### Option 1: download a region in OrthoStreamXP +### Option 1: build your own packages -The simplest way, if you have no scenery packages yet. Under **No scenery packages yet?**, click **Download a region…**. If you already chose a folder without packages, the hint turns red and **Download a region now** opens the same list. +The simplest way, if you have no scenery packages yet. OrthoStreamXP makes them from X-Plane's own Global Scenery, here on your PC. Under **No scenery packages yet?**, click **Build your own packages…**. If you already chose a folder without packages, the hint turns red and says *No packages yet? Build your own below.* ![Setup step 3: a folder without scenery packages](images/setup-scenery-empty.png) -The list of regions opens: click **Install** next to the region you fly in. The progress shows under it, and you can stop and resume the download. When it finishes, the region's folder is chosen as your scenery packages folder and **Next** becomes available. +A map of the world opens, the same as on the **Packages** page's **Build own packages** tab. Pick the areas you fly, by name under **Pick by region or country** or by clicking tiles on the map, and click **Build the picked tiles**. Each tile takes a few seconds. When the build ends, the folder the packages were built in is chosen as your scenery packages folder and **Next** becomes available. **Stream from here** chooses it straight away. -![Setup step 3: the regions to download](images/setup-scenery-download.png) +![Setup step 3: building your own packages](images/setup-scenery-build.png) -See [Packages](packages.md) for the sizes, the roads, forests and buildings, and how to update or delete a region later. You can download more regions at any time on the **Packages** page. +See [Packages › Build own packages](packages.md#build-own-packages) for picking the tiles, the packages' names and building more later. To download a whole region's mesh instead, finish the setup with the folder you want for it, and use the **Packages** page's **Download kubilus1 packages** tab (see [Packages › Download kubilus1 packages](packages.md#download-kubilus1-packages)). ### Option 2: use your own scenery packages diff --git a/docs/images/packages-build.png b/docs/images/packages-build.png new file mode 100644 index 0000000..25adfec Binary files /dev/null and b/docs/images/packages-build.png differ diff --git a/docs/images/packages.png b/docs/images/packages.png index d7feb6b..5efb30e 100644 Binary files a/docs/images/packages.png and b/docs/images/packages.png differ diff --git a/docs/images/setup-scenery-build.png b/docs/images/setup-scenery-build.png new file mode 100644 index 0000000..6a2181c Binary files /dev/null and b/docs/images/setup-scenery-build.png differ diff --git a/docs/images/setup-scenery-download.png b/docs/images/setup-scenery-download.png deleted file mode 100644 index cdf5421..0000000 Binary files a/docs/images/setup-scenery-download.png and /dev/null differ diff --git a/docs/images/setup-scenery.png b/docs/images/setup-scenery.png index f1eba93..54baab1 100644 Binary files a/docs/images/setup-scenery.png and b/docs/images/setup-scenery.png differ diff --git a/docs/installation.md b/docs/installation.md index ae1cc79..07a5db8 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -6,9 +6,10 @@ - **Windows 10 or 11 (64-bit).** - **X-Plane 12.** -- **Scenery packages** for the regions you fly: the terrain (the mesh) that OrthoStreamXP adds the photos to. Two ways to get them: - 1. **Download a region in OrthoStreamXP**, during the setup or later on the **Packages** page (Europe, North America...). Nothing to prepare beforehand; see [Packages](packages.md). - 2. **Use your own.** Packages made by Ortho4XP, OrthoStudio XP, AutoOrtho or XPME work. Each package is a folder that contains an `Earth nav data` folder. Put all of them in **one parent folder**, for example: +- **Scenery packages** for the regions you fly: the terrain (the mesh) that OrthoStreamXP adds the photos to. Three ways to get them: + 1. **Build your own in OrthoStreamXP** from X-Plane's Global Scenery, during the setup or later on the **Packages** page: pick the areas on a map, and each tile is built in a few seconds. See [Packages › Build own packages](packages.md#build-own-packages). + 2. **Download a region in OrthoStreamXP** on the **Packages** page (Europe, North America...); see [Packages › Download kubilus1 packages](packages.md#download-kubilus1-packages). + 3. **Use your own.** Packages made by Ortho4XP, OrthoStudio XP, AutoOrtho or XPME work. Each package is a folder that contains an `Earth nav data` folder. Put all of them in **one parent folder**, for example: ``` D:\OrthoPackages\ diff --git a/docs/packages.md b/docs/packages.md index fe314bf..3a978fb 100644 --- a/docs/packages.md +++ b/docs/packages.md @@ -2,9 +2,66 @@ [User guide](README.md) › Packages -OrthoStreamXP streams photos onto scenery packages: the ground's shape (the mesh) for each area. The quickest way to get them is to download the mesh of a whole region, on the **Packages** page or in the **Scenery packages** step of the setup. You can also use packages of your own; keep them in a folder of their own (see [One folder per source](#one-folder-per-source)). +OrthoStreamXP streams photos onto scenery packages: the ground's shape (the mesh) for each area. The **Packages** page has two ways to get them, one on each tab: -![The Packages page: five regions installed, Asia's download stopped part-way](images/packages.png) +- **Build own packages** (the first tab): make packages for any part of the world from X-Plane's own Global Scenery, here on your PC. Nothing is downloaded to build them. +- **Download kubilus1 packages**: download the mesh of a whole region (Europe, North America...) made by AutoOrtho's author. + +You can also use packages of your own. Whichever you use, keep each source in a folder of its own (see [One folder per source](#one-folder-per-source)). + +## Build own packages + +![The Build own packages tab: 24 tiles picked on the map, all of them built](images/packages-build.png) + +The packages are made from the Global Scenery installed with your X-Plane (the `X-Plane 12 Global Scenery` and `X-Plane 12 Demo Areas` folders). It is only read, never changed. Each 1° tile keeps X-Plane's relief, water and coastlines; its ground gets the photo textures, with finer photos near the runways, and X-Plane's roads, forests and buildings go into an overlay package beside it. A tile takes a few seconds to build. The line under the page's introduction says how many tiles your X-Plane has; choose your X-Plane folder in [Settings › Folders](settings.md#folders) first if it asks for it. + +### Scenery packages folder + +The card at the top shows the folder the packages are built in. It is your scenery packages folder (see [Settings › Folders](settings.md#folders)) unless you choose another. + +- **Choose…** picks another folder to build in. +- **Open** opens the folder in Explorer. +- **Stream from here** makes this folder your scenery packages folder, so OrthoStreamXP streams the packages built in it. It shows only while the folder is a different one, and works while OrthoStreamXP is stopped. Until then the card warns that *OrthoStreamXP will not stream the packages built here*. + +Keep this folder for the built packages only: don't build them into a folder with downloaded regions or packages from other tools (see [One folder per source](#one-folder-per-source)). + +The packages are named after their continent and end in `_XP` (made from X-Plane's own scenery), so you can tell them from the downloaded regions (`OrthoStream_Eur`...). One overlay package holds the roads, forests and buildings of them all: + +| Continent | Package | +|---|---| +| Europe | `OrthoGlobal_Europe_XP` | +| North America | `OrthoGlobal_NorthAmerica_XP` | +| South America | `OrthoGlobal_SouthAmerica_XP` | +| Africa | `OrthoGlobal_Africa_XP` | +| Asia | `OrthoGlobal_Asia_XP` | +| Australia and the Pacific | `OrthoGlobal_AustraliaPacific_XP` | +| Roads, forests and buildings | `OrthoGlobal_Overlays_XP` | + +### Picking the tiles + +Only the tiles your X-Plane has scenery for can be picked; tiles of open sea cannot. + +- **Pick by region or country:** type a continent, subregion, country, region or state, such as *Germany*, *Bavaria* or *Western Europe*, choose it in the list and click **Pick** (or press Enter). Every tile it touches that X-Plane has scenery for is picked, borders included, and the map shows them. **Unpick** drops its tiles again. +- **On the map:** click a tile to pick or drop it, Shift+drag to pick a rectangle, Ctrl+drag to drop one. Drag to move the map and scroll to zoom. Zoomed in, the runways and the finer textures around them show. The buttons at the bottom right zoom in, zoom out and show the picked tiles. +- **Clear** drops every picked tile. + +The legend at the top of the map shows the tiles **In X-Plane** (outlined), **Picked**, **Built**, **Building** and **Failed**, and the **Airports**. Hovering over a tile names it, says whether it is built, and names the package it goes into. Under the map, **OpenStreetMap** shows the map's streets under the tiles (downloaded as you look, kept for two weeks), and **City names** names the cities. + +The page remembers the picked tiles for the next start. + +### Building + +Click **Build the picked tiles**. The progress bar and the line beside the buttons show how far it is, and the tiles turn from **Building** to **Built** on the map. The list below the map logs each tile, and the same lines go to OrthoStreamXP's log. + +- **Stop** ends the build. The tiles already built are kept. If you close the window during a build, OrthoStreamXP asks first, and keeps them too. +- **Building again** skips the tiles that are already up to date, so you can add more areas at any time. +- **While OrthoStreamXP runs**, you can build, but the new tiles are streamed from its next start: stop and start OrthoStreamXP, with X-Plane closed. + +The packages are made from your own X-Plane installation and are not for redistribution. + +## Download kubilus1 packages + +![The Download kubilus1 packages tab: the regions to download, with their sizes](images/packages.png) The meshes are downloaded from a public collection on [GitHub](https://github.com/kubilus1/autoortho-scenery). Six regions are offered: @@ -19,7 +76,7 @@ The meshes are downloaded from a public collection on [GitHub](https://github.co The page shows the exact sizes of the current release. -## Tiles AutoOrtho lacks +### Tiles AutoOrtho lacks AutoOrtho's collection is missing a few tiles, for example 9 in Oregon, around Portland and along the coast (North America) and one in Tonga (Australia and the Pacific). OrthoStreamXP keeps these tiles in [its own collection](https://github.com/flysimdev/orthostreamxp-scenery). @@ -32,42 +89,22 @@ It adds them to the region they belong to, so there is no extra package: - **Until they are added**, the region shows **Update available** with the number of tiles, and **Update** downloads only those (about 225 MB for North America, about 2 MB for Australia and the Pacific), even while OrthoStreamXP runs. -The region's details on the **Packages** page list these tiles, for example *+ 9 tiles AutoOrtho lacks, from OrthoStreamXP*. +The region's details on the **Download kubilus1 packages** tab list these tiles, for example *+ 9 tiles AutoOrtho lacks, from OrthoStreamXP*. These tiles never replace a file of AutoOrtho's. If they cannot be downloaded, the region is installed without them, and they are added at a later start. -## Where they go +### Where they go -Each region is installed as a package of its own in the **scenery packages folder** chosen in [Settings › Folders](settings.md#folders). If you download one during the setup and have not chosen a folder yet, it goes to `OrthoStreamXP\Base Packages` in your user folder, and that folder becomes your scenery packages folder. +Each region is installed as a package of its own in the **scenery packages folder** chosen in [Settings › Folders](settings.md#folders), shown at the top of the tab. **Open the folder** opens it in Explorer, and **Refresh** reads the folder and the list of releases again. Before you download a region, check that it is your folder for downloaded regions, not your own packages' folder or the one you build packages in. Don't have one yet? Choose a new, empty folder in [Settings › Folders](settings.md#folders), then install. Home warns that no scenery packages were found until the first region is in it. Leave about 1.7 times the download size free on the drive: the files take more room once they are unpacked. -## One folder per source - -Keep the downloaded regions in a folder of their own, and the packages of each other tool (Ortho4XP, OrthoStudio XP, XPME, AutoOrtho) in theirs. For example: - -``` -D:\Scenery\OrthoStream\ <- the regions downloaded in OrthoStreamXP -D:\Scenery\Ortho4XP\ <- your Ortho4XP tiles -D:\Scenery\OrthoStudio\ <- your OrthoStudio XP packages -``` - -Why: - -- **No doubled scenery.** A downloaded region covers a whole continent. Packages from two sources for the same area bring two meshes, and often two sets of roads, forests and buildings, which can show twice. -- **Each tool keeps its own folder.** Ortho4XP, OrthoStudio XP and the others update and delete their packages in their folders. Mixed with packages from elsewhere, it is easy to delete or overwrite the wrong one, and hard to tell which tool a package (and a problem with it) comes from. -- **Easy to switch.** To fly with another source, choose its folder in [Settings › Folders](settings.md#folders), with the scenery stopped. Your packages stay as they are, and each keeps its textures in the cache. - -OrthoStreamXP uses one scenery packages folder at a time, so you fly with one source at a time. - -The **Packages** page installs into the folder chosen at that moment, shown at the top of the page; **Open the folder** opens it in Explorer, and **Refresh** reads the folder and the list of releases again. Before you download a region, check that it is your folder for downloaded regions, not your own packages' folder. Don't have one yet? Choose a new, empty folder in [Settings › Folders](settings.md#folders), then install. Home warns that no scenery packages were found until the first region is in it. - -## Roads, forests and buildings +### Roads, forests and buildings A square of a downloaded mesh no longer shows X-Plane's own roads, forests and buildings. **Roads, forests and buildings** downloads them with each region, into one shared package, `OrthoStream_Overlays`. Turn it off if another package of yours already brings them. The choice applies to the next region you install or update. -## Downloading, stopping and resuming +### Downloading, stopping and resuming ![Asia downloading, with its progress and speed](images/packages-downloading.png) @@ -80,4 +117,23 @@ A square of a downloaded mesh no longer shows X-Plane's own roads, forests and b You can install a new region while OrthoStreamXP runs. Updating or deleting a region needs OrthoStreamXP stopped, because X-Plane has its files open while it runs. Adding the tiles AutoOrtho lacks is the exception: it only adds files, so it works while OrthoStreamXP runs. +## One folder per source + +Keep the packages you build in a folder of their own, the downloaded regions in another, and the packages of each other tool (Ortho4XP, OrthoStudio XP, XPME, AutoOrtho) in theirs. For example: + +``` +D:\Scenery\OrthoGlobal\ <- the packages built in OrthoStreamXP +D:\Scenery\OrthoStream\ <- the regions downloaded in OrthoStreamXP +D:\Scenery\Ortho4XP\ <- your Ortho4XP tiles +D:\Scenery\OrthoStudio\ <- your OrthoStudio XP packages +``` + +Why: + +- **No doubled scenery.** Packages from two sources for the same area bring two meshes, and often two sets of roads, forests and buildings, which can show twice. A downloaded region covers a whole continent, so it overlaps any package you build there. +- **Each tool keeps its own folder.** Ortho4XP, OrthoStudio XP and the others update and delete their packages in their folders. Mixed with packages from elsewhere, it is easy to delete or overwrite the wrong one, and hard to tell which tool a package (and a problem with it) comes from. +- **Easy to switch.** To fly with another source, choose its folder in [Settings › Folders](settings.md#folders) (or click **Stream from here** on the **Build own packages** tab), with the scenery stopped. Your packages stay as they are, and each keeps its textures in the cache. + +OrthoStreamXP uses one scenery packages folder at a time, so you fly with one source at a time. + Next: [X-Plane Custom Scenery](custom-scenery.md) diff --git a/docs/settings.md b/docs/settings.md index 7245a68..e9aa00a 100644 --- a/docs/settings.md +++ b/docs/settings.md @@ -92,7 +92,7 @@ Your scenery packages are not changed: OrthoStreamXP adjusts the terrain files a ![Settings: Folders](images/settings-folders.png) - **X-Plane folder:** the X-Plane installation where the packages appear (in its `Custom Scenery` folder). -- **Scenery packages folder:** the parent folder of your packages. The line below it lists the packages found. Keep the packages of each source (regions downloaded in OrthoStreamXP, Ortho4XP, OrthoStudio XP...) in a folder of their own, and choose here the one you fly with: see [Packages › One folder per source](packages.md#one-folder-per-source). +- **Scenery packages folder:** the parent folder of your packages. The line below it lists the packages found. Keep the packages of each source (packages built or regions downloaded in OrthoStreamXP, Ortho4XP, OrthoStudio XP...) in a folder of their own, and choose here the one you fly with: see [Packages › One folder per source](packages.md#one-folder-per-source). - **Cache folder:** where the textures are kept. The line below it shows the free space and how much a new area takes at the current texture size. ## Pictures and download @@ -159,7 +159,7 @@ Turn on **Light the towns at night** to give every photo tile its own lights: How many lamps are lit and how bright the houses are depends on how built up the place is: a town centre is fully lit, a village keeps all its lamps, and in the open country only a few lamps along the roads shine. Between the lights the photo stays dark; X-Plane fades the lights in at dusk by itself. -The roads come from the overlay package installed with your regions (**OrthoStream_Overlays**), or from another overlay package in X-Plane's Custom Scenery. Where no overlay package covers an area, its photo tiles stay dark at night. +The roads come from the overlay package built or installed with your packages (**OrthoGlobal_Overlays_XP** or **OrthoStream_Overlays**), or from another overlay package in X-Plane's Custom Scenery. Where no overlay package covers an area, its photo tiles stay dark at night. X-Plane loads the lights with the scenery, by day too, so they are there when night falls during a flight. The lights get the same detail as the photos under them at every distance, up to about 3 m per pixel beside the aircraft. Each tile's lights are made the first time X-Plane loads that tile, and again with more detail as you come closer; only the detail X-Plane reads is kept in the cache with the area's photos, compressed (about 50 KB per tile; a 20-minute flight around Zurich kept 160 MB), so the first flight over a new area uses a little more processor time and later flights none. Your scenery packages are not changed. **Off** is the default; a change applies from the next start. diff --git a/lib/OrthoGlobalXP.Core/OrthoGlobalXP.Core.dll b/lib/OrthoGlobalXP.Core/OrthoGlobalXP.Core.dll new file mode 100644 index 0000000..3b8a24a Binary files /dev/null and b/lib/OrthoGlobalXP.Core/OrthoGlobalXP.Core.dll differ diff --git a/lib/OrthoGlobalXP.Core/OrthoGlobalXP.Core.xml b/lib/OrthoGlobalXP.Core/OrthoGlobalXP.Core.xml new file mode 100644 index 0000000..5e18574 --- /dev/null +++ b/lib/OrthoGlobalXP.Core/OrthoGlobalXP.Core.xml @@ -0,0 +1,1078 @@ + + + + OrthoGlobalXP.Core + + + + + Reads the land runways of X-Plane 12's airports from its Global Airports apt.dat (rows 1, the airport, and 100, a land + runway with both ends). Sea lanes and helipads are left out. + + + + X-Plane's apt.dat: Global Scenery\Global Airports\Earth nav data\apt.dat. + + + Every land runway of X-Plane's airports; empty when X-Plane has no apt.dat. Takes a few seconds (the file is large). + + + The land runways of an apt.dat's text. + + + + 100 width surface shoulder smoothness centre-lights edge-lights signs, then for each end: number lat lon displaced + overrun markings approach-lights touchdown-lights REIL. + + + + Photos of on every texture that comes within of a runway. + + + Photos of on every texture that comes within of a runway. + + + + Finer photos near airports: each texture within a rule's distance of any land runway (grass strips too) + is split into four of the next zoom, and so on up to the rule's zoom. Only the rules' zooms get textures: with one rule of + ZL18, ROW_COL_BI18 lie next to ROW_COL_BI16 and the parts of a split texture beyond the distance keep its ZL16 photo. + + + + 17 within 4 km and 18 within 1.5 km of a runway. + + + Throws when a rule's zoom is not above (up to 19) or its distance is not 0 to 50 km. + + + The rules for the log: "ZL17 within 4 km, ZL18 within 1.5 km of a runway". + + + A photo texture finer than the package's zoom, by its edges. + + + A photo texture finer than the package's zoom, by its edges. + + + The textures finer photos near airports would give each tile, the same as a build makes them; for the map. + + + The package's zoom, away from airports. + + + The package's zoom, away from airports. + + + A land runway from X-Plane's apt.dat: its two ends (thresholds) and the airport it belongs to. + + + A land runway from X-Plane's apt.dat: its two ends (thresholds) and the airport it belongs to. + + + The distance between the two ends, in metres. + + + + The distance in metres from the runway (a segment between its ends) to the box .. + , .. ; 0 when they touch. Measured on a plane + tangent at the runway, which is close enough within tens of kilometres. + + + + Metres per degree of latitude (and of longitude at the equator), on a sphere of the mean radius. + + + Liang–Barsky: whether any part of the segment lies in the box. + + + + The zoom each texture should have by its distance to the nearest runway. It depends only on the texture and the runways, + never on the tile asking, so neighbouring tiles agree on the textures across their border and the meshes meet. + + + + The finest rule's zoom whose distance reaches the texture, or the texture's own zoom when none does. + + + + The finest rule's zoom whose distance reaches the texture, or 0 when none does (whatever the texture's own zoom). A + texture is never nearer a runway than the texture it is a quarter of, so it never asks for more than that one. + + + + The runways whose 1° tiles lie within the largest distance of the box. + + + + Builds photo-terrain packages from X-Plane's Global Scenery: each tile's DSF is read, re-textured and written to + Earth nav data in its continent's package (), and its roads, forests and + buildings to the same place in the overlay package (), several tiles at + once. A tile that fails is reported and the others go on. + + + + + X-Plane's runways, when already read (); otherwise they are read when the + options ask for finer photos near airports. + + + + Builds the tiles; cancelling stops the tiles under way and keeps the ones finished. + + + + Deletes the tile's DSF from the other continents' packages, where one made with another split of the continents + would leave it: X-Plane would load the tile's mesh twice. + + + + The runways the rules near airports apply to, or null when there are no rules. + + + + orthoglobalxp.json in the package: for each tile, the Global Scenery file and settings it was made from, so a later + build skips the tiles that are current and redoes those X-Plane's updates or changed settings made stale. + + + + + Raised when the way a tile is made changes, so every tile made before is made again. 2: the roads, forests and + buildings moved from the photo DSF to the overlay package. (A change of the textures near runways needs no new version: + the layout's fingerprint, recorded with each tile, changes for exactly the tiles it touches.) + + + + The manifest of a package folder; empty when there is none yet or it cannot be read (every tile is then built). + + + Writes the manifest through a temporary file. Called after each tile, so a stopped build keeps what it made. + + + + What a tile was made from: the Global Scenery file's size and time, and the settings. fingerprints + the finer textures near airports (null when the tile has none), so only the tiles they change are built again. + + + + + What a tile was made from: the Global Scenery file's size and time, and the settings. fingerprints + the finer textures near airports (null when the tile has none), so only the tiles they change are built again. + + + + + Where the packages go and how their tiles are made. The tiles are split by continent, as OrthoStreamXP's own packages + are: OrthoGlobal_Europe_XP, OrthoGlobal_NorthAmerica_XP, OrthoGlobal_SouthAmerica_XP, + OrthoGlobal_Africa_XP, OrthoGlobal_Asia_XP and OrthoGlobal_AustraliaPacific_XP (), + and their roads, forests and buildings all go to OrthoGlobal_Overlays_XP, beside them in . + + + + + Added to the prefix for the overlay package (OrthoGlobal_Overlays_XP). OrthoStreamXP takes a package whose name says + overlays for one: it lists it above the photo packages, and reads its roads to light the towns at night. + + + + Ends every package's name (OrthoGlobal_Europe_XP): made from X-Plane's own scenery. + + + + The start of the names OrthoStreamXP gives the packages it downloads and manages itself (OrthoStream_Eur, + OrthoStream_Overlays): it would take ours for its own, so the prefix may not make them. + + + + The folder the packages are made in, such as OrthoStreamXP's packages folder (base-packages). + + + The start of the packages' names: each is the prefix, '_', its continent and (OrthoGlobal_Europe_XP). + + + Finer photos near airports, or null for the same zoom everywhere. + + + + Keep X-Plane's roads, forests, buildings and objects: they are written to the overlay package + (), whose roads OrthoStreamXP also lights at night. Turn off when an overlay package + that brings them is installed too (such as AutoOrtho's OrthoStream_Overlays), or they are drawn twice. + + + + + Store the photo package's DSFs as 7z archives, as Laminar does: under half the size, and X-Plane reads them as they + are. The overlay package's stay plain, since OrthoStreamXP reads only plain DSFs for the roads it lights at night. + + + + + Also write each texture's .ter file into the package's terrain folder. OrthoStreamXP makes them itself from the names, + so they are needed only to use the package another way. + + + + Build every tile again, even those whose DSF is newer than X-Plane's and was made with the same settings. + + + The tiles built at once: unless chosen. + + + + The most a tile takes while it is built: Tokyo (+35+139), the largest Global Scenery DSF, peaks near 1 GB; most + heavy tiles 0.5 to 0.7 GB. + + + + The tiles this computer builds at once: its processors and memory. + + + + One tile per logical processor but one, which is left for the window (hyper-threads still speed the build up), and no + more than half the memory holds at each, so the computer and X-Plane keep the rest. + Memory that is not known (0) does not limit it. + + + + The photo package of a continent's tiles: OrthoGlobal_Europe_XP. + + + The one package of every continent's roads, forests and buildings, beside the photo packages: OrthoGlobal_Overlays_XP. + + + The tiles packages already have a DSF for. + + + The tiles of every continent's photo package made with these options' folder and prefix. + + + The tiles of one package folder. + + + + Writes a photo texture's terrain definition (terrain/ROW_COL_BI16.ter), the same as OrthoStreamXP makes from the name: + the texture loaded by distance from its centre, X-Plane's standard detail decals, no alpha. + + + + + Writes a photo texture's terrain definition (terrain/ROW_COL_BI16.ter), the same as OrthoStreamXP makes from the name: + the texture loaded by distance from its centre, X-Plane's standard detail decals, no alpha. + + + + Writes the definitions not in the package yet. + + + + Reads typed tile lists: names (+50+014 +50+015) and rectangles given by two opposite corners + (+49+012 .. +51+016), separated by spaces, commas, semicolons or line breaks. + + + + + Pattern:
+ \\s*\\.\\.\\s*
+ Explanation:
+ + ○ Match a whitespace character atomically any number of times.
+ ○ Match the string "..".
+ ○ Match a whitespace character atomically any number of times.
+
+
+
+ + The package's DSF was made from the same Global Scenery file with the same settings. + + + X-Plane has no Global Scenery DSF for the tile (open ocean). + + + A tile's state during a build; once it is built. + + + A tile's state during a build; once it is built. + + + How a build ended. + + + How a build ended. + + + + One pass over a CMDS payload: the terrain patches with their triangles (strips and fans unrolled), the 16-bit point + pools that objects and polygons place things from, and how many network chains there are. + + + + The 16-bit pools selected when an object or polygon command used one. + + + How many network chains (roads, railways, power lines) the commands draw. + + + Walks the commands; decides each patch's role from its definition and flags. + + + The points a triangle command lists: from the selected pool, cross-pool pairs, or a range of the selected pool. + + + Builds a CMDS payload: commands copied as they are, and terrain patches written anew. + + + The most points one triangle command lists (a whole number of triangles). + + + Triangles whose corners are all in the selected pool, by point index. + + + Triangles whose corners are in several pools of the same depth. + + + + A whole terrain patch: its triangles grouped by pool (one patch per pool, the pool selected before it, as X-Plane + expects) and the triangles spanning pools in one cross-pool patch. + + + + One atom of a DSF: a leaf holding a payload, or a container (HEAD, DEFN, GEOD, DEMS) holding atoms. + + + The four-letter name in reading order (HEAD; the file stores it reversed). + + + A leaf's bytes; null for a container. Replaceable, so a rewrite keeps the atom's place. + + + A container's atoms; null for a leaf. + + + The atom's size in the file, header included. + + + A leaf's payload, or a format error naming the atom when it is a container. + + + The opcodes of a DSF's command stream (CMDS) and the length of each command. + + + Patch flag: the terrain is solid (collisions, physics); without it the patch is an overlay drawn on top. + + + Whether the command begins a terrain patch or lists its triangles. + + + + Whether the command places something from the selected 16-bit point pool (POOL): objects and polygons. Network + chains select their points from the 32-bit pools (PO32), which are numbered on their own. + + + + The length in bytes of the command at , its opcode included. + + + Parameter, polygon count, then each polygon's point count and points. + + + + The atom tree of a DSF file: the XPLNEDSF header and version 1, the top-level atoms, and the MD5 footer + over everything before it. Atoms not changed are written back byte for byte. + + + + Whether the bytes start like a plain (not 7z-packed) DSF. + + + The atom at a path such as DEFN/TERT, or null. + + + The atom at , or a format error naming it. + + + A DSF file that does not follow the format, or uses a part of it this program does not read. + + + The string tables of a DSF (TERT, OBJT, POLY, NETW, DEMN, PROP): NUL-terminated UTF-8 strings. + + + + A 16-bit point pool (POOL atom): points of raw values each. In the file each + plane is stored on its own, raw, differenced, run-length coded or both; here the values are point by point. + + + + Point-major: point i's plane p is at i * Planes + p. + + + The plane count of a POOL payload, read from its header alone. + + + The POOL payload, every plane differenced (no run-length coding; packing the DSF does the rest). + + + A one-point pool standing in for one no command uses any more, so the indices of the others stay. + + + A point of a 16-bit pool: the pool's index in the file and the point's index in the pool. + + + A point of a 16-bit pool: the pool's index in the file and the point's index in the pool. + + + A SCAL atom: a (scale, offset) pair per plane of its pool; value = offset + raw * scale / 65535. + + + What becomes of a terrain patch of X-Plane's scenery. + + + Solid land: its triangles are re-textured with photos. + + + terrain_Water: kept as it is. + + + An overlay blending one land class into the next: left out, it would paint over the photos. + + + One terrain patch: its definition, flags, LOD range and, unless it is left out, the corners of its triangles. + + + One terrain patch: its definition, flags, LOD range and, unless it is left out, the corners of its triangles. + + + Three per triangle, in X-Plane's winding. Empty for a patch. + + + One 1° x 1° X-Plane tile, named after its south-west corner: +50+014 is 50°N 14°E. + + + Latitude of the south edge. + + + Longitude of the west edge. + + + The DSF name without extension: +50+014, -34-059. + + + The 10° folder of Earth nav data the tile's DSF is in: +50+010, -40-060. + + + Reads a tile name such as +50+014 (surrounding spaces allowed). + + + + Pattern:
+ ^\\s*([+-]\\d{2})([+-]\\d{3})\\s*$
+ Explanation:
+ + ○ Match if at the beginning of the string.
+ ○ Match a whitespace character atomically any number of times.
+ ○ 1st capture group.
+ ○ Match a character in the set [+\-].
+ ○ Match a Unicode digit exactly 2 times.
+ ○ 2nd capture group.
+ ○ Match a character in the set [+\-].
+ ○ Match a Unicode digit exactly 3 times.
+ ○ Match a whitespace character greedily any number of times.
+ ○ Match if at the end of the string or if before an ending newline.
+
+
+
+ + + The slippy-map tile grid of the imagery providers (Web Mercator): fractional tile coordinates at a zoom level, + x growing east from 180°W, y growing south from the top of the map. + + + + + Which photo textures the terrain names: ROW_COL_{ProviderCode}{Zoom}.dds, each covering 16 x 16 imagery tiles + of (the Ortho4XP / AutoOrtho layout OrthoStreamXP serves). + + + + + Which photo textures the terrain names: ROW_COL_{ProviderCode}{Zoom}.dds, each covering 16 x 16 imagery tiles + of (the Ortho4XP / AutoOrtho layout OrthoStreamXP serves). + + + + Bing at zoom 16, the layout of AutoOrtho's meshes. + + + Throws when the code is not 1 to 8 letters or digits, or the zoom is outside 12..19. + + + + Pattern:
+ ^[A-Za-z][A-Za-z0-9]{0,7}$
+ Explanation:
+ + ○ Match if at the beginning of the string.
+ ○ Match an ASCII letter.
+ ○ Match an ASCII letter or digit atomically at most 7 times.
+ ○ Match if at the end of the string or if before an ending newline.
+
+
+
+ + + One photo texture: the imagery tile at its top-left corner (both multiples of 16) at its zoom level. A texture of the next + zoom covers a quarter of it, and its edges include all of this one's, so textures of several zooms nest without gaps. + + + + + One photo texture: the imagery tile at its top-left corner (both multiples of 16) at its zoom level. A texture of the next + zoom covers a quarter of it, and its edges include all of this one's, so textures of several zooms nest without gaps. + + + + The longitude between its two western and two eastern quarters: an edge of the next zoom's textures. + + + The latitude between its two northern and two southern quarters. + + + The four textures of the next zoom that cover it. + + + + The grid of photo textures of one zoom level: each texture covers 16 x 16 imagery tiles, so its edges are lines of + constant longitude and constant latitude, and the mesh can be cut along them exactly. Textures of finer zooms (near + airports) are named and mapped by the zoom their carries. + + + + Imagery tiles along each side of one texture. + + + The zoom of the grid's textures, those away from airports. + + + The longitudes of the texture edges strictly between and , west to east. + + + The latitudes of the texture edges strictly between and , north to south. + + + The texture of the grid's zoom covering a point. + + + The texture of covering a point. + + + + A point's texture coordinates in : s from 0 at the west edge to 1 at the east edge, t from 1 at + the north edge to 0 at the south edge (Ortho4XP's st_coord), clamped to [0, 1]. + + + + The texture's stem: 11952_36192_BI16 (the zoom is the texture's own). + + + The terrain definition the DSF names for a texture: terrain/11952_36192_BI16.ter. + + + The centre of a texture and its width on the ground, for LOAD_CENTER. + + + + The photo textures of one tile: the grid's, with those near runways split into four of the next zoom, again and again up + to the zoom the runways ask for. The splits form a quadtree, so every finer texture edge continues a coarser one. + A quarter left over by a split (one no rule asks to be that fine) keeps the coarser texture its rule asks for (else the + grid's), covering only its part of it: ZL16 with ZL18 near runways gives ZL16 and ZL18 textures, never a ZL17 one. + + + + The quarters left over by a split, each with the coarser texture it shows (a split cell above it). + + + The textures split into four finer ones, coarsest first. + + + + A short hash of the split textures, or null when there are none: recorded with the tile, so it is built again when + the airports or the rules near them change (and only then). + + + + + The textures finer than the grid's that the tile has: the quarters not split again, overlapping the tile, or the + coarser texture a left-over quarter shows when that is still finer than the grid's (each once). + + + + The texture covering a point: the grid's, the finest quarter it was split into, or the one that quarter shows. + + + + Cuts the mesh along every texture edge: the grid's lines across the whole tile, then, zoom by zoom, the middles of the + split textures inside them only. + + + + The texture of that is part of. + + + Which coordinate a cut line holds constant. + + + + A line cut only where it crosses the given spans of the other coordinate (the latitudes of a longitude line), such as + the middle of a texture split into four finer ones. must follow lines already cut, so that every + triangle lies wholly inside or outside each span. + + + + + A line cut only where it crosses the given spans of the other coordinate (the latitudes of a longitude line), such as + the middle of a texture split into four finer ones. must follow lines already cut, so that every + triangle lies wholly inside or outside each span. + + + + + Cuts a mesh along lines of constant longitude and latitude (the photo texture edges), so that no triangle crosses one. + Each line is applied to the whole mesh in turn, and an edge is cut once per line however many triangles share it, so the + mesh stays watertight: no cracks and no T-junctions. Windings are kept. + + + + + Cuts the triangles inside each line's spans. A triangle outside them that shares a cut edge (on the border of a span) + is split at the new vertex too, without being cut along the line, so no T-junction is left. + + + + One line's pass over the mesh, with the vertices it made on each cut edge. + + + One line's pass over the mesh, with the vertices it made on each cut edge. + + + Whether the triangle's centre lies in one of the spans: it lies wholly in or out, by the lines cut before. + + + Splits a triangle outside the spans at the vertices its neighbours inside made on its edges, if any. + + + The vertex where the edge crosses the line, made once per edge. It lies exactly on the line. + + + + A vertex of X-Plane's base mesh: position, elevation and the two stored normal components. An elevation of + tells X-Plane to take it from the tile's elevation raster, as most Global Scenery vertices do. + + + + + A vertex of X-Plane's base mesh: position, elevation and the two stored normal components. An elevation of + tells X-Plane to take it from the tile's elevation raster, as most Global Scenery vertices do. + + + + + The point a fraction of the way from to . Its elevation is + sampled from the raster when either end's is; otherwise it is interpolated like the position and the normal. + + + + + Turns the triangles of the land patches into one connected mesh. X-Plane stores a vertex once per pool, so the two sides of + a pool border hold copies of the same point; they are merged by position (to about a centimetre), so cutting a shared edge + later gives both sides the same new vertex. + + + + + Turns the triangles of the land patches into one connected mesh. X-Plane stores a vertex once per pool, so the two sides of + a pool border hold copies of the same point; they are merged by position (to about a centimetre), so cutting a shared edge + later gives both sides the same new vertex. + + + + Triangles that became a line or a point once their copies were merged, and were left out. + + + An indexed triangle mesh: shared vertices and three vertex indices per triangle, in X-Plane's winding. + + + The triangle's area in square degrees, positive when its corners run counter-clockwise (east, then north). + + + The point inside the triangle where its medians meet. + + + + A city for the map: its name in English, where it is, and , the web-map zoom from which Natural + Earth names it (1.7 for the world's largest, 10 for small towns). + + + + + A city for the map: its name in English, where it is, and , the web-map zoom from which Natural + Earth names it (1.7 for the world's largest, 10 for small towns). + + + + The cities the map names, from Natural Earth's public-domain populated places (tools/make_cities.py). + + + Every city, most important first (by , then population). + + + + One of the six continents the photo packages are split by, as OrthoStreamXP splits the meshes it downloads + (OrthoStream_Eur, OrthoStream_NA...): is OrthoStreamXP's id for it and ends the + names of those downloaded packages. Ours are named by instead (OrthoGlobal_Europe_XP), so + the two are told apart at a glance. Every tile is in exactly one (), so no tile's mesh is in two packages. + + + + + One of the six continents the photo packages are split by, as OrthoStreamXP splits the meshes it downloads + (OrthoStream_Eur, OrthoStream_NA...): is OrthoStreamXP's id for it and ends the + names of those downloaded packages. Ours are named by instead (OrthoGlobal_Europe_XP), so + the two are told apart at a glance. Every tile is in exactly one (), so no tile's mesh is in two packages. + + + + The six, in the order a tile on a border is given to the first of those with as many tiles around it. + + + + The continent a tile's package is: the Natural Earth continent the tile is in (), with + Russia east of the Urals (60°E) in Asia. A tile on a border goes to the one of its continents with the most tiles + around it; a tile in none (sea, Antarctica, a remote island) to the continent with the most tiles in the smallest + square around it that has any. The answer depends only on the tile, so it is the same in every build. + + + + Works out from the region catalog's continents, once per tile. + + + Natural Earth's continents by name; Antarctica and the open seas are in none. + + + Natural Earth puts the whole of Russia in Europe; from this longitude on it is Asia, as OrthoStreamXP has it. + + + A group of states, such as a French region or England. + + + A state, province, county or the like: Natural Earth's first level inside a country. + + + + A continent, subregion, country or state, with the 1° tiles it touches. is the continent of a + subregion, the subregion of a country, and the country of a region or state. + + + + + A continent, subregion, country or state, with the 1° tiles it touches. is the continent of a + subregion, the subregion of a country, and the country of a region or state. + + + + + The areas tiles can be picked by, made from Natural Earth's public-domain 1:10m outlines (tools/make_regions.py). + A tile belongs to an area when the area's outline passes through it or its centre lies inside it, so tiles on a border + belong to both sides. Sea tiles are listed too; pick only those X-Plane has. + + + + Every area: continents, subregions, countries, regions, then states, each by parent and name. + + + Rows "lat:lon,lon-lon" joined by ';'. + + + + Re-textures one X-Plane Global Scenery tile with photo terrain: + + the solid land patches are joined into one mesh and cut along the photo textures' edges; + each piece is given its texture (terrain/ROW_COL_BI16.ter) and texture coordinates; + the overlays blending one land class into the next are left out; + water and every raster stay as they are, byte for byte; + the roads, forests, buildings and other objects are left out (with their definitions and the 32-bit pools of the + roads' points): they go to the tile's overlay (), or come from another overlay package. + + Elevations X-Plane samples from the tile's raster stay sampled, so the relief is X-Plane's own. + With , the textures near airports are of finer zooms (see ). + + + + + Re-textures one X-Plane Global Scenery tile with photo terrain: + + the solid land patches are joined into one mesh and cut along the photo textures' edges; + each piece is given its texture (terrain/ROW_COL_BI16.ter) and texture coordinates; + the overlays blending one land class into the next are left out; + water and every raster stay as they are, byte for byte; + the roads, forests, buildings and other objects are left out (with their definitions and the 32-bit pools of the + roads' points): they go to the tile's overlay (), or come from another overlay package. + + Elevations X-Plane samples from the tile's raster stay sampled, so the relief is X-Plane's own. + With , the textures near airports are of finer zooms (see ). + + + + The tile's textures: the grid's, finer near runways. + + + The triangles of each texture (by the texture under their centroid), coarsest zoom first, then north-west first. + + + Empties every pool but those of the water patches (the land and blends are replaced, the rest left out). Returns how many. + + + + Empties the object, polygon and network tables, so X-Plane loads none of the art the tile no longer places, and + removes the 32-bit pools: only network chains place points from them. + + + + Refuses a DSF whose sim/west and sim/south properties name another tile. + + + + One 7-plane pool of photo terrain (lon, lat, elevation, normal x, normal y, s, t) covering a 1/16° square. The square's + corner and size are exact binary fractions, so a point on its border decodes to the same position in the pools on both + sides and the textures meet without cracks. + + + + + One 7-plane pool of photo terrain (lon, lat, elevation, normal x, normal y, s, t) covering a 1/16° square. The square's + corner and size are exact binary fractions, so a point on its border decodes to the same position in the pools on both + sides and the textures meet without cracks. + + + + + The elevation plane's offset and scale: -32768 to 32767 in whole metres when a point samples the raster (so the marker + value is exact, as in X-Plane's own pools), otherwise the points' own range. + + + + + Places the photo terrain's points in pools: each mesh vertex goes to the pool of the 1/16° square it lies in, once per + texture that uses it (a vertex on a texture edge has other texture coordinates on each side). A square with more points + than one pool holds gets more pools with the same extent. + + + + The point of in texture , added on first use. + + + The new DSF of a tile and the photo textures it names. + + + The new DSF of a tile and the photo textures it names. + + + What re-texturing one tile did, for the log. + + + What re-texturing one tile did, for the log. + + + The 16-bit pools of the source DSF (its POOL and SCAL atoms, in file order), decoded when first read. + + + A point as a mesh vertex (its first five planes: lon, lat, elevation, normal x, normal y). + + + Replaces a pool nothing uses any more with a one-point stand-in, keeping the other pools' indices. + + + + Turns one X-Plane Global Scenery tile into an overlay DSF (sim/overlay 1): its roads, railways, power lines, + forests, autogen and objects, without its terrain and rasters, for the overlay package beside the photo package. + + every command but the terrain patches is copied byte for byte, pool and definition selections included; + the object, polygon and network tables and the 32-bit pools (the roads' points) stay as they are; + the 16-bit pools only the terrain used become one-point placeholders, so the others keep their indices; + the terrain and raster tables are emptied and the rasters left out. + + OrthoStreamXP reads the roads of an overlay package's plain DSFs to light the photo tiles at night, so the overlay is + never packed. + + + + The overlay DSF of from its Global Scenery DSF (unpacked). + + + Every command but the terrain patches, in order: pool and definition selections are kept, so the rest reads as before. + + + Sets sim/overlay 1 in the properties, after the tile's bounds. + + + A tile's overlay DSF and how many network chains (roads among them) it draws. + + + A tile's overlay DSF and how many network chains (roads among them) it draws. + + + + Reads and writes DSF files, plain or packed the way Laminar ships them: a 7z (LZMA) archive holding the one DSF. + X-Plane recognises the 7z signature when it loads a .dsf and unpacks it in memory. + + + + + Writes the DSF through a temporary file in the same folder, so X-Plane or a crash never sees half a file. + stores it as a 7z archive, as Laminar's own. + + + + + The tiles of X-Plane 12's Global Scenery: one DSF per 1° tile under Earth nav data, in X-Plane 12 Global Scenery and in + X-Plane 12 Demo Areas. The installer keeps the demo areas' tiles only in the latter unless their region is downloaded + too; a tile in both is the same file and is read from X-Plane 12 Global Scenery. + + + + Earth nav data of X-Plane 12 Global Scenery. + + + Earth nav data of X-Plane 12 Demo Areas. + + + Whether has Global Scenery or Demo Areas to build from. + + + + The tile's DSF: the Global Scenery one, else the Demo Areas one. When neither exists, the path it would have in Global + Scenery (so the file does not exist). + + + + Every tile that has a DSF, each once. + + + + The packages folder OrthoStreamXP mounts (base-packages in %LOCALAPPDATA%\OrthoStreamXP\orthostreamxp.ini): + a package made there is streamed with the others at OrthoStreamXP's next start. + + + + The value of the base-packages = folder line, when that folder exists. + + + Finds X-Plane 12 from the install list its installer keeps (%LOCALAPPDATA%\x-plane_install_12.txt). + + + The first listed X-Plane 12 folder that has Global Scenery (or only its Demo Areas), or null. + + + Custom -derived type for the RangePattern method. + + + Cached, thread-safe singleton instance. + + + Initializes the instance. + + + Provides a factory for creating instances to be used by methods on . + + + Creates an instance of a used by methods on . + + + Provides the runner that contains the custom logic implementing the specified regular expression. + + + Scan the starting from base.runtextstart for the next match. + The text being scanned by the regular expression. + + + Search starting from base.runtextpos for the next location a match could possibly start. + The text being scanned by the regular expression. + true if a possible match was found; false if no more matches are possible. + + + Determine whether at base.runtextpos is a match for the regular expression. + The text being scanned by the regular expression. + true if the regular expression matches at the current position; otherwise, false. + + + Custom -derived type for the NamePattern method. + + + Cached, thread-safe singleton instance. + + + Initializes the instance. + + + Provides a factory for creating instances to be used by methods on . + + + Creates an instance of a used by methods on . + + + Provides the runner that contains the custom logic implementing the specified regular expression. + + + Scan the starting from base.runtextstart for the next match. + The text being scanned by the regular expression. + + + Search starting from base.runtextpos for the next location a match could possibly start. + The text being scanned by the regular expression. + true if a possible match was found; false if no more matches are possible. + + + Determine whether at base.runtextpos is a match for the regular expression. + The text being scanned by the regular expression. + true if the regular expression matches at the current position; otherwise, false. + + + Custom -derived type for the CodePattern method. + + + Cached, thread-safe singleton instance. + + + Initializes the instance. + + + Provides a factory for creating instances to be used by methods on . + + + Creates an instance of a used by methods on . + + + Provides the runner that contains the custom logic implementing the specified regular expression. + + + Scan the starting from base.runtextstart for the next match. + The text being scanned by the regular expression. + + + Search starting from base.runtextpos for the next location a match could possibly start. + The text being scanned by the regular expression. + true if a possible match was found; false if no more matches are possible. + + + Determine whether at base.runtextpos is a match for the regular expression. + The text being scanned by the regular expression. + true if the regular expression matches at the current position; otherwise, false. + + + Helper methods used by generated -derived implementations. + + + Default timeout value set in , or if none was set. + + + Whether is non-infinite. + +
+
diff --git a/lib/OrthoGlobalXP.Core/build.ps1 b/lib/OrthoGlobalXP.Core/build.ps1 new file mode 100644 index 0000000..3626933 --- /dev/null +++ b/lib/OrthoGlobalXP.Core/build.ps1 @@ -0,0 +1,28 @@ +# Rebuilds OrthoGlobalXP.Core.dll (with its XML documentation) next to this script: the engine of the Build Scenery +# page, which re-textures X-Plane 12's own Global Scenery tiles with photo terrain (src\OrthoStreamXP\Gui\ViewModels\ +# BuildSceneryViewModel.cs). Needs the .NET 10 SDK and the OrthoGlobalXP sources, by default beside this repository. +# +# .\lib\OrthoGlobalXP.Core\build.ps1 [-Source C:\path\to\OrthoGlobalXP] +param( + [string]$Source = (Join-Path $PSScriptRoot '..\..\..\OrthoGlobalXP') +) +$ErrorActionPreference = 'Stop' + +$project = Join-Path $Source 'src\OrthoGlobalXP.Core\OrthoGlobalXP.Core.csproj' +if (-not (Test-Path $project)) { throw "OrthoGlobalXP.Core not found at $project (pass -Source)" } + +$out = Join-Path ([IO.Path]::GetTempPath()) "orthoglobalxp-core-$PID" +try { + # CS1591, CS1573: the engine documents its public surface, not every member or parameter of it. + dotnet build $project -c Release -nologo -o $out -p:GenerateDocumentationFile=true '-p:NoWarn=CS1591%3BCS1573' + if ($LASTEXITCODE -ne 0) { throw "dotnet build failed ($LASTEXITCODE)" } + foreach ($file in 'OrthoGlobalXP.Core.dll', 'OrthoGlobalXP.Core.xml') { + Copy-Item (Join-Path $out $file) $PSScriptRoot -Force + } + # Its one package dependency must match SharpCompress's version in src\OrthoStreamXP\OrthoStreamXP.csproj. + $sharpCompress = Select-Xml -Path $project -XPath "//PackageReference[@Include='SharpCompress']" | ForEach-Object { $_.Node.Version } + Write-Host "OrthoGlobalXP.Core.dll updated (it references SharpCompress $sharpCompress)." +} +finally { + Remove-Item $out -Recurse -Force -ErrorAction SilentlyContinue +} diff --git a/release-notes/v2.0.0.md b/release-notes/v2.0.0.md new file mode 100644 index 0000000..b1735a0 --- /dev/null +++ b/release-notes/v2.0.0.md @@ -0,0 +1,24 @@ +## What's new + +- **Build your own scenery packages.** OrthoStreamXP can now make photo scenery packages for any part of the world from X-Plane's own Global Scenery, right on your PC. You no longer need to download a whole region's mesh, or a separate tool such as Ortho4XP. Open the **Packages** page: its first tab, **Build own packages**, shows a map of the world. Pick the areas you fly, click **Build the picked tiles**, and each 1° tile is ready in a few seconds. +- **Pick on a map, or by name.** Click a tile to pick or drop it, Shift+drag to pick a rectangle, and Ctrl+drag to drop one. Or type a continent, country, region or state under **Pick by region or country**, such as *Germany*, *Bavaria* or *Western Europe*, and click **Pick**: every tile it touches that X-Plane has scenery for is picked. The map shows which tiles are picked, built, building or failed, with the airports, the cities and OpenStreetMap underneath. +- **X-Plane's own ground, with photos on it.** Each tile keeps X-Plane's relief, water and coastlines. Its ground gets the photo textures, with finer photos around the runways. X-Plane's roads, forests and buildings go into an overlay package beside it, so towns still have their buildings, and **Night lights** still light the streets. +- **The first setup builds them too.** In the setup's **Scenery** step, **No scenery packages yet?** now offers **Build your own packages…**. The folder they are built in becomes your scenery packages folder. +- **Downloading a region is still there.** The Packages page's second tab, **Download kubilus1 packages**, has the region downloads from before, unchanged. + +## How building works + +The packages are made from the Global Scenery already installed with your X-Plane. It is only read, never changed. Building needs no download: the photos are streamed as you fly, as with any other package. The tiles you can pick are the ones your X-Plane has scenery for, including its Demo Areas. + +The packages are named after their continent, such as **OrthoGlobal_Europe_XP** or **OrthoGlobal_NorthAmerica_XP**, so you can tell them from the downloaded regions (**OrthoStream_Eur**...). The roads, forests and buildings of all of them go into **OrthoGlobal_Overlays_XP**. They are built in the folder shown under **Scenery packages folder** at the top of the tab. That is your scenery packages folder unless you choose another with **Choose…**. If the tab warns that OrthoStreamXP will not stream the packages built there, click **Stream from here** to make that folder your scenery packages folder. + +Building again skips the tiles that are already up to date, so you can add areas later at any time. **Stop** ends a build part-way, and the tiles already built are kept. The page remembers the tiles you picked for the next start. + +## Good to know + +- **Keep the built packages in a folder of their own.** Don't build them into a folder that already holds downloaded regions or packages from Ortho4XP, AutoOrtho or another tool. Two packages for the same area bring two meshes, and the roads and buildings can show twice. Click **Choose…** and pick a new, empty folder, then click **Stream from here**. +- **Stream from here** works while OrthoStreamXP is stopped. You can build while it runs, but the new tiles are streamed only from its next start. Stop and start OrthoStreamXP, with X-Plane closed, to use them. +- If you close the window during a build, OrthoStreamXP asks first. The tiles already built are kept. +- The map's **OpenStreetMap** background is downloaded as you look at it and kept for two weeks. Untick **OpenStreetMap** if you don't want it. +- The packages are made from your own X-Plane installation and are not for redistribution. +- Nothing changes for your existing packages or settings with the update. Packages you downloaded or made before work as they did. diff --git a/release-notes/v2.1.0.md b/release-notes/v2.1.0.md new file mode 100644 index 0000000..f69b83e --- /dev/null +++ b/release-notes/v2.1.0.md @@ -0,0 +1,13 @@ +## What's new + +- **Search your scenery list.** The **X-Plane Custom Scenery** page now has a search box above the list. Type part of a package's name or folder, such as *kden* or *D:\Ortho4XP*, and only the packages that match are shown. Capitals don't matter, and a folder can be typed with \ or /. On the right, the page counts the packages: all of them, or how many match, such as *3 of 1,623 packages*. **Esc** or the **×** in the box shows the whole list again. +- **Show in list.** While you search, each package that matches has a **Show in list** button. It clears the search, scrolls to the package and marks it with a coloured border, so you can drag it to a new place. + +## Good to know + +- While you search, the switches work as usual, but packages can't be dragged: between two packages that match, many others may be hidden. Use **Show in list** first, or clear the search. +- The search stays when the list is read again, after **Refresh**, Start or Stop. +- As before, the list can be changed only while OrthoStreamXP is stopped. Searching works at any time. +- Nothing changes for your packages or settings with the update. + +Thanks to andrewcarlberg for this feature. diff --git a/src/OrthoStreamXP/Gui/Building/RegionSearch.cs b/src/OrthoStreamXP/Gui/Building/RegionSearch.cs new file mode 100644 index 0000000..ba3ee1f --- /dev/null +++ b/src/OrthoStreamXP/Gui/Building/RegionSearch.cs @@ -0,0 +1,107 @@ +using System.Globalization; +using OrthoGlobalXP.Regions; + +namespace OrthoStreamXP.Gui; + +/// An area in the list of areas tiles can be picked by. +internal sealed record RegionItem(Region Region) +{ + public string Title => Region.Name; + + public string Detail => string.Create(CultureInfo.InvariantCulture, + $"{KindName(Region.Kind)}{(Region.Parent.Length > 0 ? " · " + Region.Parent : "")} · {Region.Tiles.Count:N0} tiles"); + + private static string KindName(RegionKind kind) => kind switch + { + RegionKind.Continent => "Continent", + RegionKind.Subregion => "Subregion", + RegionKind.Country => "Country", + RegionKind.Region => "Region", + _ => "State or province", + }; +} + +/// +/// Finds the areas tiles can be picked by: continents, subregions, countries, regions and states (Natural Earth's +/// outlines, in OrthoGlobalXP's region catalogue), by name. Without a search it lists the continents, subregions and +/// countries. +/// +internal sealed class RegionSearch : ObservableObject +{ + private const int MaxMatches = 200; + + private readonly IReadOnlyList _regions; + private string _text = ""; + private IReadOnlyList _matches = []; + private RegionItem? _selected; + + public RegionSearch(IReadOnlyList regions) + { + _regions = regions; + Update(); + } + + /// A continent, subregion, country, region or state: "Germany", "Bavaria", "Western Europe". + public string Text + { + get => _text; + set + { + if (Set(ref _text, value ?? "")) Update(); + } + } + + public IReadOnlyList Matches + { + get => _matches; + private set => Set(ref _matches, value); + } + + public RegionItem? Selected + { + get => _selected; + set + { + if (Set(ref _selected, value)) RelayCommand.Refresh(); + } + } + + /// + /// Takes an area from the list: its name goes into the search without searching again, so it stays the chosen one + /// even when another area has the same name ("Georgia" the country and the state). + /// + public void Choose(RegionItem item) + { + _text = item.Title; + Raise(nameof(Text)); + Selected = item; + } + + /// + /// The areas whose name (or, after them, whose parent) holds the search, accents and case aside: an exact name first, + /// then names starting with it, names holding it and areas inside one named so; the larger kind first within each. + /// + public static IEnumerable Find(IEnumerable regions, string text) + { + string query = text.Trim(); + CompareInfo compare = CultureInfo.InvariantCulture.CompareInfo; + const CompareOptions Loose = CompareOptions.IgnoreCase | CompareOptions.IgnoreNonSpace; + return regions.Select(r => + { + if (query.Length == 0) return (Region: r, Rank: r.Kind <= RegionKind.Country ? 0 : -1); + int at = compare.IndexOf(r.Name, query, Loose); + int rank = at < 0 ? (compare.IndexOf(r.Parent, query, Loose) >= 0 ? 3 : -1) + : compare.Compare(r.Name, query, Loose) == 0 ? 0 : at == 0 ? 1 : 2; + return (Region: r, Rank: rank); + }) + .Where(x => x.Rank >= 0) + .OrderBy(x => x.Rank).ThenBy(x => x.Region.Kind).ThenBy(x => x.Region.Name, StringComparer.CurrentCultureIgnoreCase) + .Select(x => x.Region); + } + + private void Update() + { + Matches = [.. Find(_regions, Text).Take(MaxMatches).Select(r => new RegionItem(r))]; + if (Text.Trim().Length > 0) Selected = Matches.Count > 0 ? Matches[0] : null; + } +} diff --git a/src/OrthoStreamXP/Gui/MainWindow.xaml b/src/OrthoStreamXP/Gui/MainWindow.xaml index 4ad8ee4..28d1930 100644 --- a/src/OrthoStreamXP/Gui/MainWindow.xaml +++ b/src/OrthoStreamXP/Gui/MainWindow.xaml @@ -10,7 +10,7 @@ - + diff --git a/src/OrthoStreamXP/Gui/MainWindow.xaml.cs b/src/OrthoStreamXP/Gui/MainWindow.xaml.cs index b3cac5b..481c370 100644 --- a/src/OrthoStreamXP/Gui/MainWindow.xaml.cs +++ b/src/OrthoStreamXP/Gui/MainWindow.xaml.cs @@ -49,6 +49,19 @@ private async Task HandOverToXPlaneAsync(TrayIcon tray) protected override async void OnClosing(CancelEventArgs e) { base.OnClosing(e); + // A build stops before the window goes: the tiles under way are given up, the ones built kept. + if (!_closing && _main.BuildScenery.IsBuilding) + { + e.Cancel = true; + if (MessageBox.Show(this, "Scenery is being built. Stop the build and close?\n\nThe tiles already built are kept.", + "OrthoStreamXP", MessageBoxButton.OKCancel, MessageBoxImage.Question, MessageBoxResult.Cancel) != MessageBoxResult.OK) + return; + _main.BuildScenery.Stop.Execute(null); + while (_main.BuildScenery.IsBuilding) await Task.Delay(200).ConfigureAwait(true); + Close(); + return; + } + _main.BuildScenery.SaveChoices(); if (_closing || _main.Mount.IsStopped) return; e.Cancel = true; if (_main.Mount.IsRunning && MessageBox.Show(this, diff --git a/src/OrthoStreamXP/Gui/Map/StreetMapTiles.cs b/src/OrthoStreamXP/Gui/Map/StreetMapTiles.cs new file mode 100644 index 0000000..950d2ad --- /dev/null +++ b/src/OrthoStreamXP/Gui/Map/StreetMapTiles.cs @@ -0,0 +1,167 @@ +using System.Globalization; +using System.Net; +using System.Reflection; +using System.Windows.Media.Imaging; +using OrthoStreamXP.Setup; + +namespace OrthoStreamXP.Gui; + +/// One OpenStreetMap tile: zoom, column from 180°W, row from the top of the map. +internal readonly record struct StreetMapTile(int Zoom, int X, int Y); + +/// +/// OpenStreetMap's standard tiles for the Build Scenery map's background, as its tile usage policy asks: an identifying +/// User-Agent, a few connections, tiles kept on disk (%LOCALAPPDATA%\OrthoStreamXP\osm) for two weeks and in memory, +/// and only the tiles on screen asked for, those nearest the middle first. +/// +internal sealed class StreetMapTiles : IDisposable +{ + public const int MaxZoom = 19; + private const int MemoryTiles = 768, Workers = 4; + private const string Server = "https://tile.openstreetmap.org"; + private static readonly TimeSpan KeepOnDisk = TimeSpan.FromDays(14), RetryAfter = TimeSpan.FromMinutes(2); + + private readonly string _folder = Path.Join(AppPaths.Root, "osm"); + private readonly HttpClient _http; + private readonly CancellationTokenSource _stop = new(); + private readonly Lock _lock = new(); + private readonly Dictionary> _memory = []; + private readonly LinkedList<(StreetMapTile Tile, BitmapSource Image)> _recent = new(); + private readonly Dictionary _failed = []; + private readonly HashSet _loading = []; + private List _wanted = []; + private int _working; + + public StreetMapTiles() + { + string version = typeof(StreetMapTiles).Assembly.GetCustomAttribute()?.InformationalVersion.Split('+')[0] ?? "0"; + _http = new HttpClient(new SocketsHttpHandler { MaxConnectionsPerServer = Workers, AutomaticDecompression = DecompressionMethods.All }) + { + Timeout = TimeSpan.FromSeconds(20), + DefaultRequestVersion = HttpVersion.Version20, + DefaultVersionPolicy = HttpVersionPolicy.RequestVersionOrLower, + }; + _http.DefaultRequestHeaders.UserAgent.ParseAdd($"OrthoStreamXP/{version} (X-Plane scenery tool; tile picker map)"); + } + + /// Raised on a worker thread when a tile asked for is ready. + public event EventHandler? TileLoaded; + + /// The tile, when it is in memory. + public BitmapSource? TryGet(StreetMapTile tile) + { + lock (_lock) + { + if (!_memory.TryGetValue(tile, out var node)) return null; + _recent.Remove(node); + _recent.AddFirst(node); + return node.Value.Image; + } + } + + /// The tiles to load now, most wanted first. Replaces the previous request: tiles scrolled away are not loaded. + public void Want(IReadOnlyList tiles) + { + lock (_lock) + { + DateTime now = DateTime.UtcNow; + _wanted = [.. tiles.Where(t => !_memory.ContainsKey(t) && !_loading.Contains(t) && !(_failed.TryGetValue(t, out DateTime at) && now - at < RetryAfter))]; + _wanted.Reverse(); // taken from the end + while (_working < Workers && _working < _wanted.Count) + { + _working++; + _ = Task.Run(WorkAsync); + } + } + } + + public void Dispose() + { + _stop.Cancel(); + _http.Dispose(); + _stop.Dispose(); + } + + private async Task WorkAsync() + { + while (true) + { + StreetMapTile tile; + CancellationToken token; + lock (_lock) + { + if (_wanted.Count == 0 || _stop.IsCancellationRequested) + { + _working--; + return; + } + tile = _wanted[^1]; + _wanted.RemoveAt(_wanted.Count - 1); + _loading.Add(tile); + token = _stop.Token; + } + BitmapSource? image = null; + try + { + image = await LoadAsync(tile, token).ConfigureAwait(false); + } + catch (Exception ex) when (ex is HttpRequestException or IOException or UnauthorizedAccessException or OperationCanceledException + or NotSupportedException or InvalidOperationException or ArgumentException or ObjectDisposedException) + { + // Offline, refused, closed or a damaged file: the map shows the coarser tile and tries again later. + } + lock (_lock) + { + _loading.Remove(tile); + if (image is null) _failed[tile] = DateTime.UtcNow; + else Remember(tile, image); + } + if (image is not null) TileLoaded?.Invoke(this, EventArgs.Empty); + } + } + + private async Task LoadAsync(StreetMapTile tile, CancellationToken cancellationToken) + { + string path = Path.Join(_folder, tile.Zoom.ToString(CultureInfo.InvariantCulture), tile.X.ToString(CultureInfo.InvariantCulture), + tile.Y.ToString(CultureInfo.InvariantCulture) + ".png"); + var file = new FileInfo(path); + if (file.Exists && DateTime.UtcNow - file.LastWriteTimeUtc < KeepOnDisk) + return Decode(await File.ReadAllBytesAsync(path, cancellationToken).ConfigureAwait(false)); + byte[] bytes; + try + { + bytes = await _http.GetByteArrayAsync(new Uri($"{Server}/{tile.Zoom}/{tile.X}/{tile.Y}.png"), cancellationToken).ConfigureAwait(false); + } + catch (HttpRequestException) when (file.Exists) + { + // Offline: an old tile is better than none. + return Decode(await File.ReadAllBytesAsync(path, cancellationToken).ConfigureAwait(false)); + } + BitmapSource image = Decode(bytes); + AtomicFile.Write(path, bytes); + return image; + } + + private static BitmapImage Decode(byte[] bytes) + { + var image = new BitmapImage(); + image.BeginInit(); + image.CacheOption = BitmapCacheOption.OnLoad; + image.CreateOptions = BitmapCreateOptions.IgnoreColorProfile; + image.StreamSource = new MemoryStream(bytes); + image.EndInit(); + image.Freeze(); + return image; + } + + private void Remember(StreetMapTile tile, BitmapSource image) + { + if (_memory.ContainsKey(tile)) return; + _memory[tile] = _recent.AddFirst((tile, image)); + while (_recent.Count > MemoryTiles) + { + _memory.Remove(_recent.Last!.Value.Tile); + _recent.RemoveLast(); + } + } +} diff --git a/src/OrthoStreamXP/Gui/Map/TileMapModel.cs b/src/OrthoStreamXP/Gui/Map/TileMapModel.cs new file mode 100644 index 0000000..23694af --- /dev/null +++ b/src/OrthoStreamXP/Gui/Map/TileMapModel.cs @@ -0,0 +1,85 @@ +using OrthoGlobalXP.Geo; + +namespace OrthoStreamXP.Gui; + +/// Where a tile is in a build, as the Build Scenery map shows it. +internal enum MapTileState +{ + None, + Building, + Built, + Failed, +} + +/// +/// What the Build Scenery map shows of each 1° tile: whether X-Plane's Global Scenery has it (so it can be built), whether +/// it is picked, and where it is in a build. fires after every change. +/// +internal sealed class TileMapModel +{ + private readonly HashSet _available = []; + private readonly HashSet _selected = []; + private readonly Dictionary _states = []; + + public event EventHandler? Changed; + + public IReadOnlyCollection Selected => _selected; + + public int AvailableCount => _available.Count; + + public bool IsAvailable(TileCoordinate tile) => _available.Contains(tile); + + public bool IsSelected(TileCoordinate tile) => _selected.Contains(tile); + + public MapTileState StateOf(TileCoordinate tile) => _states.GetValueOrDefault(tile); + + /// The tiles X-Plane has; picked tiles it lacks are dropped. + public void SetAvailable(IEnumerable tiles) + { + _available.Clear(); + _available.UnionWith(tiles); + _selected.IntersectWith(_available); + OnChanged(); + } + + /// Marks the tiles the packages have, clearing the build states of the others. + public void SetBuilt(IEnumerable tiles) + { + _states.Clear(); + foreach (TileCoordinate tile in tiles) _states[tile] = MapTileState.Built; + OnChanged(); + } + + public void SetState(TileCoordinate tile, MapTileState state) + { + if (state == MapTileState.None) _states.Remove(tile); + else _states[tile] = state; + OnChanged(); + } + + /// Picks or drops one tile; only tiles X-Plane has can be picked. + public void Toggle(TileCoordinate tile) + { + if (!_selected.Remove(tile) && _available.Contains(tile)) _selected.Add(tile); + OnChanged(); + } + + /// Picks (only those X-Plane has) or drops the tiles. + public void Select(IEnumerable tiles, bool selected) + { + foreach (TileCoordinate tile in tiles) + { + if (!selected) _selected.Remove(tile); + else if (_available.Contains(tile)) _selected.Add(tile); + } + OnChanged(); + } + + public void ClearSelection() + { + _selected.Clear(); + OnChanged(); + } + + private void OnChanged() => Changed?.Invoke(this, EventArgs.Empty); +} diff --git a/src/OrthoStreamXP/Gui/Map/TileMapView.cs b/src/OrthoStreamXP/Gui/Map/TileMapView.cs new file mode 100644 index 0000000..01196c1 --- /dev/null +++ b/src/OrthoStreamXP/Gui/Map/TileMapView.cs @@ -0,0 +1,805 @@ +using System.Globalization; +using System.Windows; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Threading; +using OrthoGlobalXP.Airports; +using OrthoGlobalXP.Geo; +using GlobalCity = OrthoGlobalXP.Regions.City; + +namespace OrthoStreamXP.Gui; + +/// +/// The Build Scenery map: the world in Web Mercator as a grid of 1° tiles, over OpenStreetMap or plain. Tiles X-Plane's +/// Global Scenery has are shaded (or, over the street map, those it lacks are veiled). Zoomed in, the runways show, with the +/// finer textures the airports get. Cities are named, more as the map zooms in. Click picks or drops a tile, drag pans, +/// Shift+drag picks a rectangle, Ctrl+drag drops one, the wheel zooms. Its colours come from the brushes set on it (the +/// window's theme), so it follows light and dark. +/// +internal sealed class TileMapView : FrameworkElement +{ + public static readonly DependencyProperty ModelProperty = DependencyProperty.Register( + nameof(Model), typeof(TileMapModel), typeof(TileMapView), new PropertyMetadata(null, OnModelChanged)); + + public static readonly DependencyProperty ShowStreetMapProperty = DependencyProperty.Register( + nameof(ShowStreetMap), typeof(bool), typeof(TileMapView), new PropertyMetadata(false, OnLookChanged)); + + public static readonly DependencyProperty RunwaysProperty = DependencyProperty.Register( + nameof(Runways), typeof(IReadOnlyList), typeof(TileMapView), new PropertyMetadata(null, OnRunwaysChanged)); + + public static readonly DependencyProperty AirportPreviewProperty = DependencyProperty.Register( + nameof(AirportPreview), typeof(AirportZoomPreview), typeof(TileMapView), new PropertyMetadata(null, OnAirportPreviewChanged)); + + public static readonly DependencyProperty CitiesProperty = DependencyProperty.Register( + nameof(Cities), typeof(IReadOnlyList), typeof(TileMapView), new PropertyMetadata(null, OnLookChanged)); + + public static readonly DependencyProperty ShowCitiesProperty = DependencyProperty.Register( + nameof(ShowCities), typeof(bool), typeof(TileMapView), new PropertyMetadata(true, OnLookChanged)); + + public static readonly DependencyProperty BackgroundProperty = BrushProperty(nameof(Background), Color.FromRgb(0x20, 0x20, 0x20)); + public static readonly DependencyProperty ForegroundProperty = BrushProperty(nameof(Foreground), Colors.White); + public static readonly DependencyProperty PickedBrushProperty = BrushProperty(nameof(PickedBrush), Color.FromRgb(0x3D, 0x8B, 0xFD)); + public static readonly DependencyProperty BuiltBrushProperty = BrushProperty(nameof(BuiltBrush), Color.FromRgb(0x2F, 0xA3, 0x6B)); + public static readonly DependencyProperty BuildingBrushProperty = BrushProperty(nameof(BuildingBrush), Color.FromRgb(0xF0, 0xA0, 0x30)); + public static readonly DependencyProperty FailedBrushProperty = BrushProperty(nameof(FailedBrush), Color.FromRgb(0xE0, 0x52, 0x52)); + + private const double ClickSlop = 4, MaxLatitude = 85.0511287798; + // Cities are named from a zoom this much below the one Natural Earth gives (overlapping names are left out anyway). + private const double CityZoomBias = 1; + private const int MaxCityLabels = 400; + // Scales are pixels across the whole world; pixels per degree of longitude are a 360th of that. + private const double MinScale = 360 * 1.5, MaxScale = 256.0 * (1 << 16); + // Pixels per degree from which the grid shows every degree, the tiles are named, the finer textures and the runways show. + private const double GridFrom = 6, LabelsFrom = 56, FinerTexturesFrom = 40, RunwaysFrom = 90; + private const int PreviewTilesPerFrame = 64; + + private static readonly Pen RunwayPen = Frozen(new Pen(Brushes.White, 2.5) { StartLineCap = PenLineCap.Round, EndLineCap = PenLineCap.Round }); + private static readonly Pen RunwayCasing = Frozen(new Pen(new SolidColorBrush(Color.FromRgb(0x20, 0x20, 0x20)), 4.5) + { StartLineCap = PenLineCap.Round, EndLineCap = PenLineCap.Round }); + private static readonly Typeface LabelFace = new("Segoe UI"); + private static readonly Typeface CityFace = new(new FontFamily("Segoe UI"), FontStyles.Normal, FontWeights.Normal, FontStretches.Normal); + private static readonly Typeface MajorCityFace = new(new FontFamily("Segoe UI"), FontStyles.Normal, FontWeights.SemiBold, FontStretches.Normal); + + // OpenStreetMap is light whatever the window's theme: dark text and lines with a white halo over it. + private static readonly Color StreetInk = Color.FromRgb(0x1A, 0x22, 0x2C); + private static readonly Brush StreetCityText = Frozen(new SolidColorBrush(StreetInk)); + private static readonly Pen StreetCityHalo = Frozen(new Pen(new SolidColorBrush(Color.FromArgb(0xE0, 0xFF, 0xFF, 0xFF)), 3) { LineJoin = PenLineJoin.Round }); + + /// The finer textures: one zoom above the package's, two, three and beyond (the legend's colours). + private static readonly Brush[] FinerFills = + [Solid(Color.FromRgb(0xFF, 0xC8, 0x2E)), Solid(Color.FromRgb(0xE8, 0x4F, 0xD8)), Solid(Color.FromRgb(0xFF, 0x40, 0x40))]; + + private readonly List[] _rows = [.. Enumerable.Range(0, 180).Select(_ => new List())]; + private readonly List _sceneryEdges = []; + private readonly Dictionary> _preview = []; + private readonly Dictionary> _runwaysByTile = []; + private readonly Dictionary _cityLabels = []; + private Palette? _palette; + private StreetMapTiles? _streetMap; + private bool _redrawQueued; + + private double _centerX = 0.5, _centerY = 0.5, _scale; + private Point _pressedAt, _lastMouse; + private DragMode _drag; + private bool _moved; + + public TileMapView() + { + Focusable = true; + ClipToBounds = true; + Unloaded += (_, _) => + { + _streetMap?.Dispose(); + _streetMap = null; + }; + } + + private enum DragMode + { + None, + Pan, + Pick, + Drop, + } + + private enum Shade + { + NoScenery, + Land, + Picked, + Built, + PickedBuilt, + Building, + Failed, + } + + /// The tile under the mouse, or null; for the line under the map. + public event EventHandler? HoverChanged; + + public TileMapModel? Model + { + get => (TileMapModel?)GetValue(ModelProperty); + set => SetValue(ModelProperty, value); + } + + public bool ShowStreetMap + { + get => (bool)GetValue(ShowStreetMapProperty); + set => SetValue(ShowStreetMapProperty, value); + } + + public IReadOnlyList? Runways + { + get => (IReadOnlyList?)GetValue(RunwaysProperty); + set => SetValue(RunwaysProperty, value); + } + + public AirportZoomPreview? AirportPreview + { + get => (AirportZoomPreview?)GetValue(AirportPreviewProperty); + set => SetValue(AirportPreviewProperty, value); + } + + /// The cities to name, most important first. + public IReadOnlyList? Cities + { + get => (IReadOnlyList?)GetValue(CitiesProperty); + set => SetValue(CitiesProperty, value); + } + + public bool ShowCities + { + get => (bool)GetValue(ShowCitiesProperty); + set => SetValue(ShowCitiesProperty, value); + } + + /// The sea, and the map around the world (the plain map). + public Brush Background + { + get => (Brush)GetValue(BackgroundProperty); + set => SetValue(BackgroundProperty, value); + } + + /// The land, lines and names of the plain map. + public Brush Foreground + { + get => (Brush)GetValue(ForegroundProperty); + set => SetValue(ForegroundProperty, value); + } + + public Brush PickedBrush + { + get => (Brush)GetValue(PickedBrushProperty); + set => SetValue(PickedBrushProperty, value); + } + + public Brush BuiltBrush + { + get => (Brush)GetValue(BuiltBrushProperty); + set => SetValue(BuiltBrushProperty, value); + } + + public Brush BuildingBrush + { + get => (Brush)GetValue(BuildingBrushProperty); + set => SetValue(BuildingBrushProperty, value); + } + + public Brush FailedBrush + { + get => (Brush)GetValue(FailedBrushProperty); + set => SetValue(FailedBrushProperty, value); + } + + private double PixelsPerDegree => _scale / 360; + + private Palette Colours => _palette ??= new Palette(ColorOf(Background), ColorOf(Foreground), ColorOf(PickedBrush), ColorOf(BuiltBrush), + ColorOf(BuildingBrush), ColorOf(FailedBrush)); + + /// Centres the map on a point at the given zoom, or keeps the zoom when it is null. + public void CenterOn(double lat, double lon, double? pixelsPerDegree = null) + { + _centerX = WorldX(lon); + _centerY = WorldY(lat); + if (pixelsPerDegree is { } ppd) _scale = Math.Clamp(ppd * 360, MinScale, MaxScale); + InvalidateVisual(); + } + + /// Shows the whole box, with a margin, zoomed in no further than . + public void Frame(double west, double south, double east, double north, double maxPixelsPerDegree = MaxScale / 360) + { + double x0 = WorldX(west), x1 = WorldX(east), y0 = WorldY(north), y1 = WorldY(south); + _centerX = (x0 + x1) / 2; + _centerY = (y0 + y1) / 2; + double width = Math.Max(ActualWidth, 100), height = Math.Max(ActualHeight, 100); + double fit = 0.85 * Math.Min(width / Math.Max(x1 - x0, 1e-9), height / Math.Max(y1 - y0, 1e-9)); + _scale = Math.Clamp(Math.Min(fit, maxPixelsPerDegree * 360), MinScale, MaxScale); + InvalidateVisual(); + } + + /// Zooms around the middle of the map, for the zoom buttons. + public void ZoomBy(double factor) + { + if (_scale <= 0) return; + _scale = Math.Clamp(_scale * factor, MinScale, MaxScale); + InvalidateVisual(); + } + + protected override void OnRender(DrawingContext drawingContext) + { + double width = ActualWidth, height = ActualHeight; + Palette colours = Colours; + drawingContext.DrawRectangle(colours.Outside, null, new Rect(0, 0, width, height)); + if (width <= 0 || height <= 0) return; + if (_scale <= 0) _scale = Math.Max(MinScale, Math.Min(width, height)); + + Rect world = new(ToScreen(-180, MaxLatitude), ToScreen(180, -MaxLatitude)); + if (ShowStreetMap) DrawStreetMap(drawingContext, width, height); + else drawingContext.DrawRectangle(colours.Ocean, null, world); + DrawTiles(drawingContext, width, height); + DrawGrid(drawingContext, width, height); + DrawSceneryEdges(drawingContext, width, height); + if (PixelsPerDegree >= FinerTexturesFrom) DrawAirports(drawingContext, width, height); + if (PixelsPerDegree >= LabelsFrom) DrawLabels(drawingContext, width, height); + if (ShowCities) DrawCities(drawingContext, width, height); + if (_drag is DragMode.Pick or DragMode.Drop && _moved) + drawingContext.DrawRectangle(colours.RectangleFill, colours.RectanglePen, new Rect(_pressedAt, _lastMouse)); + } + + protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e) + { + base.OnMouseLeftButtonDown(e); + Focus(); + _pressedAt = _lastMouse = e.GetPosition(this); + _moved = false; + _drag = Keyboard.Modifiers.HasFlag(ModifierKeys.Shift) ? DragMode.Pick + : Keyboard.Modifiers.HasFlag(ModifierKeys.Control) ? DragMode.Drop + : DragMode.Pan; + CaptureMouse(); + e.Handled = true; + } + + protected override void OnMouseRightButtonDown(MouseButtonEventArgs e) + { + base.OnMouseRightButtonDown(e); + _pressedAt = _lastMouse = e.GetPosition(this); + _moved = true; + _drag = DragMode.Pan; + CaptureMouse(); + e.Handled = true; + } + + protected override void OnMouseMove(MouseEventArgs e) + { + base.OnMouseMove(e); + Point at = e.GetPosition(this); + HoverChanged?.Invoke(this, TileAt(at)); + if (_drag == DragMode.None) return; + if (!_moved && (at - _pressedAt).Length > ClickSlop) _moved = true; + if (_drag == DragMode.Pan && _moved) + { + _centerX = Math.Clamp(_centerX - (at.X - _lastMouse.X) / _scale, 0, 1); + _centerY = Math.Clamp(_centerY - (at.Y - _lastMouse.Y) / _scale, 0, 1); + } + _lastMouse = at; + InvalidateVisual(); + } + + protected override void OnMouseLeftButtonUp(MouseButtonEventArgs e) + { + base.OnMouseLeftButtonUp(e); + EndDrag(e.GetPosition(this)); + } + + protected override void OnMouseRightButtonUp(MouseButtonEventArgs e) + { + base.OnMouseRightButtonUp(e); + EndDrag(e.GetPosition(this)); + } + + protected override void OnMouseLeave(MouseEventArgs e) + { + base.OnMouseLeave(e); + HoverChanged?.Invoke(this, null); + } + + protected override void OnLostMouseCapture(MouseEventArgs e) + { + base.OnLostMouseCapture(e); + _drag = DragMode.None; + } + + protected override void OnMouseWheel(MouseWheelEventArgs e) + { + base.OnMouseWheel(e); + Point at = e.GetPosition(this); + double x = ScreenToWorldX(at.X), y = ScreenToWorldY(at.Y); + _scale = Math.Clamp(_scale * Math.Pow(1.25, e.Delta / 120.0), MinScale, MaxScale); + // Keep the point under the mouse where it was. + _centerX = Math.Clamp(x - (at.X - ActualWidth / 2) / _scale, 0, 1); + _centerY = Math.Clamp(y - (at.Y - ActualHeight / 2) / _scale, 0, 1); + InvalidateVisual(); + // Over the map the wheel zooms, never scrolls the page. + e.Handled = true; + } + + private void EndDrag(Point at) + { + if (_drag == DragMode.None) return; + DragMode drag = _drag; + _drag = DragMode.None; + ReleaseMouseCapture(); + if (Model is { } model) + { + if (drag == DragMode.Pan && !_moved && TileAt(at) is { } tile) model.Toggle(tile); + else if (drag is DragMode.Pick or DragMode.Drop) model.Select(TilesIn(_pressedAt, at), drag == DragMode.Pick); + } + InvalidateVisual(); + } + + private static DependencyProperty BrushProperty(string name, Color fallback) => DependencyProperty.Register( + name, typeof(Brush), typeof(TileMapView), new PropertyMetadata(Solid(fallback), OnPaletteChanged)); + + private static void OnPaletteChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) + { + var view = (TileMapView)d; + view._palette = null; + view._cityLabels.Clear(); + view.InvalidateVisual(); + } + + private static void OnModelChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) + { + var view = (TileMapView)d; + if (e.OldValue is TileMapModel old) old.Changed -= view.OnTilesChanged; + if (e.NewValue is TileMapModel model) model.Changed += view.OnTilesChanged; + view.RebuildRows(); + } + + private static void OnLookChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) => ((TileMapView)d).InvalidateVisual(); + + private static void OnRunwaysChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) + { + var view = (TileMapView)d; + view._runwaysByTile.Clear(); + if (e.NewValue is IReadOnlyList runways) + { + foreach (Runway runway in runways) + { + double lat = (runway.Lat1 + runway.Lat2) / 2, lon = (runway.Lon1 + runway.Lon2) / 2; + if (Math.Abs(lat) >= 90 || Math.Abs(lon) >= 180) continue; + var tile = new TileCoordinate((int)Math.Floor(lat), (int)Math.Floor(lon)); + if (!view._runwaysByTile.TryGetValue(tile, out List? list)) view._runwaysByTile[tile] = list = []; + list.Add(runway); + } + } + view.InvalidateVisual(); + } + + private static void OnAirportPreviewChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) + { + var view = (TileMapView)d; + view._preview.Clear(); + view.InvalidateVisual(); + } + + private void OnTilesChanged(object? sender, EventArgs e) + { + if (Dispatcher.CheckAccess()) RebuildRows(); + else Dispatcher.BeginInvoke(RebuildRows); + } + + /// Redraws once, soon, however many tiles arrive meanwhile. + private void QueueRedraw() + { + if (_redrawQueued) return; + _redrawQueued = true; + Dispatcher.BeginInvoke(DispatcherPriority.Background, () => + { + _redrawQueued = false; + InvalidateVisual(); + }); + } + + /// Each row of tiles as runs of one shade, so a frame draws a few rectangles per row. + private void RebuildRows() + { + TileMapModel? model = Model; + for (int lat = -90; lat < 90; lat++) + { + List row = _rows[lat + 90]; + row.Clear(); + for (int lon = -180; lon < 180; lon++) + { + Shade shade = model is null ? Shade.NoScenery : ShadeOf(model, new TileCoordinate(lat, lon)); + if (row.Count > 0 && row[^1].Shade == shade && row[^1].East == lon - 1) row[^1] = row[^1] with { East = lon }; + else row.Add(new Run(lon, lon, shade)); + } + } + RebuildSceneryEdges(model); + InvalidateVisual(); + } + + /// The outline of the tiles X-Plane has: every side between a tile it has and one it lacks (or the world's edge). + private void RebuildSceneryEdges(TileMapModel? model) + { + _sceneryEdges.Clear(); + if (model is null || model.AvailableCount == 0) return; + bool Has(int lat, int lon) => lat is >= -90 and < 90 && lon is >= -180 and < 180 && model.IsAvailable(new TileCoordinate(lat, lon)); + for (int lat = -90; lat < 90; lat++) + { + for (int lon = -180; lon < 180; lon++) + { + if (!Has(lat, lon)) continue; + if (!Has(lat, lon - 1)) _sceneryEdges.Add(new Edge(lon, lat, lon, lat + 1)); + if (!Has(lat, lon + 1)) _sceneryEdges.Add(new Edge(lon + 1, lat, lon + 1, lat + 1)); + if (!Has(lat - 1, lon)) _sceneryEdges.Add(new Edge(lon, lat, lon + 1, lat)); + if (!Has(lat + 1, lon)) _sceneryEdges.Add(new Edge(lon, lat + 1, lon + 1, lat + 1)); + } + } + } + + private static Shade ShadeOf(TileMapModel model, TileCoordinate tile) + { + bool picked = model.IsSelected(tile); + return model.StateOf(tile) switch + { + MapTileState.Building => Shade.Building, + MapTileState.Failed => Shade.Failed, + MapTileState.Built => picked ? Shade.PickedBuilt : Shade.Built, + _ => picked ? Shade.Picked : model.IsAvailable(tile) ? Shade.Land : Shade.NoScenery, + }; + } + + private void DrawStreetMap(DrawingContext dc, double width, double height) + { + _streetMap ??= CreateStreetMap(); + double pixelsPerDip = VisualTreeHelper.GetDpi(this).PixelsPerDip; + int zoom = Math.Clamp((int)Math.Round(Math.Log2(_scale * pixelsPerDip / 256)), 0, StreetMapTiles.MaxZoom); + int n = 1 << zoom; + int x0 = Math.Clamp((int)Math.Floor(ScreenToWorldX(0) * n), 0, n - 1), x1 = Math.Clamp((int)Math.Floor(ScreenToWorldX(width) * n), 0, n - 1); + int y0 = Math.Clamp((int)Math.Floor(ScreenToWorldY(0) * n), 0, n - 1), y1 = Math.Clamp((int)Math.Floor(ScreenToWorldY(height) * n), 0, n - 1); + var missing = new List(); + for (int y = y0; y <= y1; y++) + { + for (int x = x0; x <= x1; x++) + { + var tile = new StreetMapTile(zoom, x, y); + Rect rect = WorldRect(x, y, n, pixelsPerDip); + if (_streetMap.TryGet(tile) is { } image) + { + dc.DrawImage(image, rect); + continue; + } + missing.Add(tile); + // Meanwhile, the part of a coarser tile in memory. + for (int up = 1; up <= Math.Min(zoom, 8); up++) + { + if (_streetMap.TryGet(new StreetMapTile(zoom - up, x >> up, y >> up)) is not { } coarser) continue; + dc.PushClip(new RectangleGeometry(rect)); + dc.DrawImage(coarser, WorldRect(x >> up, y >> up, n >> up, pixelsPerDip)); + dc.Pop(); + break; + } + } + } + double cx = _centerX * n, cy = _centerY * n; + _streetMap.Want([.. missing.OrderBy(t => (t.X + 0.5 - cx) * (t.X + 0.5 - cx) + (t.Y + 0.5 - cy) * (t.Y + 0.5 - cy))]); + } + + private StreetMapTiles CreateStreetMap() + { + var tiles = new StreetMapTiles(); + tiles.TileLoaded += (_, _) => Dispatcher.BeginInvoke(QueueRedraw); + return tiles; + } + + private void DrawTiles(DrawingContext dc, double width, double height) + { + Brush?[] fills = ShowStreetMap ? Colours.StreetFill : Colours.PlainFill; + var (west, north) = ToGeo(new Point(0, 0)); + var (east, south) = ToGeo(new Point(width, height)); + int firstLat = Math.Max((int)Math.Floor(south), -86), lastLat = Math.Min((int)Math.Floor(north), 85); + for (int lat = firstLat; lat <= lastLat; lat++) + { + double top = ToScreen(0, Math.Min(lat + 1, MaxLatitude)).Y, bottom = ToScreen(0, Math.Max(lat, -MaxLatitude)).Y; + foreach (Run run in _rows[lat + 90]) + { + if (run.East + 1 < west || run.West > east || fills[(int)run.Shade] is not { } fill) continue; + double left = ToScreen(Math.Max(run.West, west - 1), 0).X, right = ToScreen(Math.Min(run.East + 1, east + 1), 0).X; + dc.DrawRectangle(fill, null, new Rect(left, top, right - left, bottom - top)); + } + } + } + + private void DrawGrid(DrawingContext dc, double width, double height) + { + var (west, north) = ToGeo(new Point(0, 0)); + var (east, south) = ToGeo(new Point(width, height)); + int step = PixelsPerDegree >= GridFrom ? 1 : 10; + Palette colours = Colours; + Pen degree = ShowStreetMap ? colours.StreetDegreePen : colours.DegreePen, tenDegrees = ShowStreetMap ? colours.StreetTenDegreePen : colours.TenDegreePen; + double top = ToScreen(0, MaxLatitude).Y, bottom = ToScreen(0, -MaxLatitude).Y; + for (int lon = (int)Math.Ceiling(Math.Max(west, -180) / step) * step; lon <= Math.Min(east, 180); lon += step) + { + double x = ToScreen(lon, 0).X; + dc.DrawLine(lon % 10 == 0 ? tenDegrees : degree, new Point(x, top), new Point(x, bottom)); + } + double left = ToScreen(-180, 0).X, right = ToScreen(180, 0).X; + for (int lat = (int)Math.Ceiling(Math.Max(south, -85) / step) * step; lat <= Math.Min(north, 85); lat += step) + { + double y = ToScreen(0, lat).Y; + dc.DrawLine(lat % 10 == 0 ? tenDegrees : degree, new Point(left, y), new Point(right, y)); + } + } + + private void DrawSceneryEdges(DrawingContext dc, double width, double height) + { + if (_sceneryEdges.Count == 0) return; + var (west, north) = ToGeo(new Point(0, 0)); + var (east, south) = ToGeo(new Point(width, height)); + Pen pen = ShowStreetMap ? Colours.StreetSceneryPen : Colours.SceneryPen; + foreach (Edge edge in _sceneryEdges) + { + if (edge.East < west || edge.West > east || edge.North < south || edge.South > north) continue; + dc.DrawLine(pen, + ToScreen(edge.West, Math.Clamp(edge.South, -MaxLatitude, MaxLatitude)), + ToScreen(edge.East, Math.Clamp(edge.North, -MaxLatitude, MaxLatitude))); + } + } + + /// The finer textures near airports (when the rules are on), then the runways over them. + private void DrawAirports(DrawingContext dc, double width, double height) + { + var (west, north) = ToGeo(new Point(0, 0)); + var (east, south) = ToGeo(new Point(width, height)); + int firstLat = Math.Max((int)Math.Floor(south), -85), lastLat = Math.Min((int)Math.Floor(north), 84); + int firstLon = Math.Max((int)Math.Floor(west), -180), lastLon = Math.Min((int)Math.Floor(east), 179); + + if (AirportPreview is { } preview && PixelsPerDegree >= FinerTexturesFrom) + { + int computed = 0; + bool more = false; + // Opaque inside one layer made translucent as a whole: overlapping textures do not darken each other. + dc.PushOpacity(0.45); + for (int lat = firstLat; lat <= lastLat; lat++) + { + for (int lon = firstLon; lon <= lastLon; lon++) + { + var tile = new TileCoordinate(lat, lon); + if (!_preview.TryGetValue(tile, out IReadOnlyList? textures)) + { + if (computed >= PreviewTilesPerFrame) + { + more = true; + continue; + } + _preview[tile] = textures = preview.TexturesOf(tile); + computed++; + } + foreach (FinerTexture texture in textures) + { + Brush fill = FinerFills[Math.Clamp(texture.Zoom - preview.BaseZoom - 1, 0, FinerFills.Length - 1)]; + dc.DrawRectangle(fill, null, new Rect(ToScreen(texture.West, texture.North), ToScreen(texture.East, texture.South))); + } + } + } + dc.Pop(); + if (more) QueueRedraw(); + } + + // Runways only once they are long enough to read as lines, not dots. + if (PixelsPerDegree < RunwaysFrom) return; + for (int lat = firstLat; lat <= lastLat; lat++) + { + for (int lon = firstLon; lon <= lastLon; lon++) + { + if (!_runwaysByTile.TryGetValue(new TileCoordinate(lat, lon), out List? runways)) continue; + foreach (Runway runway in runways) + { + Point a = ToScreen(runway.Lon1, runway.Lat1), b = ToScreen(runway.Lon2, runway.Lat2); + dc.DrawLine(RunwayCasing, a, b); + dc.DrawLine(RunwayPen, a, b); + } + } + } + } + + private void DrawLabels(DrawingContext dc, double width, double height) + { + double pixelsPerDip = VisualTreeHelper.GetDpi(this).PixelsPerDip; + Brush brush = ShowStreetMap ? Colours.StreetLabel : Colours.Label; + var (west, north) = ToGeo(new Point(0, 0)); + var (east, south) = ToGeo(new Point(width, height)); + for (int lat = Math.Max((int)Math.Floor(south), -85); lat <= Math.Min((int)Math.Floor(north), 84); lat++) + { + for (int lon = Math.Max((int)Math.Floor(west), -180); lon <= Math.Min((int)Math.Floor(east), 179); lon++) + { + var text = new FormattedText(new TileCoordinate(lat, lon).Name, CultureInfo.InvariantCulture, FlowDirection.LeftToRight, + LabelFace, Math.Min(14, PixelsPerDegree / 6), brush, pixelsPerDip); + Point corner = ToScreen(lon, lat + 1); + dc.DrawText(text, new Point(corner.X + 4, corner.Y + 3)); + } + } + } + + /// + /// Names the cities big enough for the zoom, most important first, each beside its dot (right, else left); a name that + /// would overlap one already placed is left out. + /// + private void DrawCities(DrawingContext dc, double width, double height) + { + if (Cities is not { } cities) return; + double zoom = Math.Log2(_scale / 256) + CityZoomBias; + Brush text = ShowStreetMap ? StreetCityText : Colours.CityText; + Pen halo = ShowStreetMap ? StreetCityHalo : Colours.CityHalo; + var placed = new List(); + foreach (GlobalCity city in cities) + { + if (city.MinZoom > zoom || placed.Count >= MaxCityLabels) break; + Point at = ToScreen(city.Lon, city.Lat); + if (at.X < -100 || at.X > width + 100 || at.Y < -20 || at.Y > height + 20 || Math.Abs(city.Lat) > MaxLatitude) continue; + Geometry label = CityLabel(city); + Rect bounds = label.Bounds; + double radius = city.IsCapital ? 3.2 : 2.4; + Rect right = new(at.X + radius + 3, at.Y - bounds.Height / 2 - 1, bounds.Width + 2, bounds.Height + 2); + Rect left = new(at.X - radius - 3 - bounds.Width - 2, right.Y, right.Width, right.Height); + Rect box = Overlaps(placed, right) ? left : right; + if (Overlaps(placed, box)) continue; + placed.Add(box); + placed.Add(new Rect(at.X - radius - 1, at.Y - radius - 1, 2 * radius + 2, 2 * radius + 2)); + dc.DrawEllipse(text, halo, at, radius, radius); + dc.PushTransform(new TranslateTransform(box.X + 1 - bounds.X, box.Y + 1 - bounds.Y)); + dc.DrawGeometry(null, halo, label); + dc.DrawGeometry(text, null, label); + dc.Pop(); + } + + static bool Overlaps(List placed, Rect box) + { + foreach (Rect other in placed) + { + if (other.IntersectsWith(box)) return true; + } + return false; + } + } + + /// A city's name as outlines (so it can have a halo), made once: capitals and the largest cities stand out. + private Geometry CityLabel(GlobalCity city) + { + if (_cityLabels.TryGetValue(city, out Geometry? label)) return label; + bool major = city.IsCapital || city.MinZoom < 4; + var text = new FormattedText(city.Name, CultureInfo.InvariantCulture, FlowDirection.LeftToRight, major ? MajorCityFace : CityFace, + city.IsCapital ? 13.5 : major ? 12.5 : 11.5, Brushes.Black, VisualTreeHelper.GetDpi(this).PixelsPerDip); + label = text.BuildGeometry(new Point(0, 0)); + label.Freeze(); + _cityLabels[city] = label; + return label; + } + + private IEnumerable TilesIn(Point a, Point b) + { + var (lon1, lat1) = ToGeo(a); + var (lon2, lat2) = ToGeo(b); + int west = Math.Max((int)Math.Floor(Math.Min(lon1, lon2)), -180), east = Math.Min((int)Math.Floor(Math.Max(lon1, lon2)), 179); + int south = Math.Max((int)Math.Floor(Math.Min(lat1, lat2)), -90), north = Math.Min((int)Math.Floor(Math.Max(lat1, lat2)), 89); + for (int lat = south; lat <= north; lat++) + { + for (int lon = west; lon <= east; lon++) yield return new TileCoordinate(lat, lon); + } + } + + private TileCoordinate? TileAt(Point at) + { + var (lon, lat) = ToGeo(at); + int tileLat = (int)Math.Floor(lat), tileLon = (int)Math.Floor(lon); + return tileLat is >= -90 and <= 89 && tileLon is >= -180 and <= 179 && Math.Abs(lat) < MaxLatitude ? new TileCoordinate(tileLat, tileLon) : null; + } + + /// Web Mercator from 0 at 180°W to 1 at 180°E. + private static double WorldX(double lon) => (lon + 180) / 360; + + /// Web Mercator from 0 at the top (85.05°N) to 1 at the bottom. + private static double WorldY(double lat) + { + double phi = Math.Clamp(lat, -MaxLatitude, MaxLatitude) * Math.PI / 180; + return (1 - Math.Log(Math.Tan(Math.PI / 4 + phi / 2)) / Math.PI) / 2; + } + + private double ScreenToWorldX(double x) => _centerX + (x - ActualWidth / 2) / _scale; + + private double ScreenToWorldY(double y) => _centerY + (y - ActualHeight / 2) / _scale; + + private Point ToScreen(double lon, double lat) => + new((WorldX(lon) - _centerX) * _scale + ActualWidth / 2, (WorldY(lat) - _centerY) * _scale + ActualHeight / 2); + + private (double Lon, double Lat) ToGeo(Point p) + { + double y = ScreenToWorldY(p.Y); + return (ScreenToWorldX(p.X) * 360 - 180, Math.Atan(Math.Sinh(Math.PI * (1 - 2 * y))) * 180 / Math.PI); + } + + /// A street-map tile's place on screen, on whole device pixels so neighbours meet without a seam. + private Rect WorldRect(int x, int y, int n, double pixelsPerDip) + { + double Snap(double value) => Math.Round(value * pixelsPerDip) / pixelsPerDip; + double left = Snap(((double)x / n - _centerX) * _scale + ActualWidth / 2), right = Snap(((double)(x + 1) / n - _centerX) * _scale + ActualWidth / 2); + double top = Snap(((double)y / n - _centerY) * _scale + ActualHeight / 2), bottom = Snap(((double)(y + 1) / n - _centerY) * _scale + ActualHeight / 2); + return new Rect(left, top, right - left, bottom - top); + } + + private static Color ColorOf(Brush? brush) => brush is SolidColorBrush solid ? solid.Color : Colors.Gray; + + private static SolidColorBrush Solid(Color color) => Frozen(new SolidColorBrush(color)); + + private static T Frozen(T freezable) where T : Freezable + { + freezable.Freeze(); + return freezable; + } + + /// Tiles to (inclusive) of one row, all of one shade. + private readonly record struct Run(int West, int East, Shade Shade); + + /// One side of a tile, in degrees: west to east along a parallel, or south to north along a meridian. + private readonly record struct Edge(int West, int South, int East, int North); + + /// + /// The map's brushes and pens, made from the theme's colours: the plain map draws the land in a wash of the text colour + /// over the background, and the picked, built, building and failed tiles in the accent and status colours; over the + /// street map the tiles X-Plane has are left clear, the others greyed out and the states translucent. Either way an + /// outline goes round the tiles X-Plane has. + /// + private sealed class Palette + { + public Palette(Color background, Color ink, Color picked, Color built, Color building, Color failed) + { + Color pickedBuilt = Mix(picked, built); + Outside = Solid(background); + Ocean = Solid(Mix(background, ink, 0.04)); + PlainFill = [null, Solid(Mix(background, ink, 0.22)), Solid(picked), Solid(built), Solid(pickedBuilt), Solid(building), Solid(failed)]; + // The tiles X-Plane lacks are greyed out (a light veil alone vanishes over OpenStreetMap's light colours). + StreetFill = [Solid(WithAlpha(Mix(background, ink, 0.15), 0xB0)), null, Solid(WithAlpha(picked, 0x88)), Solid(WithAlpha(built, 0x80)), + Solid(WithAlpha(pickedBuilt, 0x88)), Solid(WithAlpha(building, 0x90)), Solid(WithAlpha(failed, 0x90))]; + DegreePen = Frozen(new Pen(Solid(WithAlpha(ink, 0x22)), 1)); + TenDegreePen = Frozen(new Pen(Solid(WithAlpha(ink, 0x55)), 1)); + StreetDegreePen = Frozen(new Pen(Solid(WithAlpha(StreetInk, 0x50)), 1)); + StreetTenDegreePen = Frozen(new Pen(Solid(WithAlpha(StreetInk, 0x90)), 1)); + SceneryPen = Frozen(new Pen(Solid(WithAlpha(ink, 0xB0)), 1.5)); + StreetSceneryPen = Frozen(new Pen(Solid(WithAlpha(StreetInk, 0xD0)), 1.5)); + Label = Solid(WithAlpha(ink, 0xC0)); + StreetLabel = Solid(WithAlpha(StreetInk, 0xD0)); + CityText = Solid(ink); + CityHalo = Frozen(new Pen(Solid(WithAlpha(background, 0xD0)), 3) { LineJoin = PenLineJoin.Round }); + RectangleFill = Solid(WithAlpha(picked, 0x30)); + RectanglePen = Frozen(new Pen(Solid(picked), 1.5) { DashStyle = DashStyles.Dash }); + } + + public Brush Outside { get; } + public Brush Ocean { get; } + + /// A fill per , null for none. + public Brush?[] PlainFill { get; } + public Brush?[] StreetFill { get; } + public Pen DegreePen { get; } + public Pen TenDegreePen { get; } + public Pen StreetDegreePen { get; } + public Pen StreetTenDegreePen { get; } + + /// The outline of the tiles X-Plane has. + public Pen SceneryPen { get; } + public Pen StreetSceneryPen { get; } + public Brush Label { get; } + public Brush StreetLabel { get; } + public Brush CityText { get; } + public Pen CityHalo { get; } + public Brush RectangleFill { get; } + public Pen RectanglePen { get; } + + private static Color WithAlpha(Color color, byte alpha) => Color.FromArgb(alpha, color.R, color.G, color.B); + + private static Color Mix(Color a, Color b, double share = 0.5) => Color.FromRgb( + (byte)Math.Round(a.R + (b.R - a.R) * share), (byte)Math.Round(a.G + (b.G - a.G) * share), (byte)Math.Round(a.B + (b.B - a.B) * share)); + } +} diff --git a/src/OrthoStreamXP/Gui/ViewModels/BuildSceneryViewModel.cs b/src/OrthoStreamXP/Gui/ViewModels/BuildSceneryViewModel.cs new file mode 100644 index 0000000..7329514 --- /dev/null +++ b/src/OrthoStreamXP/Gui/ViewModels/BuildSceneryViewModel.cs @@ -0,0 +1,476 @@ +using System.Collections.ObjectModel; +using System.Globalization; +using System.Windows.Input; +using OrthoGlobalXP.Airports; +using OrthoGlobalXP.Building; +using OrthoGlobalXP.Geo; +using OrthoGlobalXP.Imagery; +using OrthoGlobalXP.Regions; +using OrthoGlobalXP.Scenery; +using OrthoStreamXP.Setup; +using GlobalCity = OrthoGlobalXP.Regions.City; + +namespace OrthoStreamXP.Gui; + +/// A box of the map to show, in degrees. +internal sealed record MapFrame(double West, double South, double East, double North); + +/// +/// The Build Scenery page: photo-terrain packages made on this PC from X-Plane's own Global Scenery (OrthoGlobalXP's +/// engine). Tiles are picked on the map, by country or region, by name or from a list; each goes into its continent's +/// package (OrthoGlobal_Europe_XP, OrthoGlobal_NorthAmerica_XP…, unlike the downloaded OrthoStream_Eur…) in the chosen +/// folder, its roads, forests and buildings into OrthoGlobal_Overlays_XP beside +/// them. OrthoStreamXP streams them from its next start when the folder is its packages folder. +/// +internal sealed class BuildSceneryViewModel : ObservableObject, IPage +{ + private const int MaxLogLines = 2000; + + private readonly MountController _mount; + private readonly Func _xplane; + private readonly Func _packagesFolder; + private readonly Action _setPackagesFolder; + private readonly SceneryBuildPreferencesStore _store; + private SceneryBuildPreferences _choices; + private string? _loadedXPlane; + private bool _picksRestored, _loading, _isBuilding; + private string _hoverText = "", _status = "", _sceneryText = ""; + private int _progressValue, _progressMaximum = 1; + private IReadOnlyList? _runways; + private AirportZoomPreview? _airportPreview; + private Action? _stop; + + /// The X-Plane folder of the settings; null while there is none. + /// OrthoStreamXP's packages folder (base-packages); null while there is none. + /// + /// Sets OrthoStreamXP's packages folder, as Settings does (which may refuse it: tells). + /// + public BuildSceneryViewModel(MountController mount, Func xplane, Func packagesFolder, Action setPackagesFolder, + SceneryBuildPreferencesStore store) + { + _mount = mount; + _xplane = xplane; + _packagesFolder = packagesFolder; + _setPackagesFolder = setPackagesFolder; + _store = store; + _choices = store.Load(); + Regions = new RegionSearch(RegionCatalog.All); + Map.Changed += (_, _) => + { + Raise(nameof(SelectionText)); + RelayCommand.Refresh(); + }; + BrowseTarget = new RelayCommand(BrowseTargetFolder, () => IsIdle); + StreamFromTarget = new RelayCommand(MakeTargetThePackagesFolder, () => IsIdle && _mount.IsStopped && TargetFolder.Length > 0 && !IsPackagesFolder); + OpenTarget = new RelayCommand(() => Shell.Open(TargetFolder), () => Directory.Exists(TargetFolder)); + PickRegion = new RelayCommand(() => SelectRegion(true), () => IsIdle && Regions.Selected is not null && Map.AvailableCount > 0); + DropRegion = new RelayCommand(() => SelectRegion(false), () => IsIdle && Regions.Selected is not null && Map.Selected.Count > 0); + ClearPicks = new RelayCommand(Map.ClearSelection, () => IsIdle && Map.Selected.Count > 0); + Build = new RelayCommand(() => _ = BuildAsync(), () => IsIdle && !_loading && Map.Selected.Count > 0 && TargetFolder.Length > 0); + Stop = new RelayCommand(() => _stop?.Invoke(), () => IsBuilding && _stop is not null); + _mount.PropertyChanged += (_, e) => + { + if (e.PropertyName != nameof(MountController.State)) return; + Raise(nameof(RunningNote)); + Raise(nameof(TargetNote)); + RelayCommand.Refresh(); + }; + } + + /// Asks the view to show a part of the map. + public event EventHandler? FrameRequested; + + /// A build ended with tiles of the packages in this folder (built now or up to date already). + public event EventHandler? TilesBuilt; + + public TileMapModel Map { get; } = new(); + + public RegionSearch Regions { get; } + + /// The cities the map names (Natural Earth's, in the engine). + public IReadOnlyList Cities { get; } = CityCatalog.All; + + /// What the page did, newest last; also written to OrthoStreamXP's log. + public ObservableCollection BuildLog { get; } = []; + + public ICommand BrowseTarget { get; } + /// Makes the target folder OrthoStreamXP's packages folder (Settings), so it streams what is built there. + public ICommand StreamFromTarget { get; } + public ICommand OpenTarget { get; } + public ICommand PickRegion { get; } + public ICommand DropRegion { get; } + public ICommand ClearPicks { get; } + public ICommand Build { get; } + public ICommand Stop { get; } + + /// Whether X-Plane's Global Scenery was found, and how many tiles it has. + public string SceneryText { get => _sceneryText; private set => Set(ref _sceneryText, value); } + + /// The folder the packages are made in: the one chosen, else OrthoStreamXP's packages folder. + public string TargetFolder => _choices.TargetFolder ?? _packagesFolder() ?? ""; + + /// The target is OrthoStreamXP's packages folder, so it streams the packages made there. + public bool IsPackagesFolder => _packagesFolder() is { } packages && SamePath(packages, TargetFolder); + + /// A warning when OrthoStreamXP would not stream what is made in the target. + public string TargetNote => TargetFolder.Length == 0 + ? "Choose a folder to build your packages in." + : IsPackagesFolder ? "" + : "OrthoStreamXP will not stream the packages built here: its scenery packages folder is a different folder. " + + "Press \"Stream from here\" to make it this one" + + (_mount.IsStopped ? "." : " (stop streaming first)."); + + /// What the target folder is for. + public string TargetFolderHelp { get; } = + "Your own packages are built in this folder. Keep it for them only, apart from scenery packages from other sources."; + + public bool ShowStreetMap { get => _choices.ShowStreetMap; set => Change(_choices with { ShowStreetMap = value }); } + + public bool ShowCities { get => _choices.ShowCities; set => Change(_choices with { ShowCities = value }); } + + /// X-Plane's runways, once read; the map draws them. + public IReadOnlyList? Runways { get => _runways; private set => Set(ref _runways, value); } + + /// The finer textures the airport rule gives, for the map; null when it is off. + public AirportZoomPreview? AirportPreview { get => _airportPreview; private set => Set(ref _airportPreview, value); } + + + /// The tile under the mouse. + public string HoverText { get => _hoverText; private set => Set(ref _hoverText, value); } + + public string Status { get => _status; private set => Set(ref _status, value); } + + public int ProgressValue { get => _progressValue; private set => Set(ref _progressValue, value); } + + public int ProgressMaximum { get => _progressMaximum; private set => Set(ref _progressMaximum, value); } + + public bool IsBuilding + { + get => _isBuilding; + private set + { + if (!Set(ref _isBuilding, value)) return; + Raise(nameof(IsIdle)); + RelayCommand.Refresh(); + } + } + + public bool IsIdle => !IsBuilding; + + public string SelectionText => Map.Selected.Count switch + { + 0 => "No tiles picked", + 1 => "1 tile picked", + int n => Invariant($"{n:N0} tiles picked"), + }; + + /// While OrthoStreamXP runs, the packages made are streamed from its next start. + public string RunningNote => _mount.IsStopped ? "" : "OrthoStreamXP is running: what you build now is streamed from its next start."; + + /// Reads X-Plane's Global Scenery and runways the first time, and again when the X-Plane folder changed. + public void OnShown() + { + Raise(nameof(TargetFolder)); + Raise(nameof(IsPackagesFolder)); + Raise(nameof(TargetNote)); + if (!IsBuilding && !_loading && _xplane() != _loadedXPlane) _ = LoadGlobalSceneryAsync(); + else RefreshBuiltTiles(); + } + + public void SetHover(TileCoordinate? tile) + { + if (tile is not { } t) + { + HoverText = ""; + return; + } + string what = Map.StateOf(t) == MapTileState.Built ? "built" : Map.IsAvailable(t) ? "X-Plane scenery" : "no X-Plane scenery (sea)"; + HoverText = $"{t.Name}: {what} · {SceneryBuildPreferences.ToPackageOptions(TargetFolder).PackageNameOf(Continent.Of(t))}"; + } + + /// Remembers the choices and the picked tiles, for the next start. + public void SaveChoices() + { + if (_picksRestored) _choices = _choices with { PickedTiles = [.. Map.Selected.Select(t => t.Name).Order(StringComparer.Ordinal)] }; + _store.Save(_choices); + } + + /// Takes a changed choice and remembers it; false when nothing changed. + private bool Change(SceneryBuildPreferences choices, [System.Runtime.CompilerServices.CallerMemberName] string? name = null) + { + if (choices == _choices) return false; + _choices = choices; + Raise(name); + _store.Save(_choices); + return true; + } + + private void SetTarget(string? folder) + { + Change(_choices with { TargetFolder = folder }, nameof(TargetFolder)); + Raise(nameof(IsPackagesFolder)); + Raise(nameof(TargetNote)); + RelayCommand.Refresh(); + RefreshBuiltTiles(); + } + + private void MakeTargetThePackagesFolder() + { + string folder = TargetFolder; + _setPackagesFolder(folder); + if (_packagesFolder() is { } packages && SamePath(packages, folder)) + { + // Now "the packages folder", so the target follows a later change of it in Settings (as a folder chosen here would). + SetTarget(null); + Status = $"OrthoStreamXP's scenery packages folder is now {folder}: it streams the packages built here."; + AddLog(Status); + return; + } + Status = $"{folder} cannot be the scenery packages folder: choose X-Plane's folder first, and keep this folder out of X-Plane's Custom Scenery."; + AddLog(Status, warning: true); + SetTarget(folder); + } + + private void BrowseTargetFolder() + { + if (Shell.PickFolder("Folder the scenery packages are made in (OrthoStreamXP's packages folder)", TargetFolder) is not { } folder) return; + // The packages folder itself is kept as "the packages folder", so it follows a change of it in Settings. + SetTarget(_packagesFolder() is { } packages && SamePath(packages, folder) ? null : folder); + } + + private void SelectRegion(bool pick) + { + if (Regions.Selected?.Region is not { } region) return; + int before = Map.Selected.Count; + Map.Select(region.Tiles, pick); + int changed = Math.Abs(Map.Selected.Count - before), withScenery = region.Tiles.Count(Map.IsAvailable); + AddLog(pick + ? Invariant($"Picked {changed:N0} tiles of {region.Name}: it touches {region.Tiles.Count:N0}, {withScenery:N0} with X-Plane scenery") + : Invariant($"Unpicked {changed:N0} tiles of {region.Name}")); + if (pick) FrameTiles(region.Tiles); + } + + /// Shows the tiles, leaving out the farthest few (Alaska's Aleutians, overseas islands) so the bulk fills the map. + private void FrameTiles(IReadOnlyCollection tiles) + { + if (tiles.Count == 0) return; + int[] lats = [.. tiles.Select(t => t.Lat).Order()], lons = [.. tiles.Select(t => t.Lon).Order()]; + int low = tiles.Count >= 50 ? tiles.Count / 50 : 0, high = tiles.Count - 1 - low; + FrameRequested?.Invoke(this, new MapFrame(lons[low], lats[low], lons[high] + 1, lats[high] + 1)); + } + + private void UpdateAirportPreview() + { + try + { + AirportPreview = Runways is { Count: > 0 } runways ? new AirportZoomPreview(runways, SceneryBuildPreferences.AirportZoomOptions, SceneryBuildPreferences.Zoom) : null; + } + catch (ArgumentException ex) + { + AirportPreview = null; + Status = ex.Message; + } + } + + private async Task LoadGlobalSceneryAsync() + { + string? folder = _xplane(); + _loadedXPlane = folder; + if (folder is null) + { + Map.SetAvailable([]); + SceneryText = "Choose your X-Plane folder in Settings first: its Global Scenery is what the packages are made from."; + return; + } + _loading = true; + SceneryText = "Reading X-Plane's Global Scenery…"; + RelayCommand.Refresh(); + try + { + IReadOnlyList tiles = await Task.Run(() => new GlobalScenery(folder).Tiles()).ConfigureAwait(true); + Map.SetAvailable(tiles); + SceneryText = Invariant($"X-Plane's Global Scenery and Demo Areas have {tiles.Count:N0} tiles ({folder}). They are read, never changed."); + RestorePicks(); + RefreshBuiltTiles(); + _ = LoadRunwaysAsync(folder); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + Map.SetAvailable([]); + SceneryText = ex.Message; + Log.Warning($"Build Scenery: {ex.Message}"); + } + catch (Exception ex) + { + // Runs unawaited from the page: nothing that goes wrong may vanish. + Map.SetAvailable([]); + SceneryText = $"X-Plane's Global Scenery could not be read: {ex.Message}"; + Log.Error("Build Scenery: X-Plane's Global Scenery could not be read", ex); + } + finally + { + _loading = false; + RelayCommand.Refresh(); + } + } + + /// The tiles picked in the last session, once X-Plane's are known (only those can be picked). + private void RestorePicks() + { + if (_picksRestored) return; + _picksRestored = true; + TileCoordinate[] picked = [.. _choices.PickedTiles.Select(n => TileCoordinate.TryParse(n, out TileCoordinate t) ? t : (TileCoordinate?)null).OfType()]; + if (picked.Length == 0) return; + Map.Select(picked, true); + FrameTiles(picked); + } + + /// Reads X-Plane's runways in the background, for the map and the finer photos near airports. + private async Task LoadRunwaysAsync(string folder) + { + Runways = null; + UpdateAirportPreview(); + try + { + IReadOnlyList runways = await Task.Run(() => AirportData.LoadRunwaysAsync(folder)).ConfigureAwait(true); + if (folder != _loadedXPlane) return; + Runways = runways; + UpdateAirportPreview(); + if (runways.Count == 0) AddLog("X-Plane's apt.dat was not found: no finer photos near airports.", warning: true); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + AddLog($"X-Plane's apt.dat could not be read: {ex.Message}", warning: true); + } + catch (Exception ex) + { + // Runs unawaited: nothing that goes wrong may vanish. + Log.Error("Build Scenery: X-Plane's runways could not be read", ex); + } + } + + private void RefreshBuiltTiles() + { + if (IsBuilding) return; + try + { + Map.SetBuilt(TargetFolder.Length > 0 ? PackageTiles.Find(new PackageOptions { OutputFolder = TargetFolder }) : []); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + AddLog($"The packages' tiles could not be listed: {ex.Message}", warning: true); + } + } + + private async Task BuildAsync() + { + PackageOptions options; + GlobalScenery scenery; + try + { + options = SceneryBuildPreferences.ToPackageOptions(TargetFolder); + options.Validate(); + scenery = new GlobalScenery(_xplane() ?? throw new DirectoryNotFoundException("Choose your X-Plane folder in Settings first.")); + } + catch (Exception ex) when (ex is ArgumentException or IOException) + { + Status = ex.Message; + AddLog(ex.Message, warning: true); + return; + } + SaveChoices(); + + TileCoordinate[] tiles = [.. Map.Selected.OrderByDescending(t => t.Lat).ThenBy(t => t.Lon)]; + ProgressMaximum = tiles.Length; + ProgressValue = 0; + IsBuilding = true; + using var cancel = new CancellationTokenSource(); + _stop = cancel.Cancel; + RelayCommand.Refresh(); + string continents = string.Join(", ", tiles.GroupBy(Continent.Of).OrderBy(g => g.Key.Name, StringComparer.Ordinal) + .Select(g => Invariant($"{g.Count():N0} in {options.PackageNameOf(g.Key)}"))); + AddLog(Invariant($"Building {tiles.Length:N0} tiles, {options.Workers} at once, into {options.OutputFolder}: {continents} (ZL{options.Imagery.Zoom}") + + (options.AirportZoom is { } airports ? $", {airports}" : "") + ", " + + (options.KeepOverlays ? $"X-Plane's roads, forests and buildings into {options.OverlayPackageName}" : "without X-Plane's roads, forests and buildings") + ")"); + Status = "Starting…"; + var progress = new Progress(OnProgress); + try + { + var builder = new PackageBuilder(scenery, options, Runways is { Count: > 0 } runways ? runways : null); + BuildSummary summary = await Task.Run(() => builder.BuildAsync(tiles, progress, cancel.Token)).ConfigureAwait(true); + Status = Invariant($"{(summary.Cancelled ? "Stopped" : "Done")} in {summary.Elapsed:hh\\:mm\\:ss}: {summary.Built:N0} built, {summary.UpToDate:N0} up to date, ") + + Invariant($"{summary.Failed:N0} failed, {summary.NoSource:N0} without X-Plane scenery."); + AddLog(Status, warning: summary.Failed > 0); + if (summary.Built + summary.UpToDate > 0) TilesBuilt?.Invoke(this, options.OutputFolder); + if (summary.Built > 0 && IsPackagesFolder) + AddLog(_mount.IsStopped + ? "Start OrthoStreamXP (before X-Plane) to stream the new tiles." + : "Stop and start OrthoStreamXP (with X-Plane closed) so it mounts the new tiles."); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException) + { + Status = $"The build stopped: {ex.Message}"; + AddLog(Status, warning: true); + } + catch (Exception ex) + { + // Runs unawaited from a button: nothing that goes wrong may vanish. + Status = $"The build stopped: {ex.Message}"; + Log.Error("Build Scenery: the build stopped", ex); + BuildLog.Add($"{DateTime.Now:HH:mm:ss} {Status}"); + } + finally + { + _stop = null; + IsBuilding = false; + RefreshBuiltTiles(); + } + } + + private void OnProgress(TileProgress p) + { + switch (p.State) + { + case TileState.Building: + Map.SetState(p.Tile, MapTileState.Building); + Status = Invariant($"Building {p.Tile.Name}… ({ProgressValue:N0} of {ProgressMaximum:N0} done)"); + return; + case TileState.Built: + Map.SetState(p.Tile, MapTileState.Built); + AddLog(Invariant($"{p.Tile.Name} built in {p.Elapsed.TotalSeconds:F1} s: {p.Message}")); + break; + case TileState.Failed: + Map.SetState(p.Tile, MapTileState.Failed); + AddLog($"{p.Tile.Name} failed: {p.Message}", warning: true); + break; + default: + AddLog($"{p.Tile.Name}: {p.Message}"); + break; + } + ProgressValue++; + } + + private void AddLog(string line, bool warning = false) + { + if (warning) Log.Warning($"Build Scenery: {line}"); + else Log.Info($"Build Scenery: {line}"); + BuildLog.Add($"{DateTime.Now:HH:mm:ss} {line}"); + while (BuildLog.Count > MaxLogLines) BuildLog.RemoveAt(0); + } + + internal static bool SamePath(string a, string b) + { + if (string.IsNullOrWhiteSpace(a) || string.IsNullOrWhiteSpace(b)) return false; + try + { + return string.Equals(Path.TrimEndingDirectorySeparator(Path.GetFullPath(a)), Path.TrimEndingDirectorySeparator(Path.GetFullPath(b)), + StringComparison.OrdinalIgnoreCase); + } + catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException) + { + return false; + } + } + + private static string Invariant(FormattableString text) => FormattableString.Invariant(text); +} diff --git a/src/OrthoStreamXP/Gui/ViewModels/MainViewModel.cs b/src/OrthoStreamXP/Gui/ViewModels/MainViewModel.cs index f626f72..3a7cf7c 100644 --- a/src/OrthoStreamXP/Gui/ViewModels/MainViewModel.cs +++ b/src/OrthoStreamXP/Gui/ViewModels/MainViewModel.cs @@ -70,6 +70,10 @@ public MainViewModel() Settings = new SettingsViewModel(this); Cache = new CacheViewModel(this); Packages = new PackagesViewModel(Mount, Preferences, MeshHttp, MeshInstalls, PackagesFolder); + // The Build tab sets the packages folder through the Settings page, so that page shows it and checks it as its own box does. + BuildScenery = new BuildSceneryViewModel(Mount, () => SettingsDocument.Load(SettingsDocument.DefaultPath).Get("xplane"), PackagesFolder, + folder => Settings.PackagesFolder = folder, new SceneryBuildPreferencesStore(SceneryBuildPreferencesStore.DefaultPath)); + PackagesPage = new PackagesPageViewModel(Packages, BuildScenery); Scenery = new SceneryViewModel(Mount, () => SettingsDocument.Load(SettingsDocument.DefaultPath).Get("xplane")); Airports = new AirportsViewModel(Mount, () => SettingsDocument.Load(SettingsDocument.DefaultPath).Get("xplane")); About = new AboutViewModel(); @@ -78,7 +82,7 @@ public MainViewModel() new NavItem("Home", "", Home), new NavItem("Settings", "", Settings), new NavItem("Cache", "", Cache), - new NavItem("Packages", "", Packages), + new NavItem("Packages", "", PackagesPage), new NavItem("X-Plane Custom Scenery", "", Scenery), new NavItem("Airports", "", Airports), new NavItem("Log", "", LogPage), @@ -105,6 +109,10 @@ public MainViewModel() public HttpClient MeshHttp { get; } = PackagesViewModel.CreateHttpClient(); /// One region install or delete at a time, from the Packages page or the setup. public InstallSlot MeshInstalls { get; } = new(); + /// Photo-terrain packages made from X-Plane's own Global Scenery, for the tiles picked on a map: the Packages page's Build tab. + public BuildSceneryViewModel BuildScenery { get; } + /// The Packages page: its Download and Build tabs. + public PackagesPageViewModel PackagesPage { get; } /// X-Plane's scenery_packs.ini, to switch packages on or off. public SceneryViewModel Scenery { get; } /// Flattens the terrain under an airport, one at a time, and undoes it. diff --git a/src/OrthoStreamXP/Gui/ViewModels/PackagesPageViewModel.cs b/src/OrthoStreamXP/Gui/ViewModels/PackagesPageViewModel.cs new file mode 100644 index 0000000..0ef1041 --- /dev/null +++ b/src/OrthoStreamXP/Gui/ViewModels/PackagesPageViewModel.cs @@ -0,0 +1,34 @@ +namespace OrthoStreamXP.Gui; + +/// +/// The Packages page: its "Build own packages" tab (scenery made from X-Plane's Global Scenery), first and open at the start, +/// and its Download tab (AutoOrtho's mesh regions). Only the open tab is brought up to date, when the page is shown or the +/// tab opened. +/// +internal sealed class PackagesPageViewModel(PackagesViewModel download, BuildSceneryViewModel build) : ObservableObject, IPage +{ + public const int BuildTab = 0; + public const int DownloadTab = 1; + + private int _tab = BuildTab; + + public PackagesViewModel Download { get; } = download; + + public BuildSceneryViewModel Build { get; } = build; + + /// The open tab, kept while the page is made again each time it is shown. + public int Tab + { + get => _tab; + set + { + if (Set(ref _tab, value)) OnShown(); + } + } + + public void OnShown() + { + if (Tab == BuildTab) Build.OnShown(); + else Download.OnShown(); + } +} diff --git a/src/OrthoStreamXP/Gui/ViewModels/SetupViewModel.cs b/src/OrthoStreamXP/Gui/ViewModels/SetupViewModel.cs index 485178b..92c1b3e 100644 --- a/src/OrthoStreamXP/Gui/ViewModels/SetupViewModel.cs +++ b/src/OrthoStreamXP/Gui/ViewModels/SetupViewModel.cs @@ -54,8 +54,11 @@ public SetupViewModel(MainViewModel main) _main = main; SettingsDocument existing = SettingsDocument.Load(SettingsDocument.DefaultPath); _winFsp = SystemCheck.WinFspInstalled(); - // Before the folders are chosen below: each choice tells it where regions would go. - Downloads = new PackagesViewModel(_main.Mount, _main.Preferences, _main.MeshHttp, _main.MeshInstalls, () => DownloadFolder, RegionInstalled); + // Before the folders are chosen below: each choice tells it where packages would be built. "Stream from here" and a + // build that made tiles both make that folder this setup's packages folder. + Builder = new BuildSceneryViewModel(_main.Mount, () => _xplane, () => BuildFolder, UsePackagesFolder, + new SceneryBuildPreferencesStore(SceneryBuildPreferencesStore.DefaultPath)); + Builder.TilesBuilt += (_, folder) => UsePackagesFolder(folder); XPlaneOptions = [.. SystemCheck.FindXPlaneFolders().Select(f => new FolderOption(f, "X-Plane found here", ChooseXPlane))]; // Which packages to use is the person's own choice: nothing is searched for, only the folder chosen before is offered. @@ -98,7 +101,12 @@ public SetupViewModel(MainViewModel main) Back = new RelayCommand(() => Step--, () => Step > 0); Next = new RelayCommand(() => Step++, () => Step < StepTitles.Length - 1 && CanLeave(Step)); Finish = new RelayCommand(() => _ = FinishAsync(), () => Step == StepTitles.Length - 1); - Cancel = new RelayCommand(_main.CloseSetup); + Cancel = new RelayCommand(() => + { + // A build started here does not go on unseen once the setup is closed. + if (Builder.Stop.CanExecute(null)) Builder.Stop.Execute(null); + _main.CloseSetup(); + }); CheckWinFsp = new RelayCommand(() => { _winFsp = SystemCheck.WinFspInstalled(); @@ -120,35 +128,35 @@ public SetupViewModel(MainViewModel main) { if (Shell.PickFolder("Choose a folder for the cache", CacheFolder) is { } folder) CacheFolder = folder; }); - ShowDownloads = new RelayCommand(() => + ShowBuilder = new RelayCommand(() => { - DownloadsShown = true; - Downloads.OnShown(); - }, () => !DownloadsShown); + BuilderShown = true; + Builder.OnShown(); + }, () => !BuilderShown); } - /// The regions of the mesh, for someone without scenery packages: installed into the folder chosen, or a suggested one. - public PackagesViewModel Downloads { get; } + /// + /// Photo-scenery packages built from X-Plane's own Global Scenery (the Packages page's Build tab), for someone without + /// scenery packages: built into the folder chosen, or a suggested one. + /// + public BuildSceneryViewModel Builder { get; } - public ICommand ShowDownloads { get; } + public ICommand ShowBuilder { get; } - public bool DownloadsShown + public bool BuilderShown { - get => _downloadsShown; - private set - { - if (Set(ref _downloadsShown, value)) Raise(nameof(PackagesMissing)); - } + get => _builderShown; + private set => Set(ref _builderShown, value); } - private bool _downloadsShown; + private bool _builderShown; /// The packages folder chosen, when it can hold packages; otherwise the one the setup suggests. - private string DownloadFolder => + private string BuildFolder => _packages is not null && XPlaneOk && !SystemCheck.IsInCustomScenery(_packages, _xplane) ? _packages : SystemCheck.SuggestedPackagesFolder(); - /// A region is installed: its folder becomes the packages folder, its card telling the packages now in it. - private void RegionInstalled(string folder) + /// Packages were built in a folder: it becomes the packages folder, its card telling the packages now in it. + private void UsePackagesFolder(string folder) { FolderOption? old = PackageOptions.FirstOrDefault(o => string.Equals(o.Path, folder, StringComparison.OrdinalIgnoreCase)); if (old is not null) PackageOptions.Remove(old); @@ -207,13 +215,6 @@ public int Step /// A folder was chosen and it has no packages (shown in red; before a choice the hint is just a hint). public bool PackagesWrong => _packages is not null && !PackagesOk; - /// - /// The folder chosen can be used but holds no packages: the download is offered right under the message, until the - /// list of regions is open. - /// - public bool PackagesMissing => - !DownloadsShown && _packages is not null && XPlaneOk && !SystemCheck.IsInCustomScenery(_packages, _xplane) && SystemCheck.PackagesIn(_packages).Count == 0; - public string PackagesHint { get @@ -227,7 +228,7 @@ public string PackagesHint IReadOnlyList found = SystemCheck.PackagesIn(_packages); if (found.Count == 0) return "That folder has no scenery packages: none of its folders has an Earth nav data folder. " + - "Choose the folder that holds your packages, not a package itself. No packages yet? Download a region below."; + "Choose the folder that holds your packages, not a package itself. No packages yet? Build your own below."; IReadOnlyList taken = SystemCheck.TakenInCustomScenery(_xplane, found); return taken.Count == 0 ? "OrthoStreamXP adds photos to these packages while it runs. They stay unchanged on disk." @@ -332,9 +333,8 @@ private void ChooseXPlane(FolderOption option) Raise(nameof(PackagesOk)); Raise(nameof(PackagesWrong)); Raise(nameof(PackagesHint)); - Raise(nameof(PackagesMissing)); Raise(nameof(Summary)); - Downloads.FolderChanged(); + if (BuilderShown) Builder.OnShown(); RelayCommand.Refresh(); } @@ -346,9 +346,8 @@ private void ChoosePackages(FolderOption option) Raise(nameof(PackagesOk)); Raise(nameof(PackagesWrong)); Raise(nameof(PackagesHint)); - Raise(nameof(PackagesMissing)); Raise(nameof(Summary)); - Downloads.FolderChanged(); + if (BuilderShown) Builder.OnShown(); RelayCommand.Refresh(); } diff --git a/src/OrthoStreamXP/Gui/Views/BuildSceneryView.xaml b/src/OrthoStreamXP/Gui/Views/BuildSceneryView.xaml new file mode 100644 index 0000000..e5c440d --- /dev/null +++ b/src/OrthoStreamXP/Gui/Views/BuildSceneryView.xaml @@ -0,0 +1,241 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + © OpenStreetMap contributors + + + + + + + + + + + + + +